code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
using System; using System.Web; using RequestReduce.Api; using RequestReduce.Configuration; using RequestReduce.ResourceTypes; using RequestReduce.IOC; namespace RequestReduce.Utilities { public interface IUriBuilder { string BuildResourceUrl<T>(Guid key, byte[] bytes) where T : IResourceType; string BuildResourceUrl<T>(Guid key, string signature) where T : IResourceType; string BuildResourceUrl(Guid key, byte[] bytes, Type type); string BuildResourceUrl(Guid key, string signature, Type resourceType); string BuildSpriteUrl(Guid key, byte[] bytes); string ParseFileName(string url); Guid ParseKey(string url); string ParseSignature(string url); } public class UriBuilder : IUriBuilder { private readonly IRRConfiguration configuration; public UriBuilder(IRRConfiguration configuration) { this.configuration = configuration; } public string BuildResourceUrl(Guid key, byte[] bytes, Type type) { return BuildResourceUrl(key, Hasher.Hash(bytes).RemoveDashes(), type); } public string BuildResourceUrl<T>(Guid key, byte[] bytes) where T : IResourceType { return BuildResourceUrl<T>(key, bytes.Length > 0 ? Hasher.Hash(bytes).RemoveDashes() : Guid.Empty.RemoveDashes()); } public string BuildResourceUrl<T>(Guid key, string signature) where T : IResourceType { return BuildResourceUrl(key, signature, typeof(T)); } public string BuildResourceUrl(Guid key, string signature, Type resourceType) { var resource = RRContainer.Current.GetInstance(resourceType) as IResourceType; if (resource == null) throw new ArgumentException("resourceType must derrive from IResourceType", "resourceType"); var url = string.Format("{0}{1}/{2}-{3}-{4}", configuration.ContentHost, configuration.ResourceAbsolutePath, key.RemoveDashes(), signature, resource.FileName); return Registry.UrlTransformer != null ? Registry.UrlTransformer(RRContainer.Current.GetInstance<HttpContextBase>(), null, url) : url; } public string BuildSpriteUrl(Guid key, byte[] bytes) { var url = string.Format("{0}{1}/{2}-{3}.png", configuration.ContentHost, configuration.ResourceAbsolutePath, key.RemoveDashes(), Hasher.Hash(bytes).RemoveDashes()); return Registry.UrlTransformer != null ? Registry.UrlTransformer(RRContainer.Current.GetInstance<HttpContextBase>(), null, url) : url; } public string ParseFileName(string url) { if (string.IsNullOrEmpty(url)) return null; return string.IsNullOrEmpty(url.Trim()) ? null : url.Substring(url.LastIndexOf('/') + 1); } public Guid ParseKey(string url) { if (string.IsNullOrEmpty(url)) return Guid.Empty; var idx = url.LastIndexOf('/'); var keyDir = idx > -1 ? url.Substring(idx + 1) : url; var strKey = string.Empty; idx = keyDir.IndexOf('-'); if (idx > -1) strKey = keyDir.Substring(0, idx); try { return new Guid(strKey); } catch (FormatException) { return Guid.Empty; } } public string ParseSignature(string url) { if (string.IsNullOrEmpty(url) || string.IsNullOrEmpty(url.Trim())) return Guid.Empty.RemoveDashes(); var idx = url.LastIndexOf('/'); var keyDir = idx > -1 ? url.Substring(idx + 1) : url; try { var strKey = keyDir.Substring(33, 32); return new Guid(strKey).RemoveDashes(); } catch (Exception) { return Guid.Empty.RemoveDashes(); } } } }
mwrock/RequestReduce
RequestReduce/Utilities/UriBuilder.cs
C#
apache-2.0
4,295
package com.lixia.rdp.crypto; /** * This class implements the MD5 message digest algorithm. * <p> * <b>BUG</b>: The update method is missing. * <p> * <b>References:</b> * <ol> * <li> Ronald L. Rivest, * "<a href="http://www.roxen.com/rfc/rfc1321.html"> * The MD5 Message-Digest Algorithm</a>", * IETF RFC-1321 (informational). * <li> Bruce Schneier, * "Section 18.5 MD5," * <cite>Applied Cryptography, 2nd edition</cite>, * John Wiley &amp; Sons, 1996 * <p> * </ol> * <p> * <b>Copyright</b> &copy; 1995-1997 * <a href="http://www.systemics.com/">Systemics Ltd</a> on behalf of the * <a href="http://www.systemics.com/docs/cryptix/">Cryptix Development Team</a>. * <br>All rights reserved. * <p> * <b>$Revision: 1.1.1.1 $</b> * @author Systemics Ltd * @author David Hopwood * @since Cryptix 2.2 */ public final class MD5 extends BlockMessageDigest implements Cloneable { // MD5 constants and variables //........................................................................... /** Length of the final hash (in bytes). */ private static final int HASH_LENGTH = 16; /** Length of a block (the number of bytes hashed in every transform). */ private static final int DATA_LENGTH = 64; private int[] data; private int[] digest; private byte[] tmp; /** Returns the length of the hash (in bytes). */ protected int engineGetDigestLength() { return HASH_LENGTH; } /** Returns the length of the data (in bytes) hashed in every transform. */ protected int engineGetDataLength() { return DATA_LENGTH; } /** * The public constructor. */ public MD5() { super("MD5"); java_init(); engineReset(); } private void java_init() { digest = new int[HASH_LENGTH/4]; data = new int[DATA_LENGTH/4]; tmp = new byte[DATA_LENGTH]; } /** * This constructor is here to implement cloneability of this class. */ private MD5 (MD5 md) { this(); data = (int[])md.data.clone(); digest = (int[])md.digest.clone(); tmp = (byte[])md.tmp.clone(); } /** * Returns a copy of this MD object. */ public Object clone() { return new MD5(this); } /** * Initializes (resets) the message digest. */ public void engineReset() { super.engineReset(); java_reset(); } private void java_reset() { digest[0] = 0x67452301; digest[1] = 0xEFCDAB89; digest[2] = 0x98BADCFE; digest[3] = 0x10325476; } /** * Adds data to the message digest. * * @param data The data to be added. * @param offset The start of the data in the array. * @param length The amount of data to add. */ protected void engineTransform(byte[] in) { java_transform(in); } private void java_transform(byte[] in) { byte2int(in, 0, data, 0, DATA_LENGTH/4); transform(data); } /** * Returns the digest of the data added and resets the digest. * @return the digest of all the data added to the message digest as a byte array. */ public byte[] engineDigest(byte[] in, int length) { byte b[] = java_digest(in, length); engineReset(); return b; } private byte[] java_digest(byte[] in, int pos) { if (pos != 0) System.arraycopy(in, 0, tmp, 0, pos); tmp[pos++] = -128; // (byte)0x80; if (pos > DATA_LENGTH - 8) { while (pos < DATA_LENGTH) tmp[pos++] = 0; byte2int(tmp, 0, data, 0, DATA_LENGTH/4); transform(data); pos = 0; } while (pos < DATA_LENGTH - 8) tmp[pos++] = 0; byte2int(tmp, 0, data, 0, (DATA_LENGTH/4)-2); int bc = bitcount(); data[14] = bc; data[15] = 0; transform(data); byte buf[] = new byte[HASH_LENGTH]; // Little endian int off = 0; for (int i = 0; i < HASH_LENGTH/4; ++i) { int d = digest[i]; buf[off++] = (byte) d; buf[off++] = (byte) (d>>>8); buf[off++] = (byte) (d>>>16); buf[off++] = (byte) (d>>>24); } return buf; } // MD5 transform routines //........................................................................... static protected int F(int x,int y,int z) { return (z ^ (x & (y^z))); } static protected int G(int x,int y,int z) { return (y ^ (z & (x^y))); } static protected int H(int x,int y,int z) { return (x ^ y ^ z); } static protected int I(int x,int y,int z) { return (y ^ (x | ~z)); } static protected int FF(int a,int b,int c,int d,int k,int s,int t) { a += k+t+F(b,c,d); a = (a << s | a >>> -s); return a+b; } static protected int GG(int a,int b,int c,int d,int k,int s,int t) { a += k+t+G(b,c,d); a = (a << s | a >>> -s); return a+b; } static protected int HH(int a,int b,int c,int d,int k,int s,int t) { a += k+t+H(b,c,d); a = (a << s | a >>> -s); return a+b; } static protected int II(int a,int b,int c,int d,int k,int s,int t) { a += k+t+I(b,c,d); a = (a << s | a >>> -s); return a+b; } protected void transform (int M[]) { int a,b,c,d; a = digest[0]; b = digest[1]; c = digest[2]; d = digest[3]; a = FF(a,b,c,d,M[ 0], 7,0xd76aa478); d = FF(d,a,b,c,M[ 1],12,0xe8c7b756); c = FF(c,d,a,b,M[ 2],17,0x242070db); b = FF(b,c,d,a,M[ 3],22,0xc1bdceee); a = FF(a,b,c,d,M[ 4], 7,0xf57c0faf); d = FF(d,a,b,c,M[ 5],12,0x4787c62a); c = FF(c,d,a,b,M[ 6],17,0xa8304613); b = FF(b,c,d,a,M[ 7],22,0xfd469501); a = FF(a,b,c,d,M[ 8], 7,0x698098d8); d = FF(d,a,b,c,M[ 9],12,0x8b44f7af); c = FF(c,d,a,b,M[10],17,0xffff5bb1); b = FF(b,c,d,a,M[11],22,0x895cd7be); a = FF(a,b,c,d,M[12], 7,0x6b901122); d = FF(d,a,b,c,M[13],12,0xfd987193); c = FF(c,d,a,b,M[14],17,0xa679438e); b = FF(b,c,d,a,M[15],22,0x49b40821); a = GG(a,b,c,d,M[ 1], 5,0xf61e2562); d = GG(d,a,b,c,M[ 6], 9,0xc040b340); c = GG(c,d,a,b,M[11],14,0x265e5a51); b = GG(b,c,d,a,M[ 0],20,0xe9b6c7aa); a = GG(a,b,c,d,M[ 5], 5,0xd62f105d); d = GG(d,a,b,c,M[10], 9,0x02441453); c = GG(c,d,a,b,M[15],14,0xd8a1e681); b = GG(b,c,d,a,M[ 4],20,0xe7d3fbc8); a = GG(a,b,c,d,M[ 9], 5,0x21e1cde6); d = GG(d,a,b,c,M[14], 9,0xc33707d6); c = GG(c,d,a,b,M[ 3],14,0xf4d50d87); b = GG(b,c,d,a,M[ 8],20,0x455a14ed); a = GG(a,b,c,d,M[13], 5,0xa9e3e905); d = GG(d,a,b,c,M[ 2], 9,0xfcefa3f8); c = GG(c,d,a,b,M[ 7],14,0x676f02d9); b = GG(b,c,d,a,M[12],20,0x8d2a4c8a); a = HH(a,b,c,d,M[ 5], 4,0xfffa3942); d = HH(d,a,b,c,M[ 8],11,0x8771f681); c = HH(c,d,a,b,M[11],16,0x6d9d6122); b = HH(b,c,d,a,M[14],23,0xfde5380c); a = HH(a,b,c,d,M[ 1], 4,0xa4beea44); d = HH(d,a,b,c,M[ 4],11,0x4bdecfa9); c = HH(c,d,a,b,M[ 7],16,0xf6bb4b60); b = HH(b,c,d,a,M[10],23,0xbebfbc70); a = HH(a,b,c,d,M[13], 4,0x289b7ec6); d = HH(d,a,b,c,M[ 0],11,0xeaa127fa); c = HH(c,d,a,b,M[ 3],16,0xd4ef3085); b = HH(b,c,d,a,M[ 6],23,0x04881d05); a = HH(a,b,c,d,M[ 9], 4,0xd9d4d039); d = HH(d,a,b,c,M[12],11,0xe6db99e5); c = HH(c,d,a,b,M[15],16,0x1fa27cf8); b = HH(b,c,d,a,M[ 2],23,0xc4ac5665); a = II(a,b,c,d,M[ 0], 6,0xf4292244); d = II(d,a,b,c,M[ 7],10,0x432aff97); c = II(c,d,a,b,M[14],15,0xab9423a7); b = II(b,c,d,a,M[ 5],21,0xfc93a039); a = II(a,b,c,d,M[12], 6,0x655b59c3); d = II(d,a,b,c,M[ 3],10,0x8f0ccc92); c = II(c,d,a,b,M[10],15,0xffeff47d); b = II(b,c,d,a,M[ 1],21,0x85845dd1); a = II(a,b,c,d,M[ 8], 6,0x6fa87e4f); d = II(d,a,b,c,M[15],10,0xfe2ce6e0); c = II(c,d,a,b,M[ 6],15,0xa3014314); b = II(b,c,d,a,M[13],21,0x4e0811a1); a = II(a,b,c,d,M[ 4], 6,0xf7537e82); d = II(d,a,b,c,M[11],10,0xbd3af235); c = II(c,d,a,b,M[ 2],15,0x2ad7d2bb); b = II(b,c,d,a,M[ 9],21,0xeb86d391); digest[0] += a; digest[1] += b; digest[2] += c; digest[3] += d; } // why was this public? // Note: parameter order changed to be consistent with System.arraycopy. private static void byte2int(byte[] src, int srcOffset, int[] dst, int dstOffset, int length) { while (length-- > 0) { // Little endian dst[dstOffset++] = (src[srcOffset++] & 0xFF) | ((src[srcOffset++] & 0xFF) << 8) | ((src[srcOffset++] & 0xFF) << 16) | ((src[srcOffset++] & 0xFF) << 24); } } }
infinitiessoft/skyport-websockify
src/main/java/com/lixia/rdp/crypto/MD5.java
Java
apache-2.0
9,477
<!DOCTYPE html> <!-- Template Name: Metronic - Responsive Admin Dashboard Template build with Twitter Bootstrap 3.3.2 Version: 3.7.0 Author: KeenThemes Website: http://www.keenthemes.com/ Contact: support@keenthemes.com Follow: www.twitter.com/keenthemes Like: www.facebook.com/keenthemes Purchase: http://themeforest.net/item/metronic-responsive-admin-dashboard-template/4021469?ref=keenthemes License: You must have a valid license purchased only from themeforest(the above link) in order to legally use the theme for your project. --> <!--[if IE 8]> <html lang="en" class="ie8 no-js"> <![endif]--> <!--[if IE 9]> <html lang="en" class="ie9 no-js"> <![endif]--> <!--[if !IE]><!--> <html lang="en"> <!--<![endif]--> <!-- BEGIN HEAD --> <head> <meta charset="utf-8"/> <title>Metronic | UI Features - Tiles</title> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta content="width=device-width, initial-scale=1.0" name="viewport"/> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <meta content="" name="description"/> <meta content="" name="author"/> <!-- BEGIN GLOBAL MANDATORY STYLES --> <link href="http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700&subset=all" rel="stylesheet" type="text/css"> <link href="../../assets/global/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link href="../../assets/global/plugins/simple-line-icons/simple-line-icons.min.css" rel="stylesheet" type="text/css"> <link href="../../assets/global/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css"> <link href="../../assets/global/plugins/uniform/css/uniform.default.css" rel="stylesheet" type="text/css"> <link href="../../assets/global/plugins/bootstrap-switch/css/bootstrap-switch.min.css" rel="stylesheet" type="text/css"/> <!-- END GLOBAL MANDATORY STYLES --> <!-- BEGIN THEME STYLES --> <link href="../../assets/global/css/components-md.css" id="style_components" rel="stylesheet" type="text/css"/> <link href="../../assets/global/css/plugins-md.css" rel="stylesheet" type="text/css"/> <link href="../../assets/admin/layout2/css/layout.css" rel="stylesheet" type="text/css"/> <link id="style_color" href="../../assets/admin/layout2/css/themes/grey.css" rel="stylesheet" type="text/css"/> <link href="../../assets/admin/layout2/css/custom.css" rel="stylesheet" type="text/css"/> <!-- END THEME STYLES --> <link rel="shortcut icon" href="favicon.ico"/> </head> <!-- BEGIN BODY --> <!-- DOC: Apply "page-header-fixed-mobile" and "page-footer-fixed-mobile" class to body element to force fixed header or footer in mobile devices --> <!-- DOC: Apply "page-sidebar-closed" class to the body and "page-sidebar-menu-closed" class to the sidebar menu element to hide the sidebar by default --> <!-- DOC: Apply "page-sidebar-hide" class to the body to make the sidebar completely hidden on toggle --> <!-- DOC: Apply "page-sidebar-closed-hide-logo" class to the body element to make the logo hidden on sidebar toggle --> <!-- DOC: Apply "page-sidebar-hide" class to body element to completely hide the sidebar on sidebar toggle --> <!-- DOC: Apply "page-sidebar-fixed" class to have fixed sidebar --> <!-- DOC: Apply "page-footer-fixed" class to the body element to have fixed footer --> <!-- DOC: Apply "page-sidebar-reversed" class to put the sidebar on the right side --> <!-- DOC: Apply "page-full-width" class to the body element to have full width page without the sidebar menu --> <body class="page-md page-boxed page-header-fixed page-container-bg-solid page-sidebar-closed-hide-logo "> <!-- BEGIN HEADER --> <div class="page-header md-shadow-z-1-i navbar navbar-fixed-top"> <!-- BEGIN HEADER INNER --> <div class="page-header-inner container"> <!-- BEGIN LOGO --> <div class="page-logo"> <a href="index.html"> <img src="../../assets/admin/layout2/img/logo-default.png" alt="logo" class="logo-default"/> </a> <div class="menu-toggler sidebar-toggler"> <!-- DOC: Remove the above "hide" to enable the sidebar toggler button on header --> </div> </div> <!-- END LOGO --> <!-- BEGIN RESPONSIVE MENU TOGGLER --> <a href="javascript:;" class="menu-toggler responsive-toggler" data-toggle="collapse" data-target=".navbar-collapse"> </a> <!-- END RESPONSIVE MENU TOGGLER --> <!-- BEGIN PAGE ACTIONS --> <!-- DOC: Remove "hide" class to enable the page header actions --> <div class="page-actions hide"> <div class="btn-group"> <button type="button" class="btn btn-circle red-pink dropdown-toggle" data-toggle="dropdown"> <i class="icon-bar-chart"></i>&nbsp;<span class="hidden-sm hidden-xs">New&nbsp;</span>&nbsp;<i class="fa fa-angle-down"></i> </button> <ul class="dropdown-menu" role="menu"> <li> <a href="javascript:;"> <i class="icon-user"></i> New User </a> </li> <li> <a href="javascript:;"> <i class="icon-present"></i> New Event <span class="badge badge-success">4</span> </a> </li> <li> <a href="javascript:;"> <i class="icon-basket"></i> New order </a> </li> <li class="divider"> </li> <li> <a href="javascript:;"> <i class="icon-flag"></i> Pending Orders <span class="badge badge-danger">4</span> </a> </li> <li> <a href="javascript:;"> <i class="icon-users"></i> Pending Users <span class="badge badge-warning">12</span> </a> </li> </ul> </div> <div class="btn-group"> <button type="button" class="btn btn-circle green-haze dropdown-toggle" data-toggle="dropdown"> <i class="icon-bell"></i>&nbsp;<span class="hidden-sm hidden-xs">Post&nbsp;</span>&nbsp;<i class="fa fa-angle-down"></i> </button> <ul class="dropdown-menu" role="menu"> <li> <a href="javascript:;"> <i class="icon-docs"></i> New Post </a> </li> <li> <a href="javascript:;"> <i class="icon-tag"></i> New Comment </a> </li> <li> <a href="javascript:;"> <i class="icon-share"></i> Share </a> </li> <li class="divider"> </li> <li> <a href="javascript:;"> <i class="icon-flag"></i> Comments <span class="badge badge-success">4</span> </a> </li> <li> <a href="javascript:;"> <i class="icon-users"></i> Feedbacks <span class="badge badge-danger">2</span> </a> </li> </ul> </div> </div> <!-- END PAGE ACTIONS --> <!-- BEGIN PAGE TOP --> <div class="page-top"> <!-- BEGIN HEADER SEARCH BOX --> <!-- DOC: Apply "search-form-expanded" right after the "search-form" class to have half expanded search box --> <form class="search-form search-form-expanded" action="extra_search.html" method="GET"> <div class="input-group"> <input type="text" class="form-control" placeholder="Search..." name="query"> <span class="input-group-btn"> <a href="javascript:;" class="btn submit"><i class="icon-magnifier"></i></a> </span> </div> </form> <!-- END HEADER SEARCH BOX --> <!-- BEGIN TOP NAVIGATION MENU --> <div class="top-menu"> <ul class="nav navbar-nav pull-right"> <!-- BEGIN NOTIFICATION DROPDOWN --> <!-- DOC: Apply "dropdown-dark" class after below "dropdown-extended" to change the dropdown styte --> <li class="dropdown dropdown-extended dropdown-notification" id="header_notification_bar"> <a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true"> <i class="icon-bell"></i> <span class="badge badge-default"> 7 </span> </a> <ul class="dropdown-menu"> <li class="external"> <h3><span class="bold">12 pending</span> notifications</h3> <a href="extra_profile.html">view all</a> </li> <li> <ul class="dropdown-menu-list scroller" style="height: 250px;" data-handle-color="#637283"> <li> <a href="javascript:;"> <span class="time">just now</span> <span class="details"> <span class="label label-sm label-icon label-success"> <i class="fa fa-plus"></i> </span> New user registered. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">3 mins</span> <span class="details"> <span class="label label-sm label-icon label-danger"> <i class="fa fa-bolt"></i> </span> Server #12 overloaded. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">10 mins</span> <span class="details"> <span class="label label-sm label-icon label-warning"> <i class="fa fa-bell-o"></i> </span> Server #2 not responding. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">14 hrs</span> <span class="details"> <span class="label label-sm label-icon label-info"> <i class="fa fa-bullhorn"></i> </span> Application error. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">2 days</span> <span class="details"> <span class="label label-sm label-icon label-danger"> <i class="fa fa-bolt"></i> </span> Database overloaded 68%. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">3 days</span> <span class="details"> <span class="label label-sm label-icon label-danger"> <i class="fa fa-bolt"></i> </span> A user IP blocked. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">4 days</span> <span class="details"> <span class="label label-sm label-icon label-warning"> <i class="fa fa-bell-o"></i> </span> Storage Server #4 not responding dfdfdfd. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">5 days</span> <span class="details"> <span class="label label-sm label-icon label-info"> <i class="fa fa-bullhorn"></i> </span> System Error. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">9 days</span> <span class="details"> <span class="label label-sm label-icon label-danger"> <i class="fa fa-bolt"></i> </span> Storage server failed. </span> </a> </li> </ul> </li> </ul> </li> <!-- END NOTIFICATION DROPDOWN --> <!-- BEGIN INBOX DROPDOWN --> <!-- DOC: Apply "dropdown-dark" class after below "dropdown-extended" to change the dropdown styte --> <li class="dropdown dropdown-extended dropdown-inbox" id="header_inbox_bar"> <a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true"> <i class="icon-envelope-open"></i> <span class="badge badge-default"> 4 </span> </a> <ul class="dropdown-menu"> <li class="external"> <h3>You have <span class="bold">7 New</span> Messages</h3> <a href="page_inbox.html">view all</a> </li> <li> <ul class="dropdown-menu-list scroller" style="height: 275px;" data-handle-color="#637283"> <li> <a href="inbox.html?a=view"> <span class="photo"> <img src="../../assets/admin/layout3/img/avatar2.jpg" class="img-circle" alt=""> </span> <span class="subject"> <span class="from"> Lisa Wong </span> <span class="time">Just Now </span> </span> <span class="message"> Vivamus sed auctor nibh congue nibh. auctor nibh auctor nibh... </span> </a> </li> <li> <a href="inbox.html?a=view"> <span class="photo"> <img src="../../assets/admin/layout3/img/avatar3.jpg" class="img-circle" alt=""> </span> <span class="subject"> <span class="from"> Richard Doe </span> <span class="time">16 mins </span> </span> <span class="message"> Vivamus sed congue nibh auctor nibh congue nibh. auctor nibh auctor nibh... </span> </a> </li> <li> <a href="inbox.html?a=view"> <span class="photo"> <img src="../../assets/admin/layout3/img/avatar1.jpg" class="img-circle" alt=""> </span> <span class="subject"> <span class="from"> Bob Nilson </span> <span class="time">2 hrs </span> </span> <span class="message"> Vivamus sed nibh auctor nibh congue nibh. auctor nibh auctor nibh... </span> </a> </li> <li> <a href="inbox.html?a=view"> <span class="photo"> <img src="../../assets/admin/layout3/img/avatar2.jpg" class="img-circle" alt=""> </span> <span class="subject"> <span class="from"> Lisa Wong </span> <span class="time">40 mins </span> </span> <span class="message"> Vivamus sed auctor 40% nibh congue nibh... </span> </a> </li> <li> <a href="inbox.html?a=view"> <span class="photo"> <img src="../../assets/admin/layout3/img/avatar3.jpg" class="img-circle" alt=""> </span> <span class="subject"> <span class="from"> Richard Doe </span> <span class="time">46 mins </span> </span> <span class="message"> Vivamus sed congue nibh auctor nibh congue nibh. auctor nibh auctor nibh... </span> </a> </li> </ul> </li> </ul> </li> <!-- END INBOX DROPDOWN --> <!-- BEGIN TODO DROPDOWN --> <!-- DOC: Apply "dropdown-dark" class after below "dropdown-extended" to change the dropdown styte --> <li class="dropdown dropdown-extended dropdown-tasks" id="header_task_bar"> <a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true"> <i class="icon-calendar"></i> <span class="badge badge-default"> 3 </span> </a> <ul class="dropdown-menu extended tasks"> <li class="external"> <h3>You have <span class="bold">12 pending</span> tasks</h3> <a href="page_todo.html">view all</a> </li> <li> <ul class="dropdown-menu-list scroller" style="height: 275px;" data-handle-color="#637283"> <li> <a href="javascript:;"> <span class="task"> <span class="desc">New release v1.2 </span> <span class="percent">30%</span> </span> <span class="progress"> <span style="width: 40%;" class="progress-bar progress-bar-success" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">40% Complete</span></span> </span> </a> </li> <li> <a href="javascript:;"> <span class="task"> <span class="desc">Application deployment</span> <span class="percent">65%</span> </span> <span class="progress"> <span style="width: 65%;" class="progress-bar progress-bar-danger" aria-valuenow="65" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">65% Complete</span></span> </span> </a> </li> <li> <a href="javascript:;"> <span class="task"> <span class="desc">Mobile app release</span> <span class="percent">98%</span> </span> <span class="progress"> <span style="width: 98%;" class="progress-bar progress-bar-success" aria-valuenow="98" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">98% Complete</span></span> </span> </a> </li> <li> <a href="javascript:;"> <span class="task"> <span class="desc">Database migration</span> <span class="percent">10%</span> </span> <span class="progress"> <span style="width: 10%;" class="progress-bar progress-bar-warning" aria-valuenow="10" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">10% Complete</span></span> </span> </a> </li> <li> <a href="javascript:;"> <span class="task"> <span class="desc">Web server upgrade</span> <span class="percent">58%</span> </span> <span class="progress"> <span style="width: 58%;" class="progress-bar progress-bar-info" aria-valuenow="58" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">58% Complete</span></span> </span> </a> </li> <li> <a href="javascript:;"> <span class="task"> <span class="desc">Mobile development</span> <span class="percent">85%</span> </span> <span class="progress"> <span style="width: 85%;" class="progress-bar progress-bar-success" aria-valuenow="85" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">85% Complete</span></span> </span> </a> </li> <li> <a href="javascript:;"> <span class="task"> <span class="desc">New UI release</span> <span class="percent">38%</span> </span> <span class="progress progress-striped"> <span style="width: 38%;" class="progress-bar progress-bar-important" aria-valuenow="18" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">38% Complete</span></span> </span> </a> </li> </ul> </li> </ul> </li> <!-- END TODO DROPDOWN --> <!-- BEGIN USER LOGIN DROPDOWN --> <!-- DOC: Apply "dropdown-dark" class after below "dropdown-extended" to change the dropdown styte --> <li class="dropdown dropdown-user"> <a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true"> <img alt="" class="img-circle" src="../../assets/admin/layout2/img/avatar3_small.jpg"/> <span class="username username-hide-on-mobile"> Nick </span> <i class="fa fa-angle-down"></i> </a> <ul class="dropdown-menu dropdown-menu-default"> <li> <a href="extra_profile.html"> <i class="icon-user"></i> My Profile </a> </li> <li> <a href="page_calendar.html"> <i class="icon-calendar"></i> My Calendar </a> </li> <li> <a href="inbox.html"> <i class="icon-envelope-open"></i> My Inbox <span class="badge badge-danger"> 3 </span> </a> </li> <li> <a href="page_todo.html"> <i class="icon-rocket"></i> My Tasks <span class="badge badge-success"> 7 </span> </a> </li> <li class="divider"> </li> <li> <a href="extra_lock.html"> <i class="icon-lock"></i> Lock Screen </a> </li> <li> <a href="login.html"> <i class="icon-key"></i> Log Out </a> </li> </ul> </li> <!-- END USER LOGIN DROPDOWN --> </ul> </div> <!-- END TOP NAVIGATION MENU --> </div> <!-- END PAGE TOP --> </div> <!-- END HEADER INNER --> </div> <!-- END HEADER --> <div class="clearfix"> </div> <div class="container"> <!-- BEGIN CONTAINER --> <div class="page-container"> <!-- BEGIN SIDEBAR --> <div class="page-sidebar-wrapper"> <!-- DOC: Set data-auto-scroll="false" to disable the sidebar from auto scrolling/focusing --> <!-- DOC: Change data-auto-speed="200" to adjust the sub menu slide up/down speed --> <div class="page-sidebar navbar-collapse collapse"> <!-- BEGIN SIDEBAR MENU --> <!-- DOC: Apply "page-sidebar-menu-light" class right after "page-sidebar-menu" to enable light sidebar menu style(without borders) --> <!-- DOC: Apply "page-sidebar-menu-hover-submenu" class right after "page-sidebar-menu" to enable hoverable(hover vs accordion) sub menu mode --> <!-- DOC: Apply "page-sidebar-menu-closed" class right after "page-sidebar-menu" to collapse("page-sidebar-closed" class must be applied to the body element) the sidebar sub menu mode --> <!-- DOC: Set data-auto-scroll="false" to disable the sidebar from auto scrolling/focusing --> <!-- DOC: Set data-keep-expand="true" to keep the submenues expanded --> <!-- DOC: Set data-auto-speed="200" to adjust the sub menu slide up/down speed --> <ul class="page-sidebar-menu page-sidebar-menu-hover-submenu " data-keep-expanded="false" data-auto-scroll="true" data-slide-speed="200"> <li class="start "> <a href="index.html"> <i class="icon-home"></i> <span class="title">Dashboard</span> </a> </li> <li> <a href="javascript:;"> <i class="icon-basket"></i> <span class="title">eCommerce</span> <span class="arrow "></span> </a> <ul class="sub-menu"> <li> <a href="ecommerce_index.html"> <i class="icon-home"></i> Dashboard</a> </li> <li> <a href="ecommerce_orders.html"> <i class="icon-basket"></i> Orders</a> </li> <li> <a href="ecommerce_orders_view.html"> <i class="icon-tag"></i> Order View</a> </li> <li> <a href="ecommerce_products.html"> <i class="icon-handbag"></i> Products</a> </li> <li> <a href="ecommerce_products_edit.html"> <i class="icon-pencil"></i> Product Edit</a> </li> </ul> </li> <li> <a href="javascript:;"> <i class="icon-rocket"></i> <span class="title">Page Layouts</span> <span class="arrow "></span> </a> <ul class="sub-menu"> <li> <a href="layout_fontawesome_icons.html"> <span class="badge badge-roundless badge-danger">new</span>Layout with Fontawesome Icons</a> </li> <li> <a href="layout_glyphicons.html"> Layout with Glyphicon</a> </li> <li> <a href="layout_full_height_content.html"> <span class="badge badge-roundless badge-warning">new</span>Full Height Content</a> </li> <li> <a href="layout_sidebar_reversed.html"> <span class="badge badge-roundless badge-warning">new</span>Right Sidebar Page</a> </li> <li> <a href="layout_sidebar_fixed.html"> Sidebar Fixed Page</a> </li> <li> <a href="layout_sidebar_closed.html"> Sidebar Closed Page</a> </li> <li> <a href="layout_ajax.html"> Content Loading via Ajax</a> </li> <li> <a href="layout_disabled_menu.html"> Disabled Menu Links</a> </li> <li> <a href="layout_blank_page.html"> Blank Page</a> </li> <li> <a href="layout_fluid_page.html"> Fluid Page</a> </li> <li> <a href="layout_language_bar.html"> Language Switch Bar</a> </li> </ul> </li> <li class="active open"> <a href="javascript:;"> <i class="icon-diamond"></i> <span class="title">UI Features</span> <span class="selected"></span> <span class="arrow open"></span> </a> <ul class="sub-menu"> <li> <a href="ui_general.html"> General Components</a> </li> <li> <a href="ui_buttons.html"> Buttons</a> </li> <li> <a href="ui_icons.html"> <span class="badge badge-roundless badge-danger">new</span>Font Icons</a> </li> <li> <a href="ui_colors.html"> Flat UI Colors</a> </li> <li> <a href="ui_typography.html"> Typography</a> </li> <li> <a href="ui_tabs_accordions_navs.html"> Tabs, Accordions & Navs</a> </li> <li> <a href="ui_tree.html"> <span class="badge badge-roundless badge-danger">new</span>Tree View</a> </li> <li> <a href="ui_page_progress_style_1.html"> <span class="badge badge-roundless badge-warning">new</span>Page Progress Bar</a> </li> <li> <a href="ui_blockui.html"> Block UI</a> </li> <li> <a href="ui_bootstrap_growl.html"> <span class="badge badge-roundless badge-warning">new</span>Bootstrap Growl Notifications</a> </li> <li> <a href="ui_notific8.html"> Notific8 Notifications</a> </li> <li> <a href="ui_toastr.html"> Toastr Notifications</a> </li> <li> <a href="ui_alert_dialog_api.html"> <span class="badge badge-roundless badge-danger">new</span>Alerts & Dialogs API</a> </li> <li> <a href="ui_session_timeout.html"> Session Timeout</a> </li> <li> <a href="ui_idle_timeout.html"> User Idle Timeout</a> </li> <li> <a href="ui_modals.html"> Modals</a> </li> <li> <a href="ui_extended_modals.html"> Extended Modals</a> </li> <li class="active"> <a href="ui_tiles.html"> Tiles</a> </li> <li> <a href="ui_datepaginator.html"> <span class="badge badge-roundless badge-success">new</span>Date Paginator</a> </li> <li> <a href="ui_nestable.html"> Nestable List</a> </li> </ul> </li> <li> <a href="javascript:;"> <i class="icon-puzzle"></i> <span class="title">UI Components</span> <span class="arrow "></span> </a> <ul class="sub-menu"> <li> <a href="components_pickers.html"> Date & Time Pickers</a> </li> <li> <a href="components_context_menu.html"> Context Menu</a> </li> <li> <a href="components_dropdowns.html"> Custom Dropdowns</a> </li> <li> <a href="components_form_tools.html"> Form Widgets & Tools</a> </li> <li> <a href="components_form_tools2.html"> Form Widgets & Tools 2</a> </li> <li> <a href="components_editors.html"> Markdown & WYSIWYG Editors</a> </li> <li> <a href="components_ion_sliders.html"> Ion Range Sliders</a> </li> <li> <a href="components_noui_sliders.html"> NoUI Range Sliders</a> </li> <li> <a href="components_jqueryui_sliders.html"> jQuery UI Sliders</a> </li> <li> <a href="components_knob_dials.html"> Knob Circle Dials</a> </li> </ul> </li> <!-- BEGIN ANGULARJS LINK --> <li class="tooltips" data-container="body" data-placement="right" data-html="true" data-original-title="AngularJS version demo"> <a href="angularjs" target="_blank"> <i class="icon-paper-plane"></i> <span class="title"> AngularJS Version </span> </a> </li> <!-- END ANGULARJS LINK --> <li> <a href="javascript:;"> <i class="icon-settings"></i> <span class="title">Form Stuff</span> <span class="arrow "></span> </a> <ul class="sub-menu"> <li> <a href="form_controls_md.html"> <span class="badge badge-roundless badge-danger">new</span>Material Design<br> Form Controls</a> </li> <li> <a href="form_controls.html"> Bootstrap<br> Form Controls</a> </li> <li> <a href="form_icheck.html"> iCheck Controls</a> </li> <li> <a href="form_layouts.html"> Form Layouts</a> </li> <li> <a href="form_editable.html"> <span class="badge badge-roundless badge-warning">new</span>Form X-editable</a> </li> <li> <a href="form_wizard.html"> Form Wizard</a> </li> <li> <a href="form_validation.html"> Form Validation</a> </li> <li> <a href="form_image_crop.html"> <span class="badge badge-roundless badge-danger">new</span>Image Cropping</a> </li> <li> <a href="form_fileupload.html"> Multiple File Upload</a> </li> <li> <a href="form_dropzone.html"> Dropzone File Upload</a> </li> </ul> </li> <li> <a href="javascript:;"> <i class="icon-briefcase"></i> <span class="title">Data Tables</span> <span class="arrow "></span> </a> <ul class="sub-menu"> <li> <a href="table_basic.html"> Basic Datatables</a> </li> <li> <a href="table_tree.html"> Tree Datatables</a> </li> <li> <a href="table_responsive.html"> Responsive Datatables</a> </li> <li> <a href="table_managed.html"> Managed Datatables</a> </li> <li> <a href="table_editable.html"> Editable Datatables</a> </li> <li> <a href="table_advanced.html"> Advanced Datatables</a> </li> <li> <a href="table_ajax.html"> Ajax Datatables</a> </li> </ul> </li> <li> <a href="javascript:;"> <i class="icon-wallet"></i> <span class="title">Portlets</span> <span class="arrow "></span> </a> <ul class="sub-menu"> <li> <a href="portlet_general.html"> General Portlets</a> </li> <li> <a href="portlet_general2.html"> <span class="badge badge-roundless badge-danger">new</span>New Portlets #1</a> </li> <li> <a href="portlet_general3.html"> <span class="badge badge-roundless badge-danger">new</span>New Portlets #2</a> </li> <li> <a href="portlet_ajax.html"> Ajax Portlets</a> </li> <li> <a href="portlet_draggable.html"> Draggable Portlets</a> </li> </ul> </li> <li> <a href="javascript:;"> <i class="icon-bar-chart"></i> <span class="title">Charts</span> <span class="arrow "></span> </a> <ul class="sub-menu"> <li> <a href="charts_amcharts.html"> amChart</a> </li> <li> <a href="charts_flotcharts.html"> Flotchart</a> </li> </ul> </li> <li> <a href="javascript:;"> <i class="icon-docs"></i> <span class="title">Pages</span> <span class="arrow "></span> </a> <ul class="sub-menu"> <li> <a href="page_timeline.html"> <i class="icon-paper-plane"></i> <span class="badge badge-warning">2</span>New Timeline</a> </li> <li> <a href="extra_profile.html"> <i class="icon-user-following"></i> <span class="badge badge-success badge-roundless">new</span>New User Profile</a> </li> <li> <a href="page_todo.html"> <i class="icon-hourglass"></i> <span class="badge badge-danger">4</span>Todo</a> </li> <li> <a href="inbox.html"> <i class="icon-envelope"></i> <span class="badge badge-danger">4</span>Inbox</a> </li> <li> <a href="extra_faq.html"> <i class="icon-info"></i> FAQ</a> </li> <li> <a href="page_portfolio.html"> <i class="icon-feed"></i> Portfolio</a> </li> <li> <a href="page_coming_soon.html"> <i class="icon-flag"></i> Coming Soon</a> </li> <li> <a href="page_calendar.html"> <i class="icon-calendar"></i> <span class="badge badge-danger">14</span>Calendar</a> </li> <li> <a href="extra_invoice.html"> <i class="icon-flag"></i> Invoice</a> </li> <li> <a href="page_blog.html"> <i class="icon-speech"></i> Blog</a> </li> <li> <a href="page_blog_item.html"> <i class="icon-link"></i> Blog Post</a> </li> <li> <a href="page_news.html"> <i class="icon-eye"></i> <span class="badge badge-success">9</span>News</a> </li> <li> <a href="page_news_item.html"> <i class="icon-bell"></i> News View</a> </li> <li> <a href="page_timeline_old.html"> <i class="icon-paper-plane"></i> <span class="badge badge-warning">2</span>Old Timeline</a> </li> <li> <a href="extra_profile_old.html"> <i class="icon-user"></i> Old User Profile</a> </li> </ul> </li> <li> <a href="javascript:;"> <i class="icon-present"></i> <span class="title">Extra</span> <span class="arrow "></span> </a> <ul class="sub-menu"> <li> <a href="page_about.html"> About Us</a> </li> <li> <a href="page_contact.html"> Contact Us</a> </li> <li> <a href="extra_search.html"> Search Results</a> </li> <li> <a href="extra_pricing_table.html"> Pricing Tables</a> </li> <li> <a href="extra_404_option1.html"> 404 Page Option 1</a> </li> <li> <a href="extra_404_option2.html"> 404 Page Option 2</a> </li> <li> <a href="extra_404_option3.html"> 404 Page Option 3</a> </li> <li> <a href="extra_500_option1.html"> 500 Page Option 1</a> </li> <li> <a href="extra_500_option2.html"> 500 Page Option 2</a> </li> </ul> </li> <li> <a href="javascript:;"> <i class="icon-folder"></i> <span class="title">Multi Level Menu</span> <span class="arrow "></span> </a> <ul class="sub-menu"> <li> <a href="javascript:;"> <i class="icon-settings"></i> Item 1 <span class="arrow"></span> </a> <ul class="sub-menu"> <li> <a href="javascript:;"> <i class="icon-user"></i> Sample Link 1 <span class="arrow"></span> </a> <ul class="sub-menu"> <li> <a href="#"><i class="icon-power"></i> Sample Link 1</a> </li> <li> <a href="#"><i class="icon-paper-plane"></i> Sample Link 1</a> </li> <li> <a href="#"><i class="icon-star"></i> Sample Link 1</a> </li> </ul> </li> <li> <a href="#"><i class="icon-camera"></i> Sample Link 1</a> </li> <li> <a href="#"><i class="icon-link"></i> Sample Link 2</a> </li> <li> <a href="#"><i class="icon-pointer"></i> Sample Link 3</a> </li> </ul> </li> <li> <a href="javascript:;"> <i class="icon-globe"></i> Item 2 <span class="arrow"></span> </a> <ul class="sub-menu"> <li> <a href="#"><i class="icon-tag"></i> Sample Link 1</a> </li> <li> <a href="#"><i class="icon-pencil"></i> Sample Link 1</a> </li> <li> <a href="#"><i class="icon-graph"></i> Sample Link 1</a> </li> </ul> </li> <li> <a href="#"> <i class="icon-bar-chart"></i> Item 3 </a> </li> </ul> </li> <li> <a href="javascript:;"> <i class="icon-user"></i> <span class="title">Login Options</span> <span class="arrow "></span> </a> <ul class="sub-menu"> <li> <a href="login.html"> Login Form 1</a> </li> <li> <a href="login_2.html"> Login Form 2</a> </li> <li> <a href="login_3.html"> Login Form 3</a> </li> <li> <a href="login_soft.html"> Login Form 4</a> </li> <li> <a href="extra_lock.html"> Lock Screen 1</a> </li> <li> <a href="extra_lock2.html"> Lock Screen 2</a> </li> </ul> </li> <li> <a href="javascript:;"> <i class="icon-envelope-open"></i> <span class="title">Email Templates</span> <span class="arrow "></span> </a> <ul class="sub-menu"> <li> <a href="email_template1.html"> New Email Template 1</a> </li> <li> <a href="email_template2.html"> New Email Template 2</a> </li> <li> <a href="email_template3.html"> New Email Template 3</a> </li> <li> <a href="email_template4.html"> New Email Template 4</a> </li> <li> <a href="email_newsletter.html"> Old Email Template 1</a> </li> <li> <a href="email_system.html"> Old Email Template 2</a> </li> </ul> </li> <li class="last "> <a href="javascript:;"> <i class="icon-pointer"></i> <span class="title">Maps</span> <span class="arrow "></span> </a> <ul class="sub-menu"> <li> <a href="maps_google.html"> Google Maps</a> </li> <li> <a href="maps_vector.html"> Vector Maps</a> </li> </ul> </li> </ul> <!-- END SIDEBAR MENU --> </div> </div> <!-- END SIDEBAR --> <!-- BEGIN CONTENT --> <div class="page-content-wrapper"> <div class="page-content"> <!-- BEGIN SAMPLE PORTLET CONFIGURATION MODAL FORM--> <div class="modal fade" id="portlet-config" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button> <h4 class="modal-title">Modal title</h4> </div> <div class="modal-body"> Widget settings form goes here </div> <div class="modal-footer"> <button type="button" class="btn blue">Save changes</button> <button type="button" class="btn default" data-dismiss="modal">Close</button> </div> </div> <!-- /.modal-content --> </div> <!-- /.modal-dialog --> </div> <!-- /.modal --> <!-- END SAMPLE PORTLET CONFIGURATION MODAL FORM--> <!-- BEGIN STYLE CUSTOMIZER --> <div class="theme-panel"> <div class="toggler tooltips" data-container="body" data-placement="left" data-html="true" data-original-title="Click to open advance theme customizer panel"> <i class="icon-settings"></i> </div> <div class="toggler-close"> <i class="icon-close"></i> </div> <div class="theme-options"> <div class="theme-option theme-colors clearfix"> <span> THEME COLOR </span> <ul> <li class="color-default current tooltips" data-style="default" data-container="body" data-original-title="Default"> </li> <li class="color-grey tooltips" data-style="grey" data-container="body" data-original-title="Grey"> </li> <li class="color-blue tooltips" data-style="blue" data-container="body" data-original-title="Blue"> </li> <li class="color-dark tooltips" data-style="dark" data-container="body" data-original-title="Dark"> </li> <li class="color-light tooltips" data-style="light" data-container="body" data-original-title="Light"> </li> </ul> </div> <div class="theme-option"> <span> Theme Style </span> <select class="layout-style-option form-control input-small"> <option value="square" selected="selected">Square corners</option> <option value="rounded">Rounded corners</option> </select> </div> <div class="theme-option"> <span> Layout </span> <select class="layout-option form-control input-small"> <option value="fluid" selected="selected">Fluid</option> <option value="boxed">Boxed</option> </select> </div> <div class="theme-option"> <span> Header </span> <select class="page-header-option form-control input-small"> <option value="fixed" selected="selected">Fixed</option> <option value="default">Default</option> </select> </div> <div class="theme-option"> <span> Top Dropdown</span> <select class="page-header-top-dropdown-style-option form-control input-small"> <option value="light" selected="selected">Light</option> <option value="dark">Dark</option> </select> </div> <div class="theme-option"> <span> Sidebar Mode</span> <select class="sidebar-option form-control input-small"> <option value="fixed">Fixed</option> <option value="default" selected="selected">Default</option> </select> </div> <div class="theme-option"> <span> Sidebar Style</span> <select class="sidebar-style-option form-control input-small"> <option value="default" selected="selected">Default</option> <option value="compact">Compact</option> </select> </div> <div class="theme-option"> <span> Sidebar Menu </span> <select class="sidebar-menu-option form-control input-small"> <option value="accordion" selected="selected">Accordion</option> <option value="hover">Hover</option> </select> </div> <div class="theme-option"> <span> Sidebar Position </span> <select class="sidebar-pos-option form-control input-small"> <option value="left" selected="selected">Left</option> <option value="right">Right</option> </select> </div> <div class="theme-option"> <span> Footer </span> <select class="page-footer-option form-control input-small"> <option value="fixed">Fixed</option> <option value="default" selected="selected">Default</option> </select> </div> </div> </div> <!-- END STYLE CUSTOMIZER --> <!-- BEGIN PAGE HEADER--> <h3 class="page-title"> Tiles <small>windows 8 style tiles examples</small> </h3> <div class="page-bar"> <ul class="page-breadcrumb"> <li> <i class="fa fa-home"></i> <a href="index.html">Home</a> <i class="fa fa-angle-right"></i> </li> <li> <a href="#">UI Features</a> <i class="fa fa-angle-right"></i> </li> <li> <a href="#">Tiles</a> </li> </ul> <div class="page-toolbar"> <div class="btn-group pull-right"> <button type="button" class="btn btn-fit-height grey-salt dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-delay="1000" data-close-others="true"> Actions <i class="fa fa-angle-down"></i> </button> <ul class="dropdown-menu pull-right" role="menu"> <li> <a href="#">Action</a> </li> <li> <a href="#">Another action</a> </li> <li> <a href="#">Something else here</a> </li> <li class="divider"> </li> <li> <a href="#">Separated link</a> </li> </ul> </div> </div> </div> <!-- END PAGE HEADER--> <!-- BEGIN PAGE CONTENT--> <div class="tiles"> <div class="tile double-down bg-blue-hoki"> <div class="tile-body"> <i class="fa fa-bell-o"></i> </div> <div class="tile-object"> <div class="name"> Notifications </div> <div class="number"> 6 </div> </div> </div> <div class="tile bg-red-sunglo"> <div class="tile-body"> <i class="fa fa-calendar"></i> </div> <div class="tile-object"> <div class="name"> Meetings </div> <div class="number"> 12 </div> </div> </div> <div class="tile double selected bg-green-turquoise"> <div class="corner"> </div> <div class="check"> </div> <div class="tile-body"> <h4>support@metronic.com</h4> <p> Re: Metronic v1.2 - Project Update! </p> <p> 24 March 2013 12.30PM confirmed for the project plan update meeting... </p> </div> <div class="tile-object"> <div class="name"> <i class="fa fa-envelope"></i> </div> <div class="number"> 14 </div> </div> </div> <div class="tile selected bg-yellow-saffron"> <div class="corner"> </div> <div class="tile-body"> <i class="fa fa-user"></i> </div> <div class="tile-object"> <div class="name"> Members </div> <div class="number"> 452 </div> </div> </div> <div class="tile double bg-blue-madison"> <div class="tile-body"> <img src="../../assets/admin/pages/media/profile/photo1.jpg" alt=""> <h4>Announcements</h4> <p> Easily style icon color, size, shadow, and anything that's possible with CSS. </p> </div> <div class="tile-object"> <div class="name"> Bob Nilson </div> <div class="number"> 24 Jan 2013 </div> </div> </div> <div class="tile bg-purple-studio"> <div class="tile-body"> <i class="fa fa-shopping-cart"></i> </div> <div class="tile-object"> <div class="name"> Orders </div> <div class="number"> 121 </div> </div> </div> <div class="tile image selected"> <div class="tile-body"> <img src="../../assets/admin/pages/media/gallery/image2.jpg" alt=""> </div> <div class="tile-object"> <div class="name"> Media </div> </div> </div> <div class="tile bg-green-meadow"> <div class="tile-body"> <i class="fa fa-comments"></i> </div> <div class="tile-object"> <div class="name"> Feedback </div> <div class="number"> 12 </div> </div> </div> <div class="tile double bg-grey-cascade"> <div class="tile-body"> <img src="../../assets/admin/pages/media/profile/photo2.jpg" alt="" class="pull-right"> <h3>@lisa_wong</h3> <p> I really love this theme. I look forward to check the next release! </p> </div> <div class="tile-object"> <div class="name"> <i class="fa fa-twitter"></i> </div> <div class="number"> 10:45PM, 23 Jan </div> </div> </div> <div class="tile bg-red-intense"> <div class="tile-body"> <i class="fa fa-coffee"></i> </div> <div class="tile-object"> <div class="name"> Meetups </div> <div class="number"> 12 Jan </div> </div> </div> <div class="tile bg-green"> <div class="tile-body"> <i class="fa fa-bar-chart-o"></i> </div> <div class="tile-object"> <div class="name"> Reports </div> <div class="number"> </div> </div> </div> <div class="tile bg-blue-steel"> <div class="tile-body"> <i class="fa fa-briefcase"></i> </div> <div class="tile-object"> <div class="name"> Documents </div> <div class="number"> 124 </div> </div> </div> <div class="tile image double selected"> <div class="tile-body"> <img src="../../assets/admin/pages/media/gallery/image4.jpg" alt=""> </div> <div class="tile-object"> <div class="name"> Gallery </div> <div class="number"> 124 </div> </div> </div> <div class="tile bg-yellow-lemon selected"> <div class="corner"> </div> <div class="check"> </div> <div class="tile-body"> <i class="fa fa-cogs"></i> </div> <div class="tile-object"> <div class="name"> Settings </div> </div> </div> <div class="tile bg-red-sunglo"> <div class="tile-body"> <i class="fa fa-plane"></i> </div> <div class="tile-object"> <div class="name"> Projects </div> <div class="number"> 34 </div> </div> </div> </div> <!-- END PAGE CONTENT--> </div> </div> <!-- END CONTENT --> <!-- BEGIN QUICK SIDEBAR --> <!--Cooming Soon...--> <!-- END QUICK SIDEBAR --> </div> <!-- END CONTAINER --> <!-- BEGIN FOOTER --> <div class="page-footer"> <div class="page-footer-inner"> 2014 &copy; Metronic by keenthemes. </div> <div class="scroll-to-top"> <i class="icon-arrow-up"></i> </div> </div> <!-- END FOOTER --> </div> <!-- BEGIN JAVASCRIPTS(Load javascripts at bottom, this will reduce page load time) --> <!-- BEGIN CORE PLUGINS --> <!--[if lt IE 9]> <script src="../../assets/global/plugins/respond.min.js"></script> <script src="../../assets/global/plugins/excanvas.min.js"></script> <![endif]--> <script src="../../assets/global/plugins/jquery.min.js" type="text/javascript"></script> <script src="../../assets/global/plugins/jquery-migrate.min.js" type="text/javascript"></script> <!-- IMPORTANT! Load jquery-ui.min.js before bootstrap.min.js to fix bootstrap tooltip conflict with jquery ui tooltip --> <script src="../../assets/global/plugins/jquery-ui/jquery-ui.min.js" type="text/javascript"></script> <script src="../../assets/global/plugins/bootstrap/js/bootstrap.min.js" type="text/javascript"></script> <script src="../../assets/global/plugins/bootstrap-hover-dropdown/bootstrap-hover-dropdown.min.js" type="text/javascript"></script> <script src="../../assets/global/plugins/jquery-slimscroll/jquery.slimscroll.min.js" type="text/javascript"></script> <script src="../../assets/global/plugins/jquery.blockui.min.js" type="text/javascript"></script> <script src="../../assets/global/plugins/jquery.cokie.min.js" type="text/javascript"></script> <script src="../../assets/global/plugins/uniform/jquery.uniform.min.js" type="text/javascript"></script> <script src="../../assets/global/plugins/bootstrap-switch/js/bootstrap-switch.min.js" type="text/javascript"></script> <!-- END CORE PLUGINS --> <script src="../../assets/global/scripts/metronic.js" type="text/javascript"></script> <script src="../../assets/admin/layout2/scripts/layout.js" type="text/javascript"></script> <script src="../../assets/admin/layout2/scripts/demo.js" type="text/javascript"></script> <script> jQuery(document).ready(function() { // initiate layout and plugins Metronic.init(); // init metronic core components Layout.init(); // init current layout Demo.init(); // init demo features }); </script> <!-- END JAVASCRIPTS --> </body> <!-- END BODY --> </html>
zzsoszz/metronicv37
theme/templates/admin2_material_design/ui_tiles.html
HTML
apache-2.0
52,092
/****************************************************************************** * @file startup_ARMv81MML.c * @brief CMSIS Core Device Startup File for ARMv81MML Device * @version V2.0.1 * @date 23. July 2019 ******************************************************************************/ /* * Copyright (c) 2009-2019 Arm Limited. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * 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 * * 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. */ #if defined (ARMv81MML_DSP_DP_MVE_FP) #include "ARMv81MML_DSP_DP_MVE_FP.h" #else #error device not specified! #endif #define SERIAL_BASE_ADDRESS (0xA8000000ul) #define SERIAL_DATA *((volatile unsigned *) SERIAL_BASE_ADDRESS) /*---------------------------------------------------------------------------- Exception / Interrupt Handler Function Prototype *----------------------------------------------------------------------------*/ typedef void( *pFunc )( void ); /*---------------------------------------------------------------------------- External References *----------------------------------------------------------------------------*/ extern uint32_t __INITIAL_SP; extern uint32_t __STACK_LIMIT; extern void __PROGRAM_START(void) __NO_RETURN; /*---------------------------------------------------------------------------- Internal References *----------------------------------------------------------------------------*/ void Default_Handler(void) __NO_RETURN; void Reset_Handler (void) __NO_RETURN; /*---------------------------------------------------------------------------- Exception / Interrupt Handler *----------------------------------------------------------------------------*/ /* Exceptions */ void NMI_Handler (void) __attribute__ ((weak, alias("Default_Handler"))); void HardFault_Handler (void) __attribute__ ((weak)); void MemManage_Handler (void) __attribute__ ((weak, alias("Default_Handler"))); void BusFault_Handler (void) __attribute__ ((weak, alias("Default_Handler"))); void UsageFault_Handler (void) __attribute__ ((weak, alias("Default_Handler"))); void SecureFault_Handler (void) __attribute__ ((weak, alias("Default_Handler"))); void SVC_Handler (void) __attribute__ ((weak, alias("Default_Handler"))); void DebugMon_Handler (void) __attribute__ ((weak, alias("Default_Handler"))); void PendSV_Handler (void) __attribute__ ((weak, alias("Default_Handler"))); void SysTick_Handler (void) __attribute__ ((weak, alias("Default_Handler"))); void Interrupt0_Handler (void) __attribute__ ((weak, alias("Default_Handler"))); void Interrupt1_Handler (void) __attribute__ ((weak, alias("Default_Handler"))); void Interrupt2_Handler (void) __attribute__ ((weak, alias("Default_Handler"))); void Interrupt3_Handler (void) __attribute__ ((weak, alias("Default_Handler"))); void Interrupt4_Handler (void) __attribute__ ((weak, alias("Default_Handler"))); void Interrupt5_Handler (void) __attribute__ ((weak, alias("Default_Handler"))); void Interrupt6_Handler (void) __attribute__ ((weak, alias("Default_Handler"))); void Interrupt7_Handler (void) __attribute__ ((weak, alias("Default_Handler"))); void Interrupt8_Handler (void) __attribute__ ((weak, alias("Default_Handler"))); void Interrupt9_Handler (void) __attribute__ ((weak, alias("Default_Handler"))); /*---------------------------------------------------------------------------- Exception / Interrupt Vector table *----------------------------------------------------------------------------*/ #if defined ( __GNUC__ ) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wpedantic" #endif extern const pFunc __VECTOR_TABLE[496]; const pFunc __VECTOR_TABLE[496] __VECTOR_TABLE_ATTRIBUTE = { (pFunc)(&__INITIAL_SP), /* Initial Stack Pointer */ Reset_Handler, /* Reset Handler */ NMI_Handler, /* -14 NMI Handler */ HardFault_Handler, /* -13 Hard Fault Handler */ MemManage_Handler, /* -12 MPU Fault Handler */ BusFault_Handler, /* -11 Bus Fault Handler */ UsageFault_Handler, /* -10 Usage Fault Handler */ SecureFault_Handler, /* -9 Secure Fault Handler */ 0, /* Reserved */ 0, /* Reserved */ 0, /* Reserved */ SVC_Handler, /* -5 SVCall Handler */ DebugMon_Handler, /* -4 Debug Monitor Handler */ 0, /* Reserved */ PendSV_Handler, /* -2 PendSV Handler */ SysTick_Handler, /* -1 SysTick Handler */ /* Interrupts */ Interrupt0_Handler, /* 0 Interrupt 0 */ Interrupt1_Handler, /* 1 Interrupt 1 */ Interrupt2_Handler, /* 2 Interrupt 2 */ Interrupt3_Handler, /* 3 Interrupt 3 */ Interrupt4_Handler, /* 4 Interrupt 4 */ Interrupt5_Handler, /* 5 Interrupt 5 */ Interrupt6_Handler, /* 6 Interrupt 6 */ Interrupt7_Handler, /* 7 Interrupt 7 */ Interrupt8_Handler, /* 8 Interrupt 8 */ Interrupt9_Handler /* 9 Interrupt 9 */ /* Interrupts 10 .. 480 are left out */ }; #if defined ( __GNUC__ ) #pragma GCC diagnostic pop #endif /*---------------------------------------------------------------------------- Reset Handler called on controller reset *----------------------------------------------------------------------------*/ void Reset_Handler(void) { __set_MSPLIM((uint32_t)(&__STACK_LIMIT)); SystemInit(); /* CMSIS System Initialization */ __PROGRAM_START(); /* Enter PreMain (C library entry point) */ } /*---------------------------------------------------------------------------- Hard Fault Handler *----------------------------------------------------------------------------*/ void HardFault_Handler(void) { SERIAL_DATA = 'H'; SERIAL_DATA = '\n'; while(1); } /*---------------------------------------------------------------------------- Default Handler for Exceptions / Interrupts *----------------------------------------------------------------------------*/ void Default_Handler(void) { SERIAL_DATA = 'D'; SERIAL_DATA = '\n'; while(1); }
JonatanAntoni/CMSIS_5
CMSIS/DSP/Platforms/FVP/ARMv81MML/Startup/AC6/startup_ARMv81MML.c
C
apache-2.0
7,238
package org.keycloak.models.entities; import java.util.Map; /** * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a> * @version $Revision: 1 $ */ public class AuthenticatorConfigEntity { protected String id; protected String alias; private Map<String, String> config; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getAlias() { return alias; } public void setAlias(String alias) { this.alias = alias; } public Map<String, String> getConfig() { return config; } public void setConfig(Map<String, String> config) { this.config = config; } }
anaerobic/keycloak
model/api/src/main/java/org/keycloak/models/entities/AuthenticatorConfigEntity.java
Java
apache-2.0
757
/* Dummy MA57 interface to be used when MA57 isn't available. 10 Sept 08: First version. */ #include "lbl.h" #include "ma57.h" #ifdef __cplusplus extern "C" { /* To prevent C++ compilers from mangling symbols */ #endif /* ================================================================= */ #ifdef __FUNCT__ #undef __FUNCT__ #endif #define __FUNCT__ "MA57_Initialize" Ma57_Data *Ma57_Initialize( int nz, int n, FILE *logfile ) { return 0; } /* ================================================================= */ #ifdef __FUNCT__ #undef __FUNCT__ #endif #define __FUNCT__ "Ma57_Analyze" int Ma57_Analyze( Ma57_Data *ma57 ) { return 0; } /* ================================================================= */ #ifdef __FUNCT__ #undef __FUNCT__ #endif #define __FUNCT__ "Ma57_Factorize" int Ma57_Factorize( Ma57_Data *ma57, double A[] ) { return 0; } /* ================================================================= */ #ifdef __FUNCT__ #undef __FUNCT__ #endif #define __FUNCT__ "Ma57_Solve" int Ma57_Solve( Ma57_Data *ma57, double x[] ) { return 0; } /* ================================================================= */ #ifdef __FUNCT__ #undef __FUNCT__ #endif #define __FUNCT__ "Ma57_Refine" int Ma57_Refine( Ma57_Data *ma57, double x[], double rhs[], double A[], int maxitref, int job ) { return 0; } /* ================================================================= */ #ifdef __FUNCT__ #undef __FUNCT__ #endif #define __FUNCT__ "Ma57_Finalize" void Ma57_Finalize( Ma57_Data *ma57 ) { return; } /* ================================================================= */ #ifdef __cplusplus } /* Closing brace for extern "C" block */ #endif
siconos/siconos
externals/lbl/src/ma57dummy_lib.c
C
apache-2.0
1,788
/* * QUANTCONNECT.COM - * QC.Algorithm - Base Class for Algorithm. * Sentiment base class object - for intangible data types. */ /********************************************************** * USING NAMESPACES **********************************************************/ using System; using System.Collections; using System.Collections.Generic; namespace QuantConnect.Models { /// <summary> /// Base Class for Meta Data Types: /// </summary> public class SentimentData : DataBase { /******************************************************** * CLASS VARIABLES *********************************************************/ /// <summary> /// Sentiment data type: /// </summary> public SentimentDataType Type = SentimentDataType.Base; /******************************************************** * CLASS PROPERTIES *********************************************************/ /******************************************************** * CLASS METHODS *********************************************************/ } } // End QC Namespace
ychaim/QCAlgorithm
QuantConnect.Common/Data/Sentiment/Sentiment.cs
C#
apache-2.0
1,154
/* * Copyright 2017-2020 Crown Copyright * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Operations for formatting the output of an operation into a required representation. */ package uk.gov.gchq.gaffer.operation.impl.output;
GovernmentCommunicationsHeadquarters/Gaffer
core/operation/src/main/java/uk/gov/gchq/gaffer/operation/impl/output/package-info.java
Java
apache-2.0
751
--- title: "mapper.hour" layout: "function" isPage: "true" link: "/warpscript/framework_map" desc: "Return the hour of the tick for which it is computed" categoryTree: ["reference","frameworks","framework-map"] oldPath: ["20-frameworks","201-framework-map","201-single-value-mappers","279-mapper_hour.html.md"] category: "reference" --- This *mapper* function returns the hour of the tick for which it is computed. The `mapper.hour` function can be applied to values of any type. ## Example ## Stack: TOP: [{"c":"toto","l":{"label0":"42"},"a":{},"v":[[1380000000003189,42],[1418910910000000,123],[1419220920000000,211],[1421530930000000,132]]}] WarpScript commands: // arguments are: GTS or [GTS], (timezone) mapper, prewindow, postwindow, occurences [ SWAP 'UTC' mapper.hour 0 0 0 ] MAP Stack: TOP: [{"c":"toto","l":{"label0":"42"},"a":{},"v":[[1380000000003189,5],[1418910910000000,13],[1419220920000000,4],[1421530930000000,21]]}] ## Let's play with it ## {% raw %} <warp10-warpscript-widget>NEWGTS "toto" RENAME { 'label0' '42' } RELABEL 1380000000003189 NaN NaN NaN 42.0 ADDVALUE 1418910910000000 NaN NaN NaN 123.0 ADDVALUE 1419220920000000 NaN NaN NaN 211.0 ADDVALUE 1421530930000000 NaN NaN NaN 132.0 ADDVALUE 1 ->LIST // arguments are: GTS or [GTS], (timezone) mapper, prewindow, postwindow, occurences [ SWAP 'UTC' mapper.hour 0 0 0 ] MAP </warp10-warpscript-widget> {% endraw %} ## Unit test ## {% raw %} <warp10-warpscript-widget>NEWGTS "toto" RENAME { 'label0' '42' } RELABEL 1380000000003189 NaN NaN NaN 42.0 ADDVALUE 1418910910000000 NaN NaN NaN 123.0 ADDVALUE 1419220920000000 NaN NaN NaN 211.0 ADDVALUE 1421530930000000 NaN NaN NaN 132.0 ADDVALUE 1 ->LIST // arguments are: GTS or [GTS], (timezone) mapper, prewindow, postwindow, occurences [ SWAP 'UTC' mapper.hour 0 0 0 ] MAP VALUES LIST-> DROP LIST-> DROP 21 == ASSERT 4 == ASSERT 13 == ASSERT 5 == ASSERT 'unit test successful' </warp10-warpscript-widget> {% endraw %}
slambour/www.warp10.io
reference/frameworks/mapper_hour.md
Markdown
apache-2.0
1,982
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_45) on Thu Nov 13 21:22:02 UTC 2014 --> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <TITLE> Uses of Class org.apache.hadoop.mapreduce.lib.db.DateSplitter (Apache Hadoop Main 2.6.0 API) </TITLE> <META NAME="date" CONTENT="2014-11-13"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.hadoop.mapreduce.lib.db.DateSplitter (Apache Hadoop Main 2.6.0 API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../org/apache/hadoop/mapreduce/lib/db/DateSplitter.html" title="class in org.apache.hadoop.mapreduce.lib.db"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../index.html?org/apache/hadoop/mapreduce/lib/db//class-useDateSplitter.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="DateSplitter.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>org.apache.hadoop.mapreduce.lib.db.DateSplitter</B></H2> </CENTER> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Packages that use <A HREF="../../../../../../../org/apache/hadoop/mapreduce/lib/db/DateSplitter.html" title="class in org.apache.hadoop.mapreduce.lib.db">DateSplitter</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#org.apache.hadoop.mapreduce.lib.db"><B>org.apache.hadoop.mapreduce.lib.db</B></A></TD> <TD>&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="org.apache.hadoop.mapreduce.lib.db"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Uses of <A HREF="../../../../../../../org/apache/hadoop/mapreduce/lib/db/DateSplitter.html" title="class in org.apache.hadoop.mapreduce.lib.db">DateSplitter</A> in <A HREF="../../../../../../../org/apache/hadoop/mapreduce/lib/db/package-summary.html">org.apache.hadoop.mapreduce.lib.db</A></FONT></TH> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Subclasses of <A HREF="../../../../../../../org/apache/hadoop/mapreduce/lib/db/DateSplitter.html" title="class in org.apache.hadoop.mapreduce.lib.db">DateSplitter</A> in <A HREF="../../../../../../../org/apache/hadoop/mapreduce/lib/db/package-summary.html">org.apache.hadoop.mapreduce.lib.db</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;class</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../../org/apache/hadoop/mapreduce/lib/db/OracleDateSplitter.html" title="class in org.apache.hadoop.mapreduce.lib.db">OracleDateSplitter</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Implement DBSplitter over date/time values returned by an Oracle db.</TD> </TR> </TABLE> &nbsp; <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../org/apache/hadoop/mapreduce/lib/db/DateSplitter.html" title="class in org.apache.hadoop.mapreduce.lib.db"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../index.html?org/apache/hadoop/mapreduce/lib/db//class-useDateSplitter.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="DateSplitter.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright &#169; 2014 <a href="http://www.apache.org">Apache Software Foundation</a>. All Rights Reserved. </BODY> </HTML>
SAT-Hadoop/hadoop-2.6.0
share/doc/hadoop/api/org/apache/hadoop/mapreduce/lib/db/class-use/DateSplitter.html
HTML
apache-2.0
8,341
''' Python Homework with Chipotle data https://github.com/TheUpshot/chipotle ''' ''' BASIC LEVEL PART 1: Read in the file with csv.reader() and store it in an object called 'file_nested_list'. Hint: This is a TSV file, and csv.reader() needs to be told how to handle it. https://docs.python.org/2/library/csv.html ''' #[your code here] import csv with open("chipotle.tsv", mode="rU") as f: file_nested_list = [row for row in csv.reader(f, delimiter="\t")] #WITHOUT csv.reader() #with open("chipotle.tsv", mode="rU") as f: # file_nested_list = [row.split("\t") for row in f] ''' BASIC LEVEL PART 2: Separate 'file_nested_list' into the 'header' and the 'data'. ''' #[your code here] header = file_nested_list[0] data = file_nested_list[1:] ''' INTERMEDIATE LEVEL PART 3: Calculate the average price of an order. Hint: Examine the data to see if the 'quantity' column is relevant to this calculation. Hint: Think carefully about the simplest way to do this! Break the problem into steps and then code each step ''' ANSWER == 18.81 #slice the data list to include only the order_id column (sublist) order_id = [] for row in data: row[0] order_id.append(row[0]) print order_id[0:5] #check to make sure the loop sliced the correct column number_orders = len(set(order_id)) #count distinct of order numbers are store it in a variable print number_orders #print out order number should be 1834 #create a list of item prices from the item_price column (list). #First remove"$" character and then converting the string into a float #need to convert to float because of decimals #Can all be accomplished in a single for loop price = [] for row in data: row[-1][1:6] price.append(float(row[-1][1:6])) type(price) #confirm that this is a list type(price[0]) #confirm that values in list are floats print price #Create a list of order quantities and convert the strings into integers #quantity = [] #for row in data: # row[1] # quantity.append(int(row[1])) #type(quantity) #confirm that this is a list #type(quantity[0]) #confirm that values in list are integers #Get total price by doing elementwise multiplication to our two lists: quantity and price #total_price = [a*b for a,b in zip(price,quantity)] #use sum function to create a single flaot value #we can use the sum function without multiplying price by the quantit column #because the price column/var already reflects the quantity multiplier sum_total_price = sum(price) print sum_total_price avg_order_price = (sum_total_price/number_orders) print avg_order_price ''' INTERMEDIATE LEVEL PART 4: Create a list (or set) of all unique sodas and soft drinks that they sell. Note: Just look for 'Canned Soda' and 'Canned Soft Drink', and ignore other drinks like 'Izze'. ''' soda_list = [] for row in data: if (row[2] == "Canned Soda" or row[2] == "Canned Soft Drink"): soda_list.append(row[3]) unique_sodas = set(soda_list) print unique_sodas ''' ADVANCED LEVEL PART 5: Calculate the average number of toppings per burrito. Note: Let's ignore the 'quantity' column to simplify this task. Hint: Think carefully about the easiest way to count the number of toppings! ''' ANSWER == 5.40 ''' NOTE: much more complicated code below, below is the condensed version ''' http://stackoverflow.com/questions/823561/what-does-mean-in-python burrito_orders = 0 toppings_number = 0 for row in data: if "Burrito" in row[2]: burrito_orders += 1 toppings_number += (row[3].count(',') + 1) avg_toppings = (round(toppings_number/float(burrito_orders), 2)) print avg_toppings ##create a list that contains only burrito toppings #toppings_list = [] #for row in data: # if (row[2] == "Steak Burrito" or row[2] == "Chicken Burrito" or row[2] == "Veggie Burrito" or row[2] == "Carnitas Burrito" or row[2] == "Barbacoa Burrito" or row[2] == "Burrito"): # toppings_list.append(row[3]) #print toppings_list #1172 # ##find the number of burritos ##check this using excel...bad I know....but I don't trust other ways of checking. ##plus it's probably more defensible to tell your stakeholder you checked this way rather ##than some complex other logic using code... #number_burrito_orders = len(toppings_list) #print number_burrito_orders # ##find the total number of toppings using list comprehension but only works for lists with ##one level of nesting #num_toppings = [item for sublist in toppings_list for item in sublist].count(",") #print num_toppings #number of burrito toppings = 5151, this number is too low ##a visual inspection of the data suggests that there are closer to 7-10 toppings per order ##thus the order number should be somewhere around 9-10K # ##create a function to flatten the list, pulled shamelessly from stack exchange #def flatten(x): # result = [] # for el in x: # if hasattr(el, "__iter__") and not isinstance(el, basestring): # result.extend(flatten(el)) # else: # result.append(el) # return result # ##store flattened list in var #flat_toppings_list = flatten(toppings_list) #print flat_toppings_list # ##loop through flattened list and count each comma and add 1 #number_toppings = [] #for item in flat_toppings_list: # item.count(",") # number_toppings.append(item.count(",") + 1) # ##create a var with the sum of toppings #sum_number_toppings = sum(number_toppings) #print sum_number_toppings # #avg_toppings = (round(sum_number_toppings / float(number_burrito_orders), 2)) #print avg_toppings ''' ADVANCED LEVEL PART 6: Create a dictionary in which the keys represent chip orders and the values represent the total number of orders. Expected output: {'Chips and Roasted Chili-Corn Salsa': 18, ... } Note: Please take the 'quantity' column into account! Optional: Learn how to use 'defaultdict' to simplify your code. ''' from collections import defaultdict chips = defaultdict(int) for row in data: if "Chips" in row[2]: chips[row[2]] += int(row[1])
jdweaver/ds_sandbox
homework2/homework_3_chipotle.py
Python
apache-2.0
6,038
define( //begin v1.x content { "days-standAlone-short": [ "nedelja", "ponedeljak", "utorak", "sreda", "četvrtak", "petak", "subota" ], "months-format-narrow": [ "j", "f", "m", "a", "m", "j", "j", "a", "s", "o", "n", "d" ], "quarters-standAlone-narrow": [ "1.", "2.", "3.", "4." ], "field-weekday": "dan u nedelji", "$locale": "sr-latn", "dateFormatItem-yQQQ": "QQQ. y", "dateFormatItem-yMEd": "E, d. M. y.", "dateFormatItem-MMMEd": "E d. MMM", "eraNarrow": [ "p. n. e.", "n. e." ], "dateFormatItem-yMM": "MM.y", "dateFormatItem-MMMdd": "dd.MMM", "days-format-short": [ "nedelja", "ponedeljak", "utorak", "sreda", "četvrtak", "petak", "subota" ], "dateFormat-long": "dd. MMMM y.", "months-format-wide": [ "januar", "februar", "mart", "april", "maj", "jun", "jul", "avgust", "septembar", "oktobar", "novembar", "decembar" ], "dayPeriods-format-wide-pm": "popodne", "dateFormat-full": "EEEE, dd. MMMM y.", "dateFormatItem-Md": "d/M", "dateFormatItem-yMd": "d. M. y.", "field-era": "era", "dateFormatItem-yM": "y-M", "months-standAlone-wide": [ "januar", "februar", "mart", "april", "maj", "jun", "jul", "avgust", "septembar", "oktobar", "novembar", "decembar" ], "timeFormat-short": "HH.mm", "quarters-format-wide": [ "Prvo tromesečje", "Drugo tromesečje", "Treće tromesečje", "Četvrto tromesečje" ], "dateFormatItem-yQQQQ": "QQQQ. y", "timeFormat-long": "HH.mm.ss z", "field-year": "godina", "dateFormatItem-yMMM": "MMM y.", "field-hour": "čas", "dateFormatItem-MMdd": "MM-dd", "months-format-abbr": [ "januar", "februar", "mart", "april", "maj", "jun", "jul", "avgust", "septembar", "oktobar", "novembar", "decembar" ], "timeFormat-full": "HH.mm.ss zzzz", "field-day-relative+0": "danas", "field-day-relative+1": "sutra", "field-day-relative+2": "prekosutra", "months-standAlone-abbr": [ "januar", "februar", "mart", "april", "maj", "jun", "jul", "avgust", "septembar", "oktobar", "novembar", "decembar" ], "quarters-format-abbr": [ "Prvo tromesečje", "Drugo tromesečje", "Treće tromesečje", "Četvrto tromesečje" ], "quarters-standAlone-wide": [ "Prvo tromesečje", "Drugo tromesečje", "Treće tromesečje", "Četvrto tromesečje" ], "days-standAlone-wide": [ "nedelja", "ponedeljak", "utorak", "sreda", "četvrtak", "petak", "subota" ], "dateFormatItem-MMMMd": "d. MMMM", "timeFormat-medium": "HH.mm.ss", "dateFormatItem-yMMdd": "dd.MM.y", "dateFormatItem-Hm": "HH.mm", "quarters-standAlone-abbr": [ "Prvo tromesečje", "Drugo tromesečje", "Treće tromesečje", "Četvrto tromesečje" ], "eraAbbr": [ "p. n. e.", "n. e." ], "field-minute": "minut", "field-dayperiod": "pre podne/popodne", "days-standAlone-abbr": [ "nedelja", "ponedeljak", "utorak", "sreda", "četvrtak", "petak", "subota" ], "dateFormatItem-ms": "mm.ss", "quarters-format-narrow": [ "1.", "2.", "3.", "4." ], "field-day-relative+-1": "juče", "dateFormatItem-h": "hh a", "field-day-relative+-2": "prekjuče", "dateFormatItem-MMMd": "d. MMM", "dateFormatItem-MEd": "E, M-d", "dateFormatItem-yMMMM": "MMMM y.", "field-day": "dan", "days-format-wide": [ "nedelja", "ponedeljak", "utorak", "sreda", "četvrtak", "petak", "subota" ], "field-zone": "zona", "dateFormatItem-y": "y.", "months-standAlone-narrow": [ "j", "f", "m", "a", "m", "j", "j", "a", "s", "o", "n", "d" ], "field-year-relative+-1": "Prošle godine", "field-month-relative+-1": "Prošlog meseca", "dateFormatItem-hm": "hh.mm a", "days-format-abbr": [ "nedelja", "ponedeljak", "utorak", "sreda", "četvrtak", "petak", "subota" ], "dateFormatItem-yMMMd": "d. MMM y.", "eraNames": [ "p. n. e.", "n. e." ], "days-format-narrow": [ "n", "p", "u", "s", "č", "p", "s" ], "field-month": "mesec", "days-standAlone-narrow": [ "n", "p", "u", "s", "č", "p", "s" ], "dayPeriods-format-wide-am": "pre podne", "dateFormatItem-MMMMEd": "E d. MMMM", "dateFormatItem-MMMMdd": "dd. MMMM", "dateFormat-short": "d.M.yy.", "field-second": "sekund", "dateFormatItem-yMMMEd": "E, d. MMM y.", "field-month-relative+0": "Ovog meseca", "field-month-relative+1": "Sledećeg meseca", "dateFormatItem-Ed": "E d.", "field-week": "nedelja", "dateFormat-medium": "dd.MM.y.", "field-year-relative+0": "Ove godine", "field-week-relative+-1": "Prošle nedelje", "field-year-relative+1": "Sledeće godine", "dateFormatItem-Hms": "HH.mm.ss", "dateFormatItem-hms": "hh.mm.ss a", "field-week-relative+0": "Ove nedelje", "field-week-relative+1": "Sledeće nedelje" } //end v1.x content );
abssi/poc-tijari
dojoLib/toolkit/dojo/dojo/cldr/nls/sh/gregorian.js
JavaScript
apache-2.0
4,822
# Copyright 2016 Capital One Services, 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. from c7n.query import QueryResourceManager from c7n.manager import resources @resources.register('iot') class IoT(QueryResourceManager): class resource_type(object): service = 'iot' enum_spec = ('list_things', 'things', None) name = "thingName" id = "thingName" dimension = None default_report_fields = ( 'thingName', 'thingTypeName' )
VeritasOS/cloud-custodian
c7n/resources/iot.py
Python
apache-2.0
1,009
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <glog/logging.h> #include <gtest/gtest.h> #include "gflags/gflags.h" #include "paddle/fluid/inference/tensorrt/helper.h" #include "paddle/fluid/inference/tests/api/trt_test_helper.h" namespace paddle { namespace inference { void run(const AnalysisConfig& config, std::vector<float>* out_data, int bs) { auto predictor = CreatePaddlePredictor(config); auto input_names = predictor->GetInputNames(); int run_batch = bs; const int run_seq_len = 128; size_t len = run_batch * run_seq_len; int64_t i0_bs1[run_seq_len] = { 1, 3558, 4, 75, 491, 89, 340, 313, 93, 4, 255, 10, 75, 321, 4095, 1902, 4, 134, 49, 75, 311, 14, 44, 178, 543, 15, 12043, 2, 75, 201, 340, 9, 14, 44, 486, 218, 1140, 279, 12043, 2}; int64_t i1_bs1[run_seq_len] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; int64_t i2_bs1[run_seq_len] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39}; float i3_bs1[run_seq_len] = { 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0}; std::vector<int64_t> i0_data(len), i1_data(len), i2_data(len); std::vector<float> i3_data(len); for (size_t i = 0; i < len; i++) { i0_data[i] = i0_bs1[i % run_seq_len]; i1_data[i] = i1_bs1[i % run_seq_len]; i2_data[i] = i2_bs1[i % run_seq_len]; i3_data[i] = i3_bs1[i % run_seq_len]; } // first input auto input_t = predictor->GetInputTensor(input_names[0]); input_t->Reshape({run_batch, run_seq_len, 1}); input_t->copy_from_cpu(i0_data.data()); // second input auto input_t2 = predictor->GetInputTensor(input_names[1]); input_t2->Reshape({run_batch, run_seq_len, 1}); input_t2->copy_from_cpu(i1_data.data()); // third input. auto input_t3 = predictor->GetInputTensor(input_names[2]); input_t3->Reshape({run_batch, run_seq_len, 1}); input_t3->copy_from_cpu(i2_data.data()); auto input_t4 = predictor->GetInputTensor(input_names[3]); input_t4->Reshape({run_batch, run_seq_len, 1}); input_t4->copy_from_cpu(i3_data.data()); ASSERT_TRUE(predictor->ZeroCopyRun()); auto output_names = predictor->GetOutputNames(); auto output_t = predictor->GetOutputTensor(output_names[0]); std::vector<int> output_shape = output_t->shape(); int out_num = std::accumulate(output_shape.begin(), output_shape.end(), 1, std::multiplies<int>()); out_data->resize(out_num); output_t->copy_to_cpu(out_data->data()); } void trt_ernie(bool with_fp16, std::vector<float> result, float near_tolerance, int batch_size = 1) { AnalysisConfig config; std::string model_dir = FLAGS_infer_model; SetConfig(&config, model_dir, true); config.SwitchUseFeedFetchOps(false); int batch = 32; int min_seq_len = 1; int max_seq_len = 128; int opt_seq_len = 128; std::vector<int> min_shape = {1, min_seq_len, 1}; std::vector<int> max_shape = {batch, max_seq_len, 1}; std::vector<int> opt_shape = {batch, opt_seq_len, 1}; // Set the input's min, max, opt shape std::map<std::string, std::vector<int>> min_input_shape = { {"read_file_0.tmp_0", min_shape}, {"read_file_0.tmp_1", min_shape}, {"read_file_0.tmp_2", min_shape}, {"read_file_0.tmp_4", min_shape}}; std::map<std::string, std::vector<int>> max_input_shape = { {"read_file_0.tmp_0", max_shape}, {"read_file_0.tmp_1", max_shape}, {"read_file_0.tmp_2", max_shape}, {"read_file_0.tmp_4", max_shape}}; std::map<std::string, std::vector<int>> opt_input_shape = { {"read_file_0.tmp_0", opt_shape}, {"read_file_0.tmp_1", opt_shape}, {"read_file_0.tmp_2", opt_shape}, {"read_file_0.tmp_4", opt_shape}}; auto precision = AnalysisConfig::Precision::kFloat32; if (with_fp16) { precision = AnalysisConfig::Precision::kHalf; } config.EnableTensorRtEngine(1 << 30, 1, 5, precision, false, false); config.SetTRTDynamicShapeInfo(min_input_shape, max_input_shape, opt_input_shape); std::vector<float> out_data; run(config, &out_data, batch_size); for (size_t i = 0; i < out_data.size(); i++) { EXPECT_NEAR(result[i], out_data[i], near_tolerance); } } TEST(AnalysisPredictor, no_fp16) { std::vector<float> result = {0.597841, 0.219972, 0.182187}; trt_ernie(false, result, 1e-5); } TEST(AnalysisPredictor, fp16) { #ifdef TRT_PLUGIN_FP16_AVALIABLE std::vector<float> result = {0.598, 0.219, 0.182}; trt_ernie(true, result, 4e-3); #endif } TEST(AnalysisPredictor, no_fp16_bs2) { std::vector<float> result = {0.597841, 0.219972, 0.182187, 0.597841, 0.219972, 0.182187}; trt_ernie(false, result, 1e-5, 2); } TEST(AnalysisPredictor, fp16_bs2) { #ifdef TRT_PLUGIN_FP16_AVALIABLE std::vector<float> result = {0.598, 0.219, 0.182, 0.598, 0.219, 0.182}; trt_ernie(true, result, 4e-3, 2); #endif } // ernie_varlen std::shared_ptr<paddle_infer::Predictor> InitPredictor() { paddle_infer::Config config; config.SetModel(FLAGS_infer_model); config.EnableUseGpu(100, 0); // Open the memory optim. config.EnableMemoryOptim(); int max_batch = 32; int max_single_seq_len = 128; int opt_single_seq_len = 64; int min_batch_seq_len = 1; int max_batch_seq_len = 512; int opt_batch_seq_len = 256; std::string input_name0 = "read_file_0.tmp_0"; std::string input_name1 = "read_file_0.tmp_1"; std::string input_name2 = "read_file_0.tmp_2"; std::string input_name3 = "read_file_0.tmp_4"; std::vector<int> min_shape = {min_batch_seq_len}; std::vector<int> max_shape = {max_batch_seq_len}; std::vector<int> opt_shape = {opt_batch_seq_len}; // Set the input's min, max, opt shape std::map<std::string, std::vector<int>> min_input_shape = { {input_name0, min_shape}, {input_name1, min_shape}, {input_name2, {1}}, {input_name3, {1, 1, 1}}}; std::map<std::string, std::vector<int>> max_input_shape = { {input_name0, max_shape}, {input_name1, max_shape}, {input_name2, {max_batch + 1}}, {input_name3, {1, max_single_seq_len, 1}}}; std::map<std::string, std::vector<int>> opt_input_shape = { {input_name0, opt_shape}, {input_name1, opt_shape}, {input_name2, {max_batch + 1}}, {input_name3, {1, opt_single_seq_len, 1}}}; // only kHalf supported config.EnableTensorRtEngine( 1 << 30, 1, 5, paddle_infer::Config::Precision::kHalf, false, false); // erinie varlen must be used with dynamic shape config.SetTRTDynamicShapeInfo(min_input_shape, max_input_shape, opt_input_shape); // erinie varlen must be used with oss config.EnableTensorRtOSS(); return paddle_infer::CreatePredictor(config); } void run(paddle_infer::Predictor* predictor, std::vector<float>* out_data) { const int run_batch = 2; const int run_seq_len = 71; const int max_seq_len = 128; int32_t i1[run_seq_len] = { // sentence 1 1, 3558, 4, 75, 491, 89, 340, 313, 93, 4, 255, 10, 75, 321, 4095, 1902, 4, 134, 49, 75, 311, 14, 44, 178, 543, 15, 12043, 2, 75, 201, 340, 9, 14, 44, 486, 218, 1140, 279, 12043, 2, // sentence 2 101, 2054, 2234, 2046, 2486, 2044, 1996, 2047, 4552, 2001, 9536, 1029, 102, 2004, 1997, 2008, 2154, 1010, 1996, 2047, 4552, 9536, 2075, 1996, 2117, 3072, 2234, 2046, 2486, 1012, 102, }; int32_t i2[run_seq_len] = { // sentence 1 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // sentence 2 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; // shape info of this batch int32_t i3[3] = {0, 40, 71}; // max_seq_len represents the max sentence length of all the sentences, only // length of // input i4 is useful, data means nothing. int32_t i4[max_seq_len] = {0}; auto input_names = predictor->GetInputNames(); // first input auto input_t1 = predictor->GetInputHandle(input_names[0]); input_t1->Reshape({run_seq_len}); input_t1->CopyFromCpu(i1); // second input auto input_t2 = predictor->GetInputHandle(input_names[1]); input_t2->Reshape({run_seq_len}); input_t2->CopyFromCpu(i2); // third input auto input_t3 = predictor->GetInputHandle(input_names[2]); input_t3->Reshape({run_batch + 1}); input_t3->CopyFromCpu(i3); // fourth input auto input_t4 = predictor->GetInputHandle(input_names[3]); input_t4->Reshape({1, max_seq_len, 1}); input_t4->CopyFromCpu(i4); CHECK(predictor->Run()); auto output_names = predictor->GetOutputNames(); auto output_t = predictor->GetOutputHandle(output_names[0]); std::vector<int> output_shape = output_t->shape(); int out_num = std::accumulate(output_shape.begin(), output_shape.end(), 1, std::multiplies<int>()); out_data->resize(out_num); output_t->CopyToCpu(out_data->data()); return; } TEST(AnalysisPredictor, ernie_varlen) { #if IS_TRT_VERSION_GE(7234) if (platform::GetGPUComputeCapability(0) >= 75) { auto predictor = InitPredictor(); std::vector<float> out_data; run(predictor.get(), &out_data); std::vector<float> ref_data{0.59814, 0.219882, 0.181978, 0.359796, 0.577414, 0.0627908}; float near_tolerance = 1e-3; for (size_t i = 0; i < out_data.size(); i++) { EXPECT_NEAR(ref_data[i], out_data[i], near_tolerance); } } #endif } } // namespace inference } // namespace paddle
PaddlePaddle/Paddle
paddle/fluid/inference/tests/api/trt_dynamic_shape_ernie_test.cc
C++
apache-2.0
10,824
/** * Copyright (c) 2013-2014 Netflix, 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.netflix.msl.msg; import java.io.InputStream; import java.io.OutputStream; /** * A filter stream factory provides filter input stream and filter output * stream instances. * * Implementations must be thread-safe. * * @author Wesley Miaw <wmiaw@netflix.com> */ public interface FilterStreamFactory { /** * Return a new input stream that has the provided input stream as its * backing source. If no filtering is desired then the original input * stream must be returned. * * @param in the input stream to wrap. * @return a new filter input stream backed by the provided input stream or * the original input stream.. */ public InputStream getInputStream(final InputStream in); /** * Return a new output stream that has the provided output stream as its * backing destination. If no filtering is desired then the original output * stream must be returned. * * @param out the output stream to wrap. * @return a new filter output stream backed by the provided output stream * or the original output stream. */ public OutputStream getOutputStream(final OutputStream out); }
Netflix/msl
core/src/main/java/com/netflix/msl/msg/FilterStreamFactory.java
Java
apache-2.0
1,837
<div> <h2 translate="health.title">Health Checks</h2> <p> <button type="button" class="btn btn-primary" ng-click="refresh()"> <span class="glyphicon glyphicon-refresh"></span>&nbsp;<span translate="health.refresh.button">Refresh</span> </button> <button type="button" class="btn btn-primary" ng-click="reIndexAll()"> <span class="glyphicon glyphicon-refresh"></span>&nbsp;<span>Re index ElasticSearch</span> </button> </p> <p> <span ng-if ="updatingIndexHealth" class="label label-success" > {{indexationStatut}} </span> </p> <table id="healthCheck" class="table table-striped"> <thead> <tr> <th class="col-md-7" translate="health.table.service">Service Name</th> <th class="col-md-2 text-center" translate="health.table.status">Status</th> <th class="col-md-2 text-center" translate="health.details.details">Details</th> </tr> </thead> <tbody> <tr ng-repeat="health in healthData"> <td>{{'health.indicator.' + baseName(health.name) | translate}} {{subSystemName(health.name)}}</td> <td class="text-center"><span class="label" ng-class="getLabelClass(health.status)"> {{'health.status.' + health.status | translate}} </span></td> <td class="text-center"><a class="hand" ng-click="showHealth(health)" ng-show="health.details || health.error"> <i class="glyphicon glyphicon-eye-open"></i> </a></td> </tr> </tbody> </table> </div>
bzinoun/cream
src/main/webapp/scripts/app/admin/health/health.html
HTML
apache-2.0
1,451
/* * Copyright 2012-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.autoconfigure.data.elasticsearch; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.data.elasticsearch.client.reactive.ReactiveElasticsearchClient; import org.springframework.data.elasticsearch.repository.ReactiveElasticsearchRepository; import org.springframework.data.elasticsearch.repository.config.EnableReactiveElasticsearchRepositories; import org.springframework.data.elasticsearch.repository.support.ReactiveElasticsearchRepositoryFactoryBean; /** * {@link EnableAutoConfiguration Auto-configuration} for Spring Data's Elasticsearch * Reactive Repositories. * * @author Brian Clozel * @since 2.2.0 * @see EnableReactiveElasticsearchRepositories */ @Configuration(proxyBeanMethods = false) @ConditionalOnClass({ ReactiveElasticsearchClient.class, ReactiveElasticsearchRepository.class }) @ConditionalOnProperty(prefix = "spring.data.elasticsearch.repositories", name = "enabled", havingValue = "true", matchIfMissing = true) @ConditionalOnMissingBean(ReactiveElasticsearchRepositoryFactoryBean.class) @Import(ReactiveElasticsearchRepositoriesRegistrar.class) public class ReactiveElasticsearchRepositoriesAutoConfiguration { }
Buzzardo/spring-boot
spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveElasticsearchRepositoriesAutoConfiguration.java
Java
apache-2.0
2,202
/*! * Ext JS Library 3.4.0 * Copyright(c) 2006-2011 Sencha Inc. * licensing@sencha.com * http://www.sencha.com/license */ Ext.ux.PortalColumn = Ext.extend(Ext.Container, { layout : 'anchor', //autoEl : 'div',//already defined by Ext.Component defaultType : 'portlet', cls : 'x-portal-column' }); Ext.reg('portalcolumn', Ext.ux.PortalColumn);
ahwxl/cms
icms/src/main/webapp/res/extjs/ux/PortalColumn.js
JavaScript
apache-2.0
378
/* * Druid - a distributed column store. * Copyright 2012 - 2015 Metamarkets Group Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.druid.cli; import com.google.inject.Injector; import io.airlift.command.Cli; import io.airlift.command.Help; import io.airlift.command.ParseException; import io.druid.cli.convert.ConvertProperties; import io.druid.cli.validate.DruidJsonValidator; import io.druid.guice.ExtensionsConfig; import io.druid.guice.GuiceInjectors; import io.druid.initialization.Initialization; import java.util.Collection; /** */ public class Main { @SuppressWarnings("unchecked") public static void main(String[] args) { final Cli.CliBuilder<Runnable> builder = Cli.builder("druid"); builder.withDescription("Druid command-line runner.") .withDefaultCommand(Help.class) .withCommands(Help.class, Version.class); builder.withGroup("server") .withDescription("Run one of the Druid server types.") .withDefaultCommand(Help.class) .withCommands( CliCoordinator.class, CliHistorical.class, CliBroker.class, CliRealtime.class, CliOverlord.class, CliMiddleManager.class, CliBridge.class, CliRouter.class ); builder.withGroup("example") .withDescription("Run an example") .withDefaultCommand(Help.class) .withCommands(CliRealtimeExample.class); builder.withGroup("tools") .withDescription("Various tools for working with Druid") .withDefaultCommand(Help.class) .withCommands(ConvertProperties.class, DruidJsonValidator.class, PullDependencies.class, CreateTables.class); builder.withGroup("index") .withDescription("Run indexing for druid") .withDefaultCommand(Help.class) .withCommands(CliHadoopIndexer.class); builder.withGroup("internal") .withDescription("Processes that Druid runs \"internally\", you should rarely use these directly") .withDefaultCommand(Help.class) .withCommands(CliPeon.class, CliInternalHadoopIndexer.class); final Injector injector = GuiceInjectors.makeStartupInjector(); final ExtensionsConfig config = injector.getInstance(ExtensionsConfig.class); final Collection<CliCommandCreator> extensionCommands = Initialization.getFromExtensions(config, CliCommandCreator.class); for (CliCommandCreator creator : extensionCommands) { creator.addCommands(builder); } final Cli<Runnable> cli = builder.build(); try { final Runnable command = cli.parse(args); if (! (command instanceof Help)) { // Hack to work around Help not liking being injected injector.injectMembers(command); } command.run(); } catch (ParseException e) { System.out.println("ERROR!!!!"); System.out.println(e.getMessage()); System.out.println("==="); cli.parse(new String[]{"help"}).run(); } } }
nvoron23/druid
services/src/main/java/io/druid/cli/Main.java
Java
apache-2.0
3,527
/* * Minio Cloud Storage, (C) 2018 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cmd import ( "github.com/gorilla/mux" ) const ( prometheusMetricsPath = "/prometheus/metrics" ) // registerMetricsRouter - add handler functions for metrics. func registerMetricsRouter(router *mux.Router) { // metrics router metricsRouter := router.NewRoute().PathPrefix(minioReservedBucketPath).Subrouter() metricsRouter.Handle(prometheusMetricsPath, metricsHandler()) }
abperiasamy/minio
cmd/metrics-router.go
GO
apache-2.0
999
/* * Copyright 2006-2011 The Virtual Laboratory for e-Science (VL-e) * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * For details, see the LICENCE.txt file location in the root directory of this * distribution or obtain the Apache Licence at the following location: * 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. * * See: http://www.vl-e.nl/ * See: LICENCE.txt (located in the root folder of this distribution). * --- * $Id: File.java,v 1.7 2011-06-07 16:12:50 ptdeboer Exp $ * $Date: 2011-06-07 16:12:50 $ */ // source: package nl.uva.vlet.io.javafile; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Serializable; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.util.ArrayList; import java.util.Random; import nl.uva.vlet.data.StringUtil; import nl.uva.vlet.exception.VRLSyntaxException; import nl.uva.vlet.exception.VlException; import nl.uva.vlet.vfs.VDir; import nl.uva.vlet.vfs.VFS; import nl.uva.vlet.vfs.VFSClient; import nl.uva.vlet.vfs.VFSNode; import nl.uva.vlet.vfs.VFile; import nl.uva.vlet.vrl.VRL; import nl.uva.vlet.vrl.VRLUtil; import nl.uva.vlet.vrs.VComposite; import nl.uva.vlet.vrs.VNode; import nl.uva.vlet.vrs.VRSContext; import nl.uva.vlet.vrs.VRenamable; /** * The nl.uva.vlet.ui.javafile.File is a java.io.File equivalent class. Most * methods are the same except that for path strings VRL or URI strings can be * used. Resolving relative paths might be different as URI resolving mechanisms * are used. * <p> * The java.io.File class is nothing more than a class specifying a path on the * local file system. This class does the same except it wraps around an URI (or * VRL in this case). <br> * Implementation notes: <br> * Setting File permissions are currently not implemented as are file system * space methods.<br> * Not all methods and possible combinations have been tested.<br> * <p> * The classes in this package are under construction and any volunteer willing * to test this class is welcome. * * @author Piter T. de Boer */ public class File implements Serializable, Comparable<File>, Cloneable { private static final long serialVersionUID = -5564471676154170368L; /** * VRL Separator char, uses URI separator ! (Forward Slash) Separator chars * will be translated to local (OS depended) separator if needed. */ public static final char separatorChar = VRL.SEP_CHAR; public static final String separator = "" + separatorChar; /** * Normalized VRL path separator, uses colon ":" as default, will be * translated to local OS depended path separator char if needed. */ public static final char pathSeparatorChar = ':'; public static final String pathSeparator = "" + pathSeparatorChar; // static VFS Client for global file access ! private static VFSClient staticVFS; private static Random randomizer = new Random(System.currentTimeMillis()); /** * Specify global VFSClient which is used as VFSNode factory,. Only use * setStaticVFSClient() once at the startup of your application. */ public static synchronized void setStaticVFSClient(VFSClient vfsClient) { staticVFS = vfsClient; } /** * Returns global VFSClient used to access the VFS. The wrapper class * javafile.File doesn't hold any state regarding the VFSClient nor does is * keep a cached copy of VFSClient. This because the java.io.File is just an * 'abstract' file which is nothing more than a path or in this case a (VRL) * location object. <br> * Each method which needs the VFSClient call this methods. <br> * If a setStaticVFSClient() is called between javafile.File methods * different results could be returned depending of the state of the * VFSClient and/or VRSContext associated witht the VFSClient. Only use * setStaticVFSClient() once at the startup of your application. It is used * as global VFSNode factory. */ public static synchronized VFSClient getStaticVFSClient() { // lazy initialization ! if (staticVFS == null) { staticVFS = new VFSClient(VFS.getDefaultVRSContext()); } return staticVFS; } /** Convertor method to convert anarray of VNodes to Files */ public static File[] toFiles(VNode[] childs) { File files[] = new File[childs.length]; for (int i = 0; i < files.length; i++) { files[i] = new File(childs[i].getVRL()); } return files; } // ==================================================================== // Instance // ==================================================================== /** Is not muteable ! */ private final VRL location; /** * Constructs (abstract) File from relative or absolute path or URI * location. * * @param pathname * A location string relative or absolute URI/VRL * @throws NullPointerException * If the <code>pathname</code> argument is <code>null</code> */ public File(String pathOrURI) { if (pathOrURI == null) { throw new NullPointerException(); } // Warning: can be relative ! try { this.location = new VRL(pathOrURI); } catch (VRLSyntaxException e) { throw new Error("URISyntax Exception for:" + pathOrURI, e); } } /** Resolve optional relative path against current working directory */ public VRL cwdResolve(String name) { try { return getStaticVFSClient().getWorkingDir().resolvePath(name); } catch (VRLSyntaxException e) { throw new Error("URI Syntax exception", e); } } /** * Tries to resolve child location against parent location. If parent==null * then child location is used "as is". * * @param parent * The parent location string (VRL or URI) * @param child * The child location string (VRL or URI) * @throws NullPointerException * If <code>child</code> is <code>null</code> */ public File(String parent, String child) { if (child == null) { throw new NullPointerException(); } try { if (parent != null) { VRL parentVrl = new VRL(parent); this.location = parentVrl.resolvePath(child); } else { // can be relative ! this.location = new VRL(child); } } catch (VRLSyntaxException e) { throw new Error("JavaFile URI Exception:" + e.getMessage(), e); } } /** * Creates a new <code>File</code> instance from a parent location and a * child location string. * * <p> * If <code>parent</code> is <code>null</code> then the new * <code>File</code> instance is created as if by invoking the * single-argument <code>File</code> constructor on the given * <code>child</code> location string. * * @param parent * The parent File * @param child * The child pathname string * @throws NullPointerException * If <code>child</code> is <code>null</code> */ public File(File parent, String child) { if (child == null) { throw new NullPointerException(); } try { if (parent != null) { this.location = parent.getAbsoluteVRL().resolvePath(child); } else { this.location = new VRL(child); } } catch (VRLSyntaxException e) { throw new Error("URI Syntax exception for resolving:'" + this + "' + '" + child + "'", e); } } /** Resolve relative location against this file's location */ public VRL resolve(String child) { try { return getAbsoluteVRL().resolvePath(child); } catch (VRLSyntaxException e) { throw new Error("JavaFile URI Exception:" + e.getMessage(), e); } } /** Construct abstract file from specified URI */ public File(URI uri) { this.location = new VRL(uri); } /** Construct abstract file from specified VRL */ public File(VRL vrl) { this.location = vrl.duplicate(); } /** Construct abstract File from VNode. */ public File(VNode node) { this.location = node.getVRL().duplicate(); } /** Returns last part of path or basename part of VRL. */ public String getName() { return this.location.getBasename(); } /** Return parents directory name or dirname part of VRL. */ public String getParent() { String str = this.location.getDirname(); if (StringUtil.isEmpty(str)) return null; // stay compatible with java.o.File return str; } /** Return parent VRL of this location. */ public VRL getParentVRL() { return this.location.getParent(); } /** Get parent directory of this file location. Doesn' resolve the location. */ public File getParentFile() { String parentPath = VRL.dirname(location.getPath()); // java.io.File compatibility: parent of relative file is NULL if (StringUtil.isEmpty(parentPath)) return null; // could be relative return new File(parentPath); } /** Returns relative or absolute path part of VRL */ public String getPath() { return location.getPath(); } /** * Returns path as string array where each element is a path element * matching the (sub) directory name of the path without any slash or * backslash. */ public String[] getPathElements() { return location.getPathElements(); } /** * Whether location is absolute. Method calls VRL.isAbsolute() of VRL * location of this File. */ public boolean isAbsolute() { return location.isAbsolute(); } /** Returns resolved path of File VRL */ public String getAbsolutePath() { return getAbsoluteVRL().getPath(); } /** * Returns resolved File VRL. Since there is no difference in VRLs (nor * URIs) between canonical and absolute paths a relative paths will always * be matched against the current working directory and not between OS * specific 'Drives' or paths like "c:<relative path>". */ public VRL getAbsoluteVRL() { if (location.isAbsolute() == false) { return cwdResolve(location.getPath()); } else { return location; } } /** * Returns resolved JavaFile. Calls new JavaFile(getAbsoluteVRL()); */ public File getAbsoluteFile() { return new File(this.getAbsoluteVRL()); } /** * Returns the canonical pathname string of this abstract pathname. resolves * VRL and returns paths. This method behaves the same as getAbsolutePath() * since for VRLs there is no difference between canonical and absolute * VRLs. */ public String getCanonicalPath() throws IOException { return getCanonicalVRL().getPath(); } /** * Returns the resolved absolute VRL. Similar to getAbsoluteVRL() since for * VRLs there is no difference between canonical and absolute VRLs. */ public VRL getCanonicalVRL() throws IOException { return getAbsoluteVRL(); } /** * Returns canonicalFile. Similar to getAbsoluteFile() since for VRLs there * is no difference between canonical and absolute VRLs. */ public File getCanonicalFile() throws IOException { return new File(this.getCanonicalVRL()); } public URL toURL() throws MalformedURLException { return this.toURI().toURL(); } /** * Returns URI of this file. If the file can be resolved to an (existing) * directory, the URI has a slash ('/') appended. */ public URI toURI() { try { if (isDirectory()) return VRLUtil.toDirURL(getAbsoluteVRL()).toURI();// append '/' else return getAbsoluteVRL().toURI(); } catch (Exception e) { throw new Error("JavaFile URI Exception:" + e.getMessage(), e); } } /** * Tests whether this location is readable by the current user. * * @throws Error * if the location doesn't exist, or some other exception * occurred. */ public boolean canRead() { try { VFSNode node = getStaticVFSClient().getVFSNode(getAbsoluteVRL()); return node.isReadable(); } catch (Exception e) { throw new Error("canRead(): Couldn't access location:" + location, e); } } /** * Tests whether this location is writable by the current user. * * @throws Error * if the location doesn't exist, or some other exception * occurred. */ public boolean canWrite() { try { VFSNode node = getStaticVFSNode(); return node.isWritable(); } catch (Exception e) { throw new Error("canWrite(): Couldn't access location:" + location, e); } } /** * Tests whether the path denoted by this abstract location is a file or * directory and it exists. * * @throws Error * if it couldn't be determined whether the path exists or not. */ public boolean exists() { try { // need Exists ! if (getStaticVFSClient().existsPath(getAbsoluteVRL())) return true; return false; } catch (Exception e) { throw new Error("exists(): Couldn't access location:" + location, e); } } /** * Tests whether the directory denoted by this abstract location is a normal * directory and it exists. * * @throws Error * if it couldn't be determined whether the directory exists or * not. */ public boolean isDirectory() { try { if (getStaticVFSClient().existsDir(getAbsoluteVRL())) return true; return false; } catch (Exception e) { throw new Error("Couldn't access location:" + location, e); } } /** * Tests whether the file denoted by this abstract location is a normal file * and exists. * * @throws Error * if it couldn't be determined whether the file exists or not. */ public boolean isFile() { try { if (getStaticVFSClient().existsFile(getAbsoluteVRL())) return true; return false; } catch (Exception e) { throw new Error("Couldn't access:" + location, e); } } public boolean isHidden() { return false; } public long lastModified() { try { VFSNode node = getStaticVFSNode(); // getStaticVFSClient().getVFSNode(this.location); return node.getModificationTime(); } catch (Exception e) { throw new Error("Couldn't access:" + location, e); } } /** * Returns the length of the file denoted by this abstract pathname. Returns * 0 if this location denotes a directory. */ public long length() { try { VNode node = getStaticVNode(); if (node instanceof VFile) { return ((VFile) node).getLength(); } return 0; } catch (Exception e) { throw new Error("Couldn't access:" + location, e); } } /** Create new File. Ignores optional existing file. */ public boolean createNewFile() throws IOException { try { VFile vfile = getStaticVFSClient().newFile(this.location); return vfile.create(true); } catch (Exception e) { throw VlException.createIOException("Couldn't create new file:" + location, e); } } /** Deletes file. */ public boolean delete() { try { VFile vfile = getStaticVFSClient().newFile(getAbsoluteVRL()); return vfile.delete(); } catch (Exception e) { throw new Error("Couldn't delete file:" + location, e); } } /** * @deprecated Not Implemented ! Deletion of remote files can take forever... */ public void deleteOnExit() { throw new Error("Not implemented"); } /** * Returns list of child if this file is a directory. Returns NULL if this * file is not a directory * * @return */ public String[] list() { try { VNode[] nodes = this.listNodes(); if (nodes == null) return null; String list[] = new String[nodes.length]; for (int i = 0; i < list.length; i++) { list[i] = nodes[i].getBasename(); } return list; } catch (Exception e) { throw new Error("Couldn't list location:" + location, e); } } public VNode[] listNodes() throws IOException { try { VNode node = getStaticVNode(); if (node instanceof VComposite) { return ((VComposite) node).getNodes(); } return null; } catch (Exception e) { throw VlException.createIOException("Couldn't list location:" + location, e); } } /** Return contents of directory. */ public String[] list(FilenameFilter filter) { String names[] = list(); if ((names == null) || (filter == null)) { return names; } ArrayList<String> v = new ArrayList<String>(); for (int i = 0; i < names.length; i++) { if (filter.accept(this, names[i])) { v.add(names[i]); } } return (String[]) (v.toArray(new String[v.size()])); } /** Return contents of directory. */ public File[] listFiles() { VNode nodes[]; try { nodes = listNodes(); } catch (IOException e) { throw new Error("Couldn't read contents of:" + location, e); } if (nodes == null) return null; return toFiles(nodes); } /** * Returns filtered contents of this location is this location is a * directory. Returns NULL otherwise. */ public File[] listFiles(FilenameFilter filter) { String ss[] = list(); if (ss == null) return null; ArrayList<File> v = new ArrayList<File>(); for (int i = 0; i < ss.length; i++) { if ((filter == null) || filter.accept(this, ss[i])) { try { v.add(new File(getAbsoluteVRL().resolve(ss[i]))); } catch (VRLSyntaxException e) { throw new Error("URI Syntax exception :" + ss[i], e); } } } return (File[]) (v.toArray(new File[v.size()])); } public File[] listFiles(FileFilter filter) { String ss[] = list(); if (ss == null) return null; ArrayList<File> v = new ArrayList<File>(); for (int i = 0; i < ss.length; i++) { File f; try { f = new File(getAbsoluteVRL().resolve(ss[i])); } catch (VRLSyntaxException e) { throw new Error("URI Syntax exception :" + ss[i], e); } if ((filter == null) || filter.accept(f)) { v.add(f); } } return (File[]) (v.toArray(new File[v.size()])); } /** * Creates the directory named by this abstract location. */ public boolean mkdir() { try { return (getStaticVFSClient().mkdir(getAbsoluteVRL()) != null); } catch (Exception e) { throw new Error("Couldn't delete file:" + location, e); } } /** * Creates the directory named by this abstract pathname, including any * necessary but nonexistent parent directories. Note that if this operation * fails it may have succeeded in creating some of the necessary parent * location. */ public boolean mkdirs() { try { return (getStaticVFSClient().mkdirs(getAbsoluteVRL()) != null); } catch (Exception e) { throw new Error("Couldn't delete file:" + location, e); } } /** * Renames the file denoted by this abstract pathname. */ public boolean renameTo(File dest) { return (rename(dest) != null); } public VRL rename(File dest) { if (VRLUtil.hasSameServer(this.getAbsoluteVRL(), dest.getAbsoluteVRL()) == false) { throw new Error("Cannot rename file which are on different filesystems!:" + this); } try { VNode node = getStaticVFSClient().getNode(this.location); if (node instanceof VRenamable) { return ((VRenamable) node).rename(dest.getAbsoluteVRL().getPath(), true); } throw new Error("Location is not renamable:" + location); } catch (Exception e) { throw new Error("Couldn't rename location:" + location, e); } } /** @deprecated Not Implemented ! */ public boolean setLastModified(long time) { if (time < 0) throw new IllegalArgumentException("Negative time"); throw new Error("Not implemented"); } /** @deprecated Not Implemented ! */ public boolean setReadOnly() { throw new Error("Not Implemented!"); } /** @deprecated Not Implemented ! */ public boolean setWritable(boolean writable, boolean ownerOnly) { throw new Error("Not Implemented!"); } /** @deprecated Not Implemented ! */ public boolean setWritable(boolean writable) { throw new Error("Not Implemented!"); } /** @deprecated Not Implemented ! */ public boolean setReadable(boolean readable, boolean ownerOnly) { throw new Error("Not Implemented!"); } /** @deprecated Not Implemented ! */ public boolean setReadable(boolean readable) { return setReadable(readable, true); } /** @deprecated Executables do not makes sense in distributed environment */ public boolean setExecutable(boolean executable, boolean ownerOnly) { return false; } /** @deprecated Executables do not makes sense in a distributed environment */ public boolean setExecutable(boolean executable) { return false; } /** @deprecated Executables do not makes sense in a distributed environment */ public boolean canExecute() { return false; } /** Lists virtual roots. These are the child nodes from "My Vle" */ public static File[] listRoots() { try { VNode vnode = getStaticVFSClient().getVRSContext().getVirtualRoot(); VNode childs[] = ((VComposite) vnode).getNodes(); return toFiles(childs); } catch (Exception e) { throw new Error("Couldn't get nodes from rootnode", e); } } /** @deprecated Not implemented ! Virtual file systems don't have space ! */ public long getTotalSpace() { return 0; } /** @deprecated Not implemented ! Virtual file systems don't have space ! */ public long getFreeSpace() { return 0; } /** @deprecated Not implemented ! Virtual file systems don't have space ! */ public long getUsableSpace() { return 0; } /** * <p> * Creates a new empty file in the specified directory, using the given * prefix and suffix strings to generate its name. */ public static File createTempFile(String prefix, String suffix, File directory) throws IOException { if (prefix == null) prefix = "vtempFile"; if (suffix == null) suffix = ".tmp"; VFSClient vfs = getStaticVFSClient(); VDir tempDir = null; try { if (directory != null) { tempDir = vfs.getDir(directory.getAbsoluteVRL()); } else { tempDir = vfs.getTempDir(); } VFile tmpFile = null; do { long n = randomizer.nextLong(); if (n == Long.MIN_VALUE) { n = 0; // corner case } else { n = Math.abs(n); } VRL pathVRL = tempDir.resolvePathVRL(prefix + Long.toString(n) + suffix); tmpFile = vfs.newFile(pathVRL); } while (tmpFile.exists() == true); tmpFile.create(); return new File(tmpFile); } catch (VlException e) { throw VlException.createIOException("Couldn't create new temp file in directory:" + directory, e); } } /** * Creates an empty file in the default temporary-file directory, using the * given prefix and suffix to generate its name. Invoking this method is * equivalent to invoking <code>{@link #createTempFile(java.lang.String, * java.lang.String, java.io.File) * createTempFile(prefix,&nbsp;suffix,&nbsp;null)}</code>. * * @param prefix * The prefix string to be used in generating the file's name; * must be at least three characters long * * @param suffix * The suffix string to be used in generating the file's name; * may be <code>null</code>, in which case the suffix * <code>".tmp"</code> will be used * * @return An abstract pathname denoting a newly-created empty file * * @throws IllegalArgumentException * If the <code>prefix</code> argument contains fewer than three * characters * * @throws IOException * If a file could not be created * * @throws SecurityException * If a security manager exists and its <code>{@link * java.lang.SecurityManager#checkWrite(java.lang.String)}</code> * method does not allow a file to be created * * @since 1.2 */ public static File createTempFile(String prefix, String suffix) throws IOException { return createTempFile(prefix, suffix, null); } /** * Test whether the absolute and normalized VRLs are equivalent. See * VRL.compareTo(); */ public int compareTo(File other) { return this.getAbsoluteVRL().compareTo(other.getAbsoluteVRL()); } /** * Test whether the normalized VRLs are equivalent. See VRL.compareTo(); */ public boolean equals(Object obj) { if ((obj != null) && (obj instanceof File)) { return compareTo((File) obj) == 0; } return false; } /** Returns hashcode of absolute and normalized VRL: VRL.hashCode() */ public int hashCode() { return this.getAbsoluteVRL().hashCode(); } /** Return String representation of this location VRL. */ public String toString() { return this.location.toString(); } // ======================================================================== // VRS/VFS Methods ! // ======================================================================== /** * Returns VRL of this File. Doesn't do any resolving if this file a * relative path ! use getAbsoluteVRL() to get resolved VRL */ public VRL toVRL() { return this.location.duplicate(); } /** * Open Location using specified context and returns VNode. To determine the * type of the VNode the location must point to an existing resource ! Use * <code>toVFile()</code> or <code>toVDir()</code> to explicitly choose the * type and instantiate an non existing File or Directory. */ public VNode toNode(VRSContext context) throws VlException { return context.openLocation(getAbsoluteVRL()); } // helper method to return EXISTING VFSNode. private VFSNode getStaticVFSNode() { VRL vrl = getAbsoluteVRL(); try { return getStaticVFSClient().getVFSNode(vrl); } catch (VlException e) { throw new Error("Couldn't fetch VFSNode:" + vrl, e); } } // helper method to returns VNode private VNode getStaticVNode() { VRL vrl = getAbsoluteVRL(); try { return getStaticVFSClient().openLocation(vrl); } catch (VlException e) { throw new Error("Couldn't fetch VNode:" + vrl, e); } } /** * Open Location using specified VRSContext and return context enabled VFile * ! */ public VFile toVFile(VRSContext context) throws VlException { return new VFSClient(context).newFile(this.getAbsoluteVRL()); } /** * Open Location using specified VRSContext and returns context enabled VDir * ! If the location exsists but is not a directory an Exception might be * thrown. */ public VDir toVDir(VRSContext context) throws VlException { return new VFSClient(context).newDir(getAbsoluteVRL()); } /** * Convenience method to directly create an InputStream using the specified * VRSContext. * * @throws VlException */ public InputStream openInputStream(VRSContext context) throws VlException { return new VFSClient(context).openInputStream(getAbsoluteVRL()); } /** * Convenience method to directly create an OutputStream using the specified * VRSContext. * * @throws VlException */ public OutputStream openOutputStream(VRSContext context) throws VlException { return new VFSClient(context).openOutputStream(getAbsoluteVRL()); } /** * Convenience method to directly create an InputStream using the static * VFS. * * @throws VlException */ public InputStream openInputStream() throws VlException { return getStaticVFSClient().openInputStream(getAbsoluteVRL()); } /** * Convenience method to directly create an OutputStream using the static * VFS. * * @throws VlException */ public OutputStream openOutputStream() throws VlException { return getStaticVFSClient().openOutputStream(getAbsoluteVRL()); } public File clone() { return duplicate(); } public File duplicate() { return new File(location); } }
skoulouzis/vlet-1.5.0
source/core/nl.uva.vlet.vrs.core/source/main/nl/uva/vlet/io/javafile/File.java
Java
apache-2.0
32,655
/* * Copyright 2012 The Netty Project * * The Netty Project 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 io.netty.channel; import io.netty.buffer.ByteBufAllocator; import io.netty.util.internal.PlatformDependent; import java.util.IdentityHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; import static io.netty.channel.ChannelOption.ALLOCATOR; import static io.netty.channel.ChannelOption.AUTO_CLOSE; import static io.netty.channel.ChannelOption.AUTO_READ; import static io.netty.channel.ChannelOption.CONNECT_TIMEOUT_MILLIS; import static io.netty.channel.ChannelOption.MAX_MESSAGES_PER_READ; import static io.netty.channel.ChannelOption.MESSAGE_SIZE_ESTIMATOR; import static io.netty.channel.ChannelOption.SINGLE_EVENTEXECUTOR_PER_GROUP; import static io.netty.channel.ChannelOption.RCVBUF_ALLOCATOR; import static io.netty.channel.ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK; import static io.netty.channel.ChannelOption.WRITE_BUFFER_LOW_WATER_MARK; import static io.netty.channel.ChannelOption.WRITE_BUFFER_WATER_MARK; import static io.netty.channel.ChannelOption.WRITE_SPIN_COUNT; import static io.netty.util.internal.ObjectUtil.checkNotNull; /** * The default {@link ChannelConfig} implementation. */ public class DefaultChannelConfig implements ChannelConfig { private static final MessageSizeEstimator DEFAULT_MSG_SIZE_ESTIMATOR = DefaultMessageSizeEstimator.DEFAULT; private static final int DEFAULT_CONNECT_TIMEOUT = 30000; private static final AtomicIntegerFieldUpdater<DefaultChannelConfig> AUTOREAD_UPDATER; private static final AtomicReferenceFieldUpdater<DefaultChannelConfig, WriteBufferWaterMark> WATERMARK_UPDATER; static { AtomicIntegerFieldUpdater<DefaultChannelConfig> autoReadUpdater = PlatformDependent.newAtomicIntegerFieldUpdater(DefaultChannelConfig.class, "autoRead"); if (autoReadUpdater == null) { autoReadUpdater = AtomicIntegerFieldUpdater.newUpdater(DefaultChannelConfig.class, "autoRead"); } AUTOREAD_UPDATER = autoReadUpdater; AtomicReferenceFieldUpdater<DefaultChannelConfig, WriteBufferWaterMark> watermarkUpdater = PlatformDependent.newAtomicReferenceFieldUpdater(DefaultChannelConfig.class, "writeBufferWaterMark"); if (watermarkUpdater == null) { watermarkUpdater = AtomicReferenceFieldUpdater.newUpdater( DefaultChannelConfig.class, WriteBufferWaterMark.class, "writeBufferWaterMark"); } WATERMARK_UPDATER = watermarkUpdater; } protected final Channel channel; private volatile ByteBufAllocator allocator = ByteBufAllocator.DEFAULT; private volatile RecvByteBufAllocator rcvBufAllocator; private volatile MessageSizeEstimator msgSizeEstimator = DEFAULT_MSG_SIZE_ESTIMATOR; private volatile int connectTimeoutMillis = DEFAULT_CONNECT_TIMEOUT; private volatile int writeSpinCount = 16; @SuppressWarnings("FieldMayBeFinal") private volatile int autoRead = 1; private volatile boolean autoClose = true; private volatile WriteBufferWaterMark writeBufferWaterMark = WriteBufferWaterMark.DEFAULT; private volatile boolean pinEventExecutor = true; public DefaultChannelConfig(Channel channel) { this(channel, new AdaptiveRecvByteBufAllocator()); } protected DefaultChannelConfig(Channel channel, RecvByteBufAllocator allocator) { setRecvByteBufAllocator(allocator, channel.metadata()); this.channel = channel; } @Override @SuppressWarnings("deprecation") public Map<ChannelOption<?>, Object> getOptions() { return getOptions( null, CONNECT_TIMEOUT_MILLIS, MAX_MESSAGES_PER_READ, WRITE_SPIN_COUNT, ALLOCATOR, AUTO_READ, AUTO_CLOSE, RCVBUF_ALLOCATOR, WRITE_BUFFER_HIGH_WATER_MARK, WRITE_BUFFER_LOW_WATER_MARK, WRITE_BUFFER_WATER_MARK, MESSAGE_SIZE_ESTIMATOR, SINGLE_EVENTEXECUTOR_PER_GROUP); } protected Map<ChannelOption<?>, Object> getOptions( Map<ChannelOption<?>, Object> result, ChannelOption<?>... options) { if (result == null) { result = new IdentityHashMap<ChannelOption<?>, Object>(); } for (ChannelOption<?> o: options) { result.put(o, getOption(o)); } return result; } @SuppressWarnings("unchecked") @Override public boolean setOptions(Map<ChannelOption<?>, ?> options) { if (options == null) { throw new NullPointerException("options"); } boolean setAllOptions = true; for (Entry<ChannelOption<?>, ?> e: options.entrySet()) { if (!setOption((ChannelOption<Object>) e.getKey(), e.getValue())) { setAllOptions = false; } } return setAllOptions; } @Override @SuppressWarnings({ "unchecked", "deprecation" }) public <T> T getOption(ChannelOption<T> option) { if (option == null) { throw new NullPointerException("option"); } if (option == CONNECT_TIMEOUT_MILLIS) { return (T) Integer.valueOf(getConnectTimeoutMillis()); } if (option == MAX_MESSAGES_PER_READ) { return (T) Integer.valueOf(getMaxMessagesPerRead()); } if (option == WRITE_SPIN_COUNT) { return (T) Integer.valueOf(getWriteSpinCount()); } if (option == ALLOCATOR) { return (T) getAllocator(); } if (option == RCVBUF_ALLOCATOR) { return (T) getRecvByteBufAllocator(); } if (option == AUTO_READ) { return (T) Boolean.valueOf(isAutoRead()); } if (option == AUTO_CLOSE) { return (T) Boolean.valueOf(isAutoClose()); } if (option == WRITE_BUFFER_HIGH_WATER_MARK) { return (T) Integer.valueOf(getWriteBufferHighWaterMark()); } if (option == WRITE_BUFFER_LOW_WATER_MARK) { return (T) Integer.valueOf(getWriteBufferLowWaterMark()); } if (option == WRITE_BUFFER_WATER_MARK) { return (T) getWriteBufferWaterMark(); } if (option == MESSAGE_SIZE_ESTIMATOR) { return (T) getMessageSizeEstimator(); } if (option == SINGLE_EVENTEXECUTOR_PER_GROUP) { return (T) Boolean.valueOf(getPinEventExecutorPerGroup()); } return null; } @Override @SuppressWarnings("deprecation") public <T> boolean setOption(ChannelOption<T> option, T value) { validate(option, value); if (option == CONNECT_TIMEOUT_MILLIS) { setConnectTimeoutMillis((Integer) value); } else if (option == MAX_MESSAGES_PER_READ) { setMaxMessagesPerRead((Integer) value); } else if (option == WRITE_SPIN_COUNT) { setWriteSpinCount((Integer) value); } else if (option == ALLOCATOR) { setAllocator((ByteBufAllocator) value); } else if (option == RCVBUF_ALLOCATOR) { setRecvByteBufAllocator((RecvByteBufAllocator) value); } else if (option == AUTO_READ) { setAutoRead((Boolean) value); } else if (option == AUTO_CLOSE) { setAutoClose((Boolean) value); } else if (option == WRITE_BUFFER_HIGH_WATER_MARK) { setWriteBufferHighWaterMark((Integer) value); } else if (option == WRITE_BUFFER_LOW_WATER_MARK) { setWriteBufferLowWaterMark((Integer) value); } else if (option == WRITE_BUFFER_WATER_MARK) { setWriteBufferWaterMark((WriteBufferWaterMark) value); } else if (option == MESSAGE_SIZE_ESTIMATOR) { setMessageSizeEstimator((MessageSizeEstimator) value); } else if (option == SINGLE_EVENTEXECUTOR_PER_GROUP) { setPinEventExecutorPerGroup((Boolean) value); } else { return false; } return true; } protected <T> void validate(ChannelOption<T> option, T value) { if (option == null) { throw new NullPointerException("option"); } option.validate(value); } @Override public int getConnectTimeoutMillis() { return connectTimeoutMillis; } @Override public ChannelConfig setConnectTimeoutMillis(int connectTimeoutMillis) { if (connectTimeoutMillis < 0) { throw new IllegalArgumentException(String.format( "connectTimeoutMillis: %d (expected: >= 0)", connectTimeoutMillis)); } this.connectTimeoutMillis = connectTimeoutMillis; return this; } /** * {@inheritDoc} * <p> * @throws IllegalStateException if {@link #getRecvByteBufAllocator()} does not return an object of type * {@link MaxMessagesRecvByteBufAllocator}. */ @Override @Deprecated public int getMaxMessagesPerRead() { try { MaxMessagesRecvByteBufAllocator allocator = getRecvByteBufAllocator(); return allocator.maxMessagesPerRead(); } catch (ClassCastException e) { throw new IllegalStateException("getRecvByteBufAllocator() must return an object of type " + "MaxMessagesRecvByteBufAllocator", e); } } /** * {@inheritDoc} * <p> * @throws IllegalStateException if {@link #getRecvByteBufAllocator()} does not return an object of type * {@link MaxMessagesRecvByteBufAllocator}. */ @Override @Deprecated public ChannelConfig setMaxMessagesPerRead(int maxMessagesPerRead) { try { MaxMessagesRecvByteBufAllocator allocator = getRecvByteBufAllocator(); allocator.maxMessagesPerRead(maxMessagesPerRead); return this; } catch (ClassCastException e) { throw new IllegalStateException("getRecvByteBufAllocator() must return an object of type " + "MaxMessagesRecvByteBufAllocator", e); } } @Override public int getWriteSpinCount() { return writeSpinCount; } @Override public ChannelConfig setWriteSpinCount(int writeSpinCount) { if (writeSpinCount <= 0) { throw new IllegalArgumentException( "writeSpinCount must be a positive integer."); } this.writeSpinCount = writeSpinCount; return this; } @Override public ByteBufAllocator getAllocator() { return allocator; } @Override public ChannelConfig setAllocator(ByteBufAllocator allocator) { if (allocator == null) { throw new NullPointerException("allocator"); } this.allocator = allocator; return this; } @SuppressWarnings("unchecked") @Override public <T extends RecvByteBufAllocator> T getRecvByteBufAllocator() { return (T) rcvBufAllocator; } @Override public ChannelConfig setRecvByteBufAllocator(RecvByteBufAllocator allocator) { rcvBufAllocator = checkNotNull(allocator, "allocator"); return this; } /** * Set the {@link RecvByteBufAllocator} which is used for the channel to allocate receive buffers. * @param allocator the allocator to set. * @param metadata Used to set the {@link ChannelMetadata#defaultMaxMessagesPerRead()} if {@code allocator} * is of type {@link MaxMessagesRecvByteBufAllocator}. */ private void setRecvByteBufAllocator(RecvByteBufAllocator allocator, ChannelMetadata metadata) { if (allocator instanceof MaxMessagesRecvByteBufAllocator) { ((MaxMessagesRecvByteBufAllocator) allocator).maxMessagesPerRead(metadata.defaultMaxMessagesPerRead()); } else if (allocator == null) { throw new NullPointerException("allocator"); } rcvBufAllocator = allocator; } @Override public boolean isAutoRead() { return autoRead == 1; } @Override public ChannelConfig setAutoRead(boolean autoRead) { boolean oldAutoRead = AUTOREAD_UPDATER.getAndSet(this, autoRead ? 1 : 0) == 1; if (autoRead && !oldAutoRead) { channel.read(); } else if (!autoRead && oldAutoRead) { autoReadCleared(); } return this; } /** * Is called once {@link #setAutoRead(boolean)} is called with {@code false} and {@link #isAutoRead()} was * {@code true} before. */ protected void autoReadCleared() { } @Override public boolean isAutoClose() { return autoClose; } @Override public ChannelConfig setAutoClose(boolean autoClose) { this.autoClose = autoClose; return this; } @Override public int getWriteBufferHighWaterMark() { return writeBufferWaterMark.high(); } @Override public ChannelConfig setWriteBufferHighWaterMark(int writeBufferHighWaterMark) { if (writeBufferHighWaterMark < 0) { throw new IllegalArgumentException( "writeBufferHighWaterMark must be >= 0"); } for (;;) { WriteBufferWaterMark waterMark = writeBufferWaterMark; if (writeBufferHighWaterMark < waterMark.low()) { throw new IllegalArgumentException( "writeBufferHighWaterMark cannot be less than " + "writeBufferLowWaterMark (" + waterMark.low() + "): " + writeBufferHighWaterMark); } if (WATERMARK_UPDATER.compareAndSet(this, waterMark, new WriteBufferWaterMark(waterMark.low(), writeBufferHighWaterMark, false))) { return this; } } } @Override public int getWriteBufferLowWaterMark() { return writeBufferWaterMark.low(); } @Override public ChannelConfig setWriteBufferLowWaterMark(int writeBufferLowWaterMark) { if (writeBufferLowWaterMark < 0) { throw new IllegalArgumentException( "writeBufferLowWaterMark must be >= 0"); } for (;;) { WriteBufferWaterMark waterMark = writeBufferWaterMark; if (writeBufferLowWaterMark > waterMark.high()) { throw new IllegalArgumentException( "writeBufferLowWaterMark cannot be greater than " + "writeBufferHighWaterMark (" + waterMark.high() + "): " + writeBufferLowWaterMark); } if (WATERMARK_UPDATER.compareAndSet(this, waterMark, new WriteBufferWaterMark(writeBufferLowWaterMark, waterMark.high(), false))) { return this; } } } @Override public ChannelConfig setWriteBufferWaterMark(WriteBufferWaterMark writeBufferWaterMark) { this.writeBufferWaterMark = checkNotNull(writeBufferWaterMark, "writeBufferWaterMark"); return this; } @Override public WriteBufferWaterMark getWriteBufferWaterMark() { return writeBufferWaterMark; } @Override public MessageSizeEstimator getMessageSizeEstimator() { return msgSizeEstimator; } @Override public ChannelConfig setMessageSizeEstimator(MessageSizeEstimator estimator) { if (estimator == null) { throw new NullPointerException("estimator"); } msgSizeEstimator = estimator; return this; } private ChannelConfig setPinEventExecutorPerGroup(boolean pinEventExecutor) { this.pinEventExecutor = pinEventExecutor; return this; } private boolean getPinEventExecutorPerGroup() { return pinEventExecutor; } }
ichaki5748/netty
transport/src/main/java/io/netty/channel/DefaultChannelConfig.java
Java
apache-2.0
16,461
/* * Copyright 2014 CyberVision, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kaaproject.kaa.server.operations.service.akka; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.nio.ByteBuffer; import java.security.GeneralSecurityException; import java.security.KeyPair; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.UUID; import java.util.concurrent.TimeUnit; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.kaaproject.kaa.common.Constants; import org.kaaproject.kaa.common.avro.AvroByteArrayConverter; import org.kaaproject.kaa.common.dto.ApplicationDto; import org.kaaproject.kaa.common.dto.EndpointProfileDto; import org.kaaproject.kaa.common.dto.EventClassFamilyVersionStateDto; import org.kaaproject.kaa.common.dto.NotificationDto; import org.kaaproject.kaa.common.dto.NotificationTypeDto; import org.kaaproject.kaa.common.dto.user.UserVerifierDto; import org.kaaproject.kaa.common.endpoint.gen.ConfigurationSyncRequest; import org.kaaproject.kaa.common.endpoint.gen.EndpointAttachRequest; import org.kaaproject.kaa.common.endpoint.gen.EndpointDetachRequest; import org.kaaproject.kaa.common.endpoint.gen.Event; import org.kaaproject.kaa.common.endpoint.gen.EventSequenceNumberRequest; import org.kaaproject.kaa.common.endpoint.gen.EventSequenceNumberResponse; import org.kaaproject.kaa.common.endpoint.gen.EventSyncRequest; import org.kaaproject.kaa.common.endpoint.gen.EventSyncResponse; import org.kaaproject.kaa.common.endpoint.gen.LogEntry; import org.kaaproject.kaa.common.endpoint.gen.LogSyncRequest; import org.kaaproject.kaa.common.endpoint.gen.NotificationSyncRequest; import org.kaaproject.kaa.common.endpoint.gen.ProfileSyncRequest; import org.kaaproject.kaa.common.endpoint.gen.RedirectSyncResponse; import org.kaaproject.kaa.common.endpoint.gen.SyncRequest; import org.kaaproject.kaa.common.endpoint.gen.SyncRequestMetaData; import org.kaaproject.kaa.common.endpoint.gen.SyncResponse; import org.kaaproject.kaa.common.endpoint.gen.SyncResponseResultType; import org.kaaproject.kaa.common.endpoint.gen.UserAttachNotification; import org.kaaproject.kaa.common.endpoint.gen.UserDetachNotification; import org.kaaproject.kaa.common.endpoint.gen.UserSyncRequest; import org.kaaproject.kaa.common.endpoint.gen.UserSyncResponse; import org.kaaproject.kaa.common.endpoint.security.KeyUtil; import org.kaaproject.kaa.common.endpoint.security.MessageEncoderDecoder; import org.kaaproject.kaa.common.endpoint.security.MessageEncoderDecoder.CipherPair; import org.kaaproject.kaa.common.hash.EndpointObjectHash; import org.kaaproject.kaa.common.hash.SHA1HashUtils; import org.kaaproject.kaa.server.common.Base64Util; import org.kaaproject.kaa.server.common.dao.ApplicationService; import org.kaaproject.kaa.server.common.log.shared.appender.LogAppender; import org.kaaproject.kaa.server.common.log.shared.appender.LogDeliveryCallback; import org.kaaproject.kaa.server.common.log.shared.appender.LogEventPack; import org.kaaproject.kaa.server.common.log.shared.appender.LogSchema; import org.kaaproject.kaa.server.common.thrift.gen.operations.Notification; import org.kaaproject.kaa.server.common.thrift.gen.operations.RedirectionRule; import org.kaaproject.kaa.server.operations.pojo.SyncContext; import org.kaaproject.kaa.server.operations.pojo.exceptions.GetDeltaException; import org.kaaproject.kaa.server.operations.service.OperationsService; import org.kaaproject.kaa.server.operations.service.cache.CacheService; import org.kaaproject.kaa.server.operations.service.cache.EventClassFqnKey; import org.kaaproject.kaa.server.operations.service.event.EndpointEvent; import org.kaaproject.kaa.server.operations.service.event.EventClassFamilyVersion; import org.kaaproject.kaa.server.operations.service.event.EventClassFqnVersion; import org.kaaproject.kaa.server.operations.service.event.EventService; import org.kaaproject.kaa.server.operations.service.event.RemoteEndpointEvent; import org.kaaproject.kaa.server.operations.service.event.RouteInfo; import org.kaaproject.kaa.server.operations.service.event.RouteOperation; import org.kaaproject.kaa.server.operations.service.event.RouteTableAddress; import org.kaaproject.kaa.server.operations.service.event.RouteTableKey; import org.kaaproject.kaa.server.operations.service.event.UserRouteInfo; import org.kaaproject.kaa.server.operations.service.logs.LogAppenderService; import org.kaaproject.kaa.server.operations.service.metrics.MeterClient; import org.kaaproject.kaa.server.operations.service.metrics.MetricsService; import org.kaaproject.kaa.server.operations.service.notification.NotificationDeltaService; import org.kaaproject.kaa.server.operations.service.security.KeyStoreService; import org.kaaproject.kaa.server.operations.service.user.EndpointUserService; import org.kaaproject.kaa.server.sync.ClientSync; import org.kaaproject.kaa.server.sync.ConfigurationClientSync; import org.kaaproject.kaa.server.sync.ConfigurationServerSync; import org.kaaproject.kaa.server.sync.EventClientSync; import org.kaaproject.kaa.server.sync.EventServerSync; import org.kaaproject.kaa.server.sync.NotificationClientSync; import org.kaaproject.kaa.server.sync.ProfileClientSync; import org.kaaproject.kaa.server.sync.ServerSync; import org.kaaproject.kaa.server.sync.UserClientSync; import org.kaaproject.kaa.server.sync.UserServerSync; import org.kaaproject.kaa.server.sync.platform.AvroEncDec; import org.kaaproject.kaa.server.transport.channel.ChannelContext; import org.kaaproject.kaa.server.transport.channel.ChannelType; import org.kaaproject.kaa.server.transport.message.ErrorBuilder; import org.kaaproject.kaa.server.transport.message.MessageBuilder; import org.kaaproject.kaa.server.transport.message.SessionAwareMessage; import org.kaaproject.kaa.server.transport.message.SessionInitMessage; import org.kaaproject.kaa.server.transport.session.SessionInfo; import org.mockito.Mockito; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.test.util.ReflectionTestUtils; public class DefaultAkkaServiceTest { private static final Logger LOG = LoggerFactory.getLogger(DefaultAkkaServiceTest.class); private static final String SERVER2 = "SERVER2"; private static final String FQN1 = "fqn1"; private static final int ECF1_VERSION = 43; private static final String ECF1_ID = "EF1_ID"; private static final String TOPIC_ID = "TopicId"; private static final String UNICAST_NOTIFICATION_ID = "UnicastNotificationId"; private static final int TIMEOUT = 10000; private static final String TENANT_ID = "TENANT_ID"; private static final String USER_ID = "USER_ID"; private static final String APP_TOKEN = "APP_TOKEN"; private static final String SDK_TOKEN = "SDK_TOKEN"; private static final String APP_ID = "APP_ID"; private static final String PROFILE_BODY = "ProfileBody"; private static final int REQUEST_ID = 42; private DefaultAkkaService akkaService; // mocks private CacheService cacheService; private MetricsService metricsService; private KeyStoreService keyStoreService; private OperationsService operationsService; private NotificationDeltaService notificationDeltaService; private ApplicationService applicationService; private EventService eventService; private ApplicationDto applicationDto; private SyncContext simpleResponse; private SyncContext noDeltaResponse; private SyncContext deltaResponse; private SyncContext noDeltaResponseWithTopicState; private NotificationDto topicNotification; private LogAppenderService logAppenderService; private EndpointUserService endpointUserService; private KeyPair clientPair; private KeyPair targetPair; private KeyPair serverPair; private ByteBuffer clientPublicKey; private ByteBuffer clientPublicKeyHash; private ByteBuffer targetPublicKeyHash; @Before public void before() throws GeneralSecurityException { akkaService = new DefaultAkkaService(); AkkaContext context = new AkkaContext(); cacheService = mock(CacheService.class); metricsService = mock(MetricsService.class); keyStoreService = mock(KeyStoreService.class); operationsService = mock(OperationsService.class); notificationDeltaService = mock(NotificationDeltaService.class); applicationService = mock(ApplicationService.class); eventService = mock(EventService.class); logAppenderService = mock(LogAppenderService.class); endpointUserService = mock(EndpointUserService.class); ReflectionTestUtils.setField(context, "cacheService", cacheService); ReflectionTestUtils.setField(context, "metricsService", metricsService); ReflectionTestUtils.setField(context, "keyStoreService", keyStoreService); ReflectionTestUtils.setField(context, "operationsService", operationsService); ReflectionTestUtils.setField(context, "notificationDeltaService", notificationDeltaService); ReflectionTestUtils.setField(context, "applicationService", applicationService); ReflectionTestUtils.setField(context, "eventService", eventService); ReflectionTestUtils.setField(context, "logAppenderService", logAppenderService); ReflectionTestUtils.setField(context, "endpointUserService", endpointUserService); clientPair = KeyUtil.generateKeyPair(); targetPair = KeyUtil.generateKeyPair(); serverPair = KeyUtil.generateKeyPair(); Mockito.when(keyStoreService.getPublicKey()).thenReturn(serverPair.getPublic()); Mockito.when(keyStoreService.getPrivateKey()).thenReturn(serverPair.getPrivate()); Mockito.when(metricsService.createMeter(Mockito.anyString(), Mockito.anyString())).thenReturn(Mockito.mock(MeterClient.class)); ReflectionTestUtils.setField(akkaService, "context", context); if (akkaService.getActorSystem() == null) { akkaService.initActorSystem(); } clientPublicKey = ByteBuffer.wrap(clientPair.getPublic().getEncoded()); clientPublicKeyHash = ByteBuffer.wrap(SHA1HashUtils.hashToBytes(clientPair.getPublic().getEncoded())); targetPublicKeyHash = ByteBuffer.wrap(SHA1HashUtils.hashToBytes(targetPair.getPublic().getEncoded())); Mockito.when(cacheService.getTenantIdByAppToken(APP_TOKEN)).thenReturn(TENANT_ID); Mockito.when(cacheService.getAppTokenBySdkToken(SDK_TOKEN)).thenReturn(APP_TOKEN); Mockito.when(cacheService.getEndpointKey(EndpointObjectHash.fromBytes(clientPublicKeyHash.array()))).thenReturn( clientPair.getPublic()); Mockito.when(cacheService.getEndpointKey(EndpointObjectHash.fromBytes(targetPublicKeyHash.array()))).thenReturn( targetPair.getPublic()); applicationDto = new ApplicationDto(); applicationDto.setId(APP_ID); applicationDto.setApplicationToken(APP_TOKEN); ServerSync response = new ServerSync(); response.setRequestId(REQUEST_ID); response.setStatus(org.kaaproject.kaa.server.sync.SyncStatus.SUCCESS); ConfigurationServerSync confSyncResponse = new ConfigurationServerSync(); confSyncResponse.setResponseStatus(org.kaaproject.kaa.server.sync.SyncResponseStatus.NO_DELTA); response.setConfigurationSync(confSyncResponse); noDeltaResponse = new SyncContext(response); Map<String, Integer> subscriptionStates = new HashMap<>(); subscriptionStates.put(TOPIC_ID, new Integer(0)); noDeltaResponseWithTopicState = new SyncContext(response); noDeltaResponseWithTopicState.setSubscriptionStates(subscriptionStates); EndpointProfileDto epDto = new EndpointProfileDto(); epDto.setSystemNfVersion(42); epDto.setUserNfVersion(43); epDto.setLogSchemaVersion(44); noDeltaResponseWithTopicState.setEndpointProfile(epDto); response = new ServerSync(); response.setStatus(org.kaaproject.kaa.server.sync.SyncStatus.SUCCESS); confSyncResponse = new ConfigurationServerSync(); confSyncResponse.setResponseStatus(org.kaaproject.kaa.server.sync.SyncResponseStatus.DELTA); response.setConfigurationSync(confSyncResponse); deltaResponse = new SyncContext(response); response = new ServerSync(); response.setRequestId(REQUEST_ID); response.setStatus(org.kaaproject.kaa.server.sync.SyncStatus.SUCCESS); simpleResponse = new SyncContext(response); topicNotification = new NotificationDto(); topicNotification.setApplicationId(APP_ID); topicNotification.setTopicId(TOPIC_ID); topicNotification.setId(UNICAST_NOTIFICATION_ID); topicNotification.setExpiredAt(new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(7))); topicNotification.setSecNum(1); topicNotification.setVersion(42); topicNotification.setType(NotificationTypeDto.SYSTEM); topicNotification.setBody("I am a dummy notification".getBytes()); when(applicationService.findAppByApplicationToken(APP_TOKEN)).thenReturn(applicationDto); when(applicationService.findAppById(APP_ID)).thenReturn(applicationDto); when(endpointUserService.findUserVerifiers(APP_ID)).thenReturn(new ArrayList<UserVerifierDto>()); when(eventService.isMainUserNode(Mockito.anyString())).thenReturn(true); } @After public void after() { akkaService.getActorSystem().shutdown(); akkaService.getActorSystem().awaitTermination(); } private SessionInitMessage toSignedRequest(final UUID uuid, final ChannelType channelType, final ChannelContext ctx, SyncRequest request, final MessageBuilder responseBuilder, final ErrorBuilder errorBuilder) throws Exception { MessageEncoderDecoder crypt = new MessageEncoderDecoder(clientPair.getPrivate(), clientPair.getPublic(), serverPair.getPublic()); return toSignedRequest(uuid, channelType, ctx, request, responseBuilder, errorBuilder, crypt); } private SessionInitMessage toSignedRequest(final UUID uuid, final ChannelType channelType, final ChannelContext ctx, SyncRequest request, final MessageBuilder responseBuilder, final ErrorBuilder errorBuilder, MessageEncoderDecoder crypt) throws Exception { AvroByteArrayConverter<SyncRequest> requestConverter = new AvroByteArrayConverter<>(SyncRequest.class); byte[] data = requestConverter.toByteArray(request); final byte[] encodedData = crypt.encodeData(data); final byte[] encodedSessionKey = crypt.getEncodedSessionKey(); final byte[] sessionKeySignature = crypt.sign(encodedSessionKey); return new SessionInitMessage() { @Override public UUID getChannelUuid() { return uuid; } @Override public ChannelType getChannelType() { return channelType; } @Override public ChannelContext getChannelContext() { return ctx; } @Override public byte[] getSessionKeySignature() { return sessionKeySignature; } @Override public byte[] getEncodedSessionKey() { return encodedSessionKey; } @Override public byte[] getEncodedMessageData() { return encodedData; } @Override public MessageBuilder getMessageBuilder() { return responseBuilder; } @Override public ErrorBuilder getErrorBuilder() { return errorBuilder; } @Override public void onSessionCreated(SessionInfo session) { } @Override public int getKeepAlive() { return 100; } @Override public boolean isEncrypted() { return true; } @Override public int getPlatformId() { return Constants.KAA_PLATFORM_PROTOCOL_AVRO_ID; } }; } @Test public void testAkkaInitialization() { Assert.assertNotNull(akkaService.getActorSystem()); } @Test public void testDecodeSighnedException() throws Exception { SessionInitMessage message = Mockito.mock(SessionInitMessage.class); ErrorBuilder errorBuilder = Mockito.mock(ErrorBuilder.class); Mockito.when(message.getChannelContext()).thenReturn(Mockito.mock(ChannelContext.class)); Mockito.when(message.getErrorBuilder()).thenReturn(errorBuilder); Mockito.when(message.getEncodedMessageData()).thenReturn("dummy".getBytes()); Mockito.when(message.getEncodedSessionKey()).thenReturn("dummy".getBytes()); Mockito.when(message.getSessionKeySignature()).thenReturn("dummy".getBytes()); Mockito.when(message.isEncrypted()).thenReturn(true); akkaService.process(message); Mockito.verify(errorBuilder, Mockito.timeout(TIMEOUT * 10).atLeastOnce()).build(Mockito.any(Exception.class)); } @Test public void testDecodeSessionException() throws Exception { SessionAwareMessage message = Mockito.mock(SessionAwareMessage.class); ErrorBuilder errorBuilder = Mockito.mock(ErrorBuilder.class); SessionInfo sessionInfo = new SessionInfo(UUID.randomUUID(), Constants.KAA_PLATFORM_PROTOCOL_AVRO_ID, Mockito.mock(ChannelContext.class), ChannelType.ASYNC, Mockito.mock(CipherPair.class), EndpointObjectHash.fromSHA1("test"), "applicationToken", "sdkToken", 100, true); Mockito.when(message.getChannelContext()).thenReturn(Mockito.mock(ChannelContext.class)); Mockito.when(message.getErrorBuilder()).thenReturn(errorBuilder); Mockito.when(message.getSessionInfo()).thenReturn(sessionInfo); Mockito.when(message.getEncodedMessageData()).thenReturn("dummy".getBytes()); Mockito.when(message.isEncrypted()).thenReturn(true); akkaService.process(message); Mockito.verify(errorBuilder, Mockito.timeout(TIMEOUT * 10).atLeastOnce()).build(Mockito.any(Exception.class)); } @Test public void testEndpointRegistrationRequest() throws Exception { ChannelContext channelContextMock = Mockito.mock(ChannelContext.class); SyncRequest request = new SyncRequest(); request.setRequestId(REQUEST_ID); SyncRequestMetaData md = new SyncRequestMetaData(); md.setSdkToken(SDK_TOKEN); md.setEndpointPublicKeyHash(clientPublicKeyHash); md.setProfileHash(clientPublicKeyHash); request.setSyncRequestMetaData(md); ProfileSyncRequest profileSync = new ProfileSyncRequest(); profileSync.setEndpointPublicKey(clientPublicKey); profileSync.setProfileBody(ByteBuffer.wrap(PROFILE_BODY.getBytes())); request.setProfileSyncRequest(profileSync); whenSync(simpleResponse); MessageBuilder responseBuilder = Mockito.mock(MessageBuilder.class); ErrorBuilder errorBuilder = Mockito.mock(ErrorBuilder.class); SessionInitMessage message = toSignedRequest(UUID.randomUUID(), ChannelType.SYNC, channelContextMock, request, responseBuilder, errorBuilder); Assert.assertNotNull(akkaService.getActorSystem()); akkaService.process(message); Mockito.verify(operationsService, Mockito.timeout(TIMEOUT * 10).atLeastOnce()).syncProfile(Mockito.any(SyncContext.class), Mockito.any(ProfileClientSync.class)); Mockito.verify(responseBuilder, Mockito.timeout(TIMEOUT).atLeastOnce()) .build(Mockito.any(byte[].class), Mockito.any(boolean.class)); } @Test public void testEndpointUpdateRequest() throws Exception { ChannelContext channelContextMock = Mockito.mock(ChannelContext.class); SyncRequest request = new SyncRequest(); request.setRequestId(REQUEST_ID); SyncRequestMetaData md = new SyncRequestMetaData(); md.setSdkToken(SDK_TOKEN); md.setEndpointPublicKeyHash(clientPublicKeyHash); md.setProfileHash(clientPublicKeyHash); request.setSyncRequestMetaData(md); ProfileSyncRequest profileSync = new ProfileSyncRequest(); profileSync.setProfileBody(ByteBuffer.wrap(PROFILE_BODY.getBytes())); request.setProfileSyncRequest(profileSync); Mockito.when(cacheService.getEndpointKey(EndpointObjectHash.fromBytes(clientPublicKeyHash.array()))).thenReturn( clientPair.getPublic()); whenSync(simpleResponse); MessageBuilder responseBuilder = Mockito.mock(MessageBuilder.class); ErrorBuilder errorBuilder = Mockito.mock(ErrorBuilder.class); SessionInitMessage message = toSignedRequest(UUID.randomUUID(), ChannelType.SYNC, channelContextMock, request, responseBuilder, errorBuilder); Assert.assertNotNull(akkaService.getActorSystem()); akkaService.process(message); Mockito.verify(operationsService, Mockito.timeout(TIMEOUT * 10).atLeastOnce()).syncProfile(Mockito.any(SyncContext.class), Mockito.any(ProfileClientSync.class)); Mockito.verify(responseBuilder, Mockito.timeout(TIMEOUT).atLeastOnce()) .build(Mockito.any(byte[].class), Mockito.any(boolean.class)); } @Test public void testSyncRequest() throws Exception { ChannelContext channelContextMock = Mockito.mock(ChannelContext.class); SyncRequest request = new SyncRequest(); request.setRequestId(REQUEST_ID); SyncRequestMetaData md = new SyncRequestMetaData(); md.setSdkToken(SDK_TOKEN); md.setEndpointPublicKeyHash(clientPublicKeyHash); md.setProfileHash(clientPublicKeyHash); request.setSyncRequestMetaData(md); SyncContext holder = simpleResponse; Mockito.when(cacheService.getEndpointKey(EndpointObjectHash.fromBytes(clientPublicKeyHash.array()))).thenReturn( clientPair.getPublic()); whenSync(holder); MessageBuilder responseBuilder = Mockito.mock(MessageBuilder.class); ErrorBuilder errorBuilder = Mockito.mock(ErrorBuilder.class); SessionInitMessage message = toSignedRequest(UUID.randomUUID(), ChannelType.SYNC, channelContextMock, request, responseBuilder, errorBuilder); Assert.assertNotNull(akkaService.getActorSystem()); akkaService.process(message); Mockito.verify(operationsService, Mockito.timeout(TIMEOUT * 10).atLeastOnce()).syncProfile(Mockito.any(SyncContext.class), Mockito.any(ProfileClientSync.class)); Mockito.verify(responseBuilder, Mockito.timeout(TIMEOUT).atLeastOnce()) .build(Mockito.any(byte[].class), Mockito.any(boolean.class)); } @Test public void testMultipleSyncRequest() throws Exception { ChannelContext channelContextMock = Mockito.mock(ChannelContext.class); SyncRequest request = new SyncRequest(); request.setRequestId(REQUEST_ID); SyncRequestMetaData md = new SyncRequestMetaData(); md.setSdkToken(SDK_TOKEN); md.setEndpointPublicKeyHash(clientPublicKeyHash); md.setProfileHash(clientPublicKeyHash); request.setSyncRequestMetaData(md); SyncContext holder = simpleResponse; Mockito.when(cacheService.getEndpointKey(EndpointObjectHash.fromBytes(clientPublicKeyHash.array()))).thenReturn( clientPair.getPublic()); whenSync(holder); Assert.assertNotNull(akkaService.getActorSystem()); MessageBuilder responseBuilder = Mockito.mock(MessageBuilder.class); ErrorBuilder errorBuilder = Mockito.mock(ErrorBuilder.class); SessionInitMessage message1 = toSignedRequest(UUID.randomUUID(), ChannelType.SYNC, channelContextMock, request, responseBuilder, errorBuilder); SessionInitMessage message2 = toSignedRequest(UUID.randomUUID(), ChannelType.SYNC, channelContextMock, request, responseBuilder, errorBuilder); akkaService.process(message1); akkaService.process(message2); Mockito.verify(operationsService, Mockito.timeout(TIMEOUT * 10).atLeastOnce()).syncProfile(Mockito.any(SyncContext.class), Mockito.any(ProfileClientSync.class)); Mockito.verify(responseBuilder, Mockito.timeout(TIMEOUT).atLeast(2)).build(Mockito.any(byte[].class), Mockito.any(boolean.class)); } @Test public void testLongSyncRequest() throws Exception { ChannelContext channelContextMock = Mockito.mock(ChannelContext.class); SyncRequest request = new SyncRequest(); request.setRequestId(REQUEST_ID); SyncRequestMetaData md = new SyncRequestMetaData(); md.setSdkToken(SDK_TOKEN); md.setEndpointPublicKeyHash(clientPublicKeyHash); md.setProfileHash(clientPublicKeyHash); md.setTimeout(1000l); request.setSyncRequestMetaData(md); Mockito.when(cacheService.getEndpointKey(EndpointObjectHash.fromBytes(clientPublicKeyHash.array()))).thenReturn( clientPair.getPublic()); whenSync(noDeltaResponse); MessageBuilder responseBuilder = Mockito.mock(MessageBuilder.class); ErrorBuilder errorBuilder = Mockito.mock(ErrorBuilder.class); SessionInitMessage message = toSignedRequest(UUID.randomUUID(), ChannelType.SYNC_WITH_TIMEOUT, channelContextMock, request, responseBuilder, errorBuilder); Assert.assertNotNull(akkaService.getActorSystem()); akkaService.process(message); Mockito.verify(operationsService, Mockito.timeout(TIMEOUT).atLeastOnce()).syncProfile(Mockito.any(SyncContext.class), Mockito.any(ProfileClientSync.class)); Mockito.verify(responseBuilder, Mockito.timeout(TIMEOUT).atLeastOnce()) .build(Mockito.any(byte[].class), Mockito.any(boolean.class)); } private void whenSync(SyncContext response) throws GetDeltaException { Mockito.when(operationsService.syncProfile(Mockito.any(SyncContext.class), Mockito.any(ProfileClientSync.class))).thenReturn( response); Mockito.when( operationsService.processEndpointAttachDetachRequests(Mockito.any(SyncContext.class), Mockito.any(UserClientSync.class))) .thenReturn(response); Mockito.when(operationsService.processEventListenerRequests(Mockito.any(SyncContext.class), Mockito.any(EventClientSync.class))) .thenReturn(response); Mockito.when(operationsService.syncConfiguration(Mockito.any(SyncContext.class), Mockito.any(ConfigurationClientSync.class))) .thenReturn(response); Mockito.when(operationsService.syncNotification(Mockito.any(SyncContext.class), Mockito.any(NotificationClientSync.class))) .thenReturn(response); } private void whenSync(ClientSync request, SyncContext response) throws GetDeltaException { SyncContext context = new SyncContext(new ServerSync()); if (request.getClientSyncMetaData() != null) { request.getClientSyncMetaData().setApplicationToken(APP_TOKEN); } context.setRequestHash(request.hashCode()); Mockito.when(operationsService.syncProfile(context, request.getProfileSync())).thenReturn(response); Mockito.when(operationsService.processEndpointAttachDetachRequests(response, request.getUserSync())).thenReturn(response); Mockito.when(operationsService.processEventListenerRequests(response, request.getEventSync())).thenReturn(response); Mockito.when(operationsService.syncConfiguration(response, request.getConfigurationSync())).thenReturn(response); Mockito.when(operationsService.syncNotification(response, request.getNotificationSync())).thenReturn(response); } @Test public void testLongSyncNotification() throws Exception { ChannelContext channelContextMock = Mockito.mock(ChannelContext.class); SyncRequest request = new SyncRequest(); request.setRequestId(REQUEST_ID); SyncRequestMetaData md = buildSyncRequestMetaData(); request.setSyncRequestMetaData(md); ConfigurationSyncRequest csRequest = new ConfigurationSyncRequest(); request.setConfigurationSyncRequest(csRequest); Mockito.when(cacheService.getEndpointKey(EndpointObjectHash.fromBytes(clientPublicKeyHash.array()))).thenReturn( clientPair.getPublic()); whenSync(noDeltaResponse); MessageBuilder responseBuilder = Mockito.mock(MessageBuilder.class); ErrorBuilder errorBuilder = Mockito.mock(ErrorBuilder.class); SessionInitMessage message = toSignedRequest(UUID.randomUUID(), ChannelType.SYNC_WITH_TIMEOUT, channelContextMock, request, responseBuilder, errorBuilder); Assert.assertNotNull(akkaService.getActorSystem()); akkaService.process(message); Mockito.verify(operationsService, Mockito.timeout(TIMEOUT).atLeastOnce()).syncProfile(Mockito.any(SyncContext.class), Mockito.any(ProfileClientSync.class)); Mockito.when(applicationService.findAppById(APP_ID)).thenReturn(applicationDto); whenSync(deltaResponse); Notification thriftNotification = new Notification(); thriftNotification.setAppId(APP_ID); akkaService.onNotification(thriftNotification); Mockito.verify(responseBuilder, Mockito.timeout(TIMEOUT).atLeastOnce()) .build(Mockito.any(byte[].class), Mockito.any(boolean.class)); } @Test public void testLongSyncUnicastNotification() throws Exception { ChannelContext channelContextMock = Mockito.mock(ChannelContext.class); SyncRequest request = new SyncRequest(); request.setRequestId(REQUEST_ID); request.setSyncRequestMetaData(buildSyncRequestMetaData()); NotificationSyncRequest nfRequest = new NotificationSyncRequest(); request.setNotificationSyncRequest(nfRequest); whenSync(noDeltaResponse); MessageBuilder responseBuilder = Mockito.mock(MessageBuilder.class); ErrorBuilder errorBuilder = Mockito.mock(ErrorBuilder.class); SessionInitMessage message = toSignedRequest(UUID.randomUUID(), ChannelType.SYNC_WITH_TIMEOUT, channelContextMock, request, responseBuilder, errorBuilder); Assert.assertNotNull(akkaService.getActorSystem()); akkaService.process(message); Mockito.verify(operationsService, Mockito.timeout(TIMEOUT / 2).atLeastOnce()).syncProfile(Mockito.any(SyncContext.class), Mockito.any(ProfileClientSync.class)); Mockito.when( operationsService.updateSyncResponse(noDeltaResponse.getResponse(), new ArrayList<NotificationDto>(), UNICAST_NOTIFICATION_ID)).thenReturn(noDeltaResponse.getResponse()); Mockito.when(applicationService.findAppById(APP_ID)).thenReturn(applicationDto); Notification thriftNotification = new Notification(); thriftNotification.setAppId(APP_ID); thriftNotification.setUnicastNotificationId(UNICAST_NOTIFICATION_ID); thriftNotification.setKeyHash(clientPublicKeyHash.array()); akkaService.onNotification(thriftNotification); Mockito.verify(operationsService, Mockito.timeout(10 * TIMEOUT / 2).atLeastOnce()).updateSyncResponse( noDeltaResponse.getResponse(), new ArrayList<NotificationDto>(), UNICAST_NOTIFICATION_ID); Mockito.verify(responseBuilder, Mockito.timeout(TIMEOUT).atLeastOnce()) .build(Mockito.any(byte[].class), Mockito.any(boolean.class)); } @Test public void testLongSyncTopicNotificationOnStart() throws Exception { ChannelContext channelContextMock = Mockito.mock(ChannelContext.class); Mockito.when(applicationService.findAppById(APP_ID)).thenReturn(applicationDto); Notification thriftNotification = new Notification(); thriftNotification.setAppId(APP_ID); thriftNotification.setTopicId(TOPIC_ID); thriftNotification.setNotificationId(UNICAST_NOTIFICATION_ID); thriftNotification.setKeyHash(clientPublicKeyHash); akkaService.onNotification(thriftNotification); Mockito.when(notificationDeltaService.findNotificationById(UNICAST_NOTIFICATION_ID)).thenReturn(topicNotification); SyncRequest request = new SyncRequest(); request.setRequestId(REQUEST_ID); request.setSyncRequestMetaData(buildSyncRequestMetaData()); NotificationSyncRequest nfRequest = new NotificationSyncRequest(); request.setNotificationSyncRequest(nfRequest); MessageBuilder responseBuilder = Mockito.mock(MessageBuilder.class); ErrorBuilder errorBuilder = Mockito.mock(ErrorBuilder.class); whenSync(noDeltaResponseWithTopicState); Mockito.when( operationsService.updateSyncResponse(noDeltaResponseWithTopicState.getResponse(), Collections.singletonList(topicNotification), null)).thenReturn(noDeltaResponseWithTopicState.getResponse()); SessionInitMessage message = toSignedRequest(UUID.randomUUID(), ChannelType.SYNC_WITH_TIMEOUT, channelContextMock, request, responseBuilder, errorBuilder); Assert.assertNotNull(akkaService.getActorSystem()); akkaService.process(message); Mockito.verify(operationsService, Mockito.timeout(TIMEOUT / 2).atLeastOnce()).syncProfile(Mockito.any(SyncContext.class), Mockito.any(ProfileClientSync.class)); Mockito.verify(operationsService, Mockito.timeout(TIMEOUT / 2).atLeastOnce()).updateSyncResponse( noDeltaResponseWithTopicState.getResponse(), Collections.singletonList(topicNotification), null); Mockito.verify(responseBuilder, Mockito.timeout(TIMEOUT).atLeastOnce()) .build(Mockito.any(byte[].class), Mockito.any(boolean.class)); } @Test public void testLongSyncTopicNotification() throws Exception { ChannelContext channelContextMock = Mockito.mock(ChannelContext.class); SyncRequest request = new SyncRequest(); request.setRequestId(REQUEST_ID); request.setSyncRequestMetaData(buildSyncRequestMetaData()); NotificationSyncRequest nfRequest = new NotificationSyncRequest(); request.setNotificationSyncRequest(nfRequest); Mockito.when(applicationService.findAppById(APP_ID)).thenReturn(applicationDto); Mockito.when(notificationDeltaService.findNotificationById(UNICAST_NOTIFICATION_ID)).thenReturn(topicNotification); whenSync(noDeltaResponseWithTopicState); Mockito.when( operationsService.updateSyncResponse(noDeltaResponseWithTopicState.getResponse(), Collections.singletonList(topicNotification), null)).thenReturn(noDeltaResponseWithTopicState.getResponse()); MessageBuilder responseBuilder = Mockito.mock(MessageBuilder.class); ErrorBuilder errorBuilder = Mockito.mock(ErrorBuilder.class); SessionInitMessage message = toSignedRequest(UUID.randomUUID(), ChannelType.SYNC_WITH_TIMEOUT, channelContextMock, request, responseBuilder, errorBuilder); Assert.assertNotNull(akkaService.getActorSystem()); akkaService.process(message); Thread.sleep(3000); Notification thriftNotification = new Notification(); thriftNotification.setAppId(APP_ID); thriftNotification.setTopicId(TOPIC_ID); thriftNotification.setNotificationId(UNICAST_NOTIFICATION_ID); thriftNotification.setKeyHash(clientPublicKeyHash); akkaService.onNotification(thriftNotification); Mockito.verify(operationsService, Mockito.timeout(TIMEOUT / 2).atLeastOnce()).syncProfile(Mockito.any(SyncContext.class), Mockito.any(ProfileClientSync.class)); Mockito.verify(operationsService, Mockito.timeout(TIMEOUT / 2).atLeastOnce()).updateSyncResponse( noDeltaResponseWithTopicState.getResponse(), Collections.singletonList(topicNotification), null); Mockito.verify(responseBuilder, Mockito.timeout(TIMEOUT).atLeastOnce()) .build(Mockito.any(byte[].class), Mockito.any(boolean.class)); } @Test public void testRedirect() throws Exception { ChannelContext channelContextMock = Mockito.mock(ChannelContext.class); MessageEncoderDecoder crypt = new MessageEncoderDecoder(clientPair.getPrivate(), clientPair.getPublic(), serverPair.getPublic()); akkaService.onRedirectionRule(new RedirectionRule("testDNS".hashCode(), 123, 1.0, 0.0, 60000)); Thread.sleep(1000); SyncRequest request = new SyncRequest(); request.setRequestId(32); request.setSyncRequestMetaData(buildSyncRequestMetaData()); MessageBuilder responseBuilder = Mockito.mock(MessageBuilder.class); ErrorBuilder errorBuilder = Mockito.mock(ErrorBuilder.class); SessionInitMessage message = toSignedRequest(UUID.randomUUID(), ChannelType.SYNC_WITH_TIMEOUT, channelContextMock, request, responseBuilder, errorBuilder, crypt); akkaService.process(message); SyncResponse response = new SyncResponse(); response.setRequestId(request.getRequestId()); response.setStatus(SyncResponseResultType.REDIRECT); response.setRedirectSyncResponse(new RedirectSyncResponse("testDNS".hashCode())); Mockito.verify(operationsService, Mockito.timeout(TIMEOUT / 2).never()).syncProfile(Mockito.any(SyncContext.class), Mockito.any(ProfileClientSync.class)); AvroByteArrayConverter<SyncResponse> responseConverter = new AvroByteArrayConverter<>(SyncResponse.class); byte[] encodedData = crypt.encodeData(responseConverter.toByteArray(response)); Mockito.verify(responseBuilder, Mockito.timeout(TIMEOUT).atLeastOnce()).build(encodedData, true); } @Test public void testRedirectSessionRequest() throws Exception { ChannelContext channelContextMock = Mockito.mock(ChannelContext.class); MessageEncoderDecoder crypt = new MessageEncoderDecoder(clientPair.getPrivate(), clientPair.getPublic(), serverPair.getPublic()); akkaService.onRedirectionRule(new RedirectionRule("testDNS".hashCode(), 123, 0.0, 1.0, 60000)); Thread.sleep(1000); SyncRequest request = new SyncRequest(); request.setRequestId(32); request.setSyncRequestMetaData(buildSyncRequestMetaData()); final MessageBuilder responseBuilder = Mockito.mock(MessageBuilder.class); final ErrorBuilder errorBuilder = Mockito.mock(ErrorBuilder.class); AvroByteArrayConverter<SyncRequest> requestConverter = new AvroByteArrayConverter<>(SyncRequest.class); final org.kaaproject.kaa.common.channels.protocols.kaatcp.messages.SyncRequest kaaSync = new org.kaaproject.kaa.common.channels.protocols.kaatcp.messages.SyncRequest( crypt.encodeData(requestConverter.toByteArray(request)), false, true); final SessionInfo session = new SessionInfo(UUID.randomUUID(), Constants.KAA_PLATFORM_PROTOCOL_AVRO_ID, channelContextMock, ChannelType.ASYNC, crypt.getSessionCipherPair(), EndpointObjectHash.fromBytes(clientPublicKey.array()), APP_TOKEN, SDK_TOKEN, 100, true); SessionAwareMessage message = new SessionAwareMessage() { @Override public SessionInfo getSessionInfo() { return session; } @Override public int getPlatformId() { return session.getPlatformId(); } @Override public UUID getChannelUuid() { return session.getUuid(); } @Override public ChannelType getChannelType() { return session.getChannelType(); } @Override public ChannelContext getChannelContext() { return session.getCtx(); } @Override public boolean isEncrypted() { return session.isEncrypted(); } @Override public MessageBuilder getMessageBuilder() { return responseBuilder; } @Override public ErrorBuilder getErrorBuilder() { return errorBuilder; } @Override public byte[] getEncodedMessageData() { return kaaSync.getAvroObject(); } }; akkaService.process(message); SyncResponse response = new SyncResponse(); response.setRequestId(request.getRequestId()); response.setStatus(SyncResponseResultType.REDIRECT); response.setRedirectSyncResponse(new RedirectSyncResponse("testDNS".hashCode())); Mockito.verify(operationsService, Mockito.timeout(TIMEOUT / 2).never()).syncProfile(Mockito.any(SyncContext.class), Mockito.any(ProfileClientSync.class)); AvroByteArrayConverter<SyncResponse> responseConverter = new AvroByteArrayConverter<>(SyncResponse.class); byte[] encodedData = crypt.encodeData(responseConverter.toByteArray(response)); Mockito.verify(responseBuilder, Mockito.timeout(TIMEOUT).atLeastOnce()).build(encodedData, true); } @Test public void testRedirectExpire() throws Exception { ChannelContext channelContextMock = Mockito.mock(ChannelContext.class); MessageEncoderDecoder crypt = new MessageEncoderDecoder(clientPair.getPrivate(), clientPair.getPublic(), serverPair.getPublic()); akkaService.onRedirectionRule(new RedirectionRule("testDNS".hashCode(), 123, 1.0, 1.0, 1000)); Thread.sleep(2000); SyncRequest request = new SyncRequest(); request.setRequestId(32); request.setSyncRequestMetaData(buildSyncRequestMetaData()); MessageBuilder responseBuilder = Mockito.mock(MessageBuilder.class); ErrorBuilder errorBuilder = Mockito.mock(ErrorBuilder.class); SessionInitMessage message = toSignedRequest(UUID.randomUUID(), ChannelType.SYNC_WITH_TIMEOUT, channelContextMock, request, responseBuilder, errorBuilder, crypt); whenSync(noDeltaResponseWithTopicState); akkaService.process(message); SyncResponse response = new SyncResponse(); response.setRequestId(request.getRequestId()); response.setStatus(SyncResponseResultType.REDIRECT); response.setRedirectSyncResponse(new RedirectSyncResponse("testDNS".hashCode())); Mockito.verify(operationsService, Mockito.timeout(TIMEOUT / 2).atLeastOnce()).syncProfile(Mockito.any(SyncContext.class), Mockito.any(ProfileClientSync.class)); } @Test public void testEndpointEventBasic() throws Exception { ChannelContext channelContextMock = Mockito.mock(ChannelContext.class); EndpointProfileDto sourceProfileMock = Mockito.mock(EndpointProfileDto.class); EndpointProfileDto targetProfileMock = Mockito.mock(EndpointProfileDto.class); EventClassFamilyVersionStateDto ecfVdto = new EventClassFamilyVersionStateDto(); ecfVdto.setEcfId(ECF1_ID); ecfVdto.setVersion(ECF1_VERSION); Event event = new Event(0, FQN1, ByteBuffer.wrap(new byte[0]), Base64Util.encode(clientPublicKeyHash.array()), null); SyncRequest sourceRequest = new SyncRequest(); sourceRequest.setRequestId(REQUEST_ID); SyncRequestMetaData md = new SyncRequestMetaData(); md.setSdkToken(SDK_TOKEN); md.setEndpointPublicKeyHash(clientPublicKeyHash); md.setProfileHash(clientPublicKeyHash); md.setTimeout(TIMEOUT * 1L); sourceRequest.setSyncRequestMetaData(md); EventSyncRequest eventRequest = new EventSyncRequest(); eventRequest.setEvents(Arrays.asList(event)); sourceRequest.setEventSyncRequest(eventRequest); ServerSync sourceResponse = new ServerSync(); sourceResponse.setStatus(org.kaaproject.kaa.server.sync.SyncStatus.SUCCESS); SyncContext sourceResponseHolder = new SyncContext(sourceResponse); sourceResponseHolder.setEndpointProfile(sourceProfileMock); SyncRequest targetRequest = new SyncRequest(); targetRequest.setRequestId(REQUEST_ID); md = new SyncRequestMetaData(); md.setSdkToken(SDK_TOKEN); md.setEndpointPublicKeyHash(targetPublicKeyHash); md.setProfileHash(targetPublicKeyHash); md.setTimeout(TIMEOUT * 1L); targetRequest.setSyncRequestMetaData(md); targetRequest.setEventSyncRequest(new EventSyncRequest()); ServerSync targetResponse = new ServerSync(); targetResponse.setRequestId(REQUEST_ID); targetResponse.setStatus(org.kaaproject.kaa.server.sync.SyncStatus.SUCCESS); SyncContext targetResponseHolder = new SyncContext(targetResponse); targetResponseHolder.setEndpointProfile(targetProfileMock); whenSync(AvroEncDec.convert(sourceRequest), sourceResponseHolder); whenSync(AvroEncDec.convert(targetRequest), targetResponseHolder); when(sourceProfileMock.getEndpointUserId()).thenReturn(USER_ID); when(sourceProfileMock.getEndpointKeyHash()).thenReturn(clientPublicKeyHash.array()); when(sourceProfileMock.getEcfVersionStates()).thenReturn(Arrays.asList(ecfVdto)); when(targetProfileMock.getEndpointUserId()).thenReturn(USER_ID); when(targetProfileMock.getEndpointKeyHash()).thenReturn(targetPublicKeyHash.array()); when(targetProfileMock.getEcfVersionStates()).thenReturn(Arrays.asList(ecfVdto)); when(cacheService.getEventClassFamilyIdByEventClassFqn(new EventClassFqnKey(TENANT_ID, FQN1))).thenReturn(ECF1_ID); RouteTableKey routeKey = new RouteTableKey(APP_TOKEN, new EventClassFamilyVersion(ECF1_ID, ECF1_VERSION)); when(cacheService.getRouteKeys(new EventClassFqnVersion(TENANT_ID, FQN1, ECF1_VERSION))) .thenReturn(Collections.singleton(routeKey)); Assert.assertNotNull(akkaService.getActorSystem()); MessageBuilder responseBuilder = Mockito.mock(MessageBuilder.class); ErrorBuilder errorBuilder = Mockito.mock(ErrorBuilder.class); MessageEncoderDecoder sourceCrypt = new MessageEncoderDecoder(clientPair.getPrivate(), clientPair.getPublic(), serverPair.getPublic()); SessionInitMessage sourceMessage = toSignedRequest(UUID.randomUUID(), ChannelType.SYNC_WITH_TIMEOUT, channelContextMock, sourceRequest, responseBuilder, errorBuilder, sourceCrypt); akkaService.process(sourceMessage); // sourceRequest Mockito.verify(operationsService, Mockito.timeout(TIMEOUT).atLeastOnce()).syncProfile(Mockito.any(SyncContext.class), Mockito.any(ProfileClientSync.class)); MessageEncoderDecoder targetCrypt = new MessageEncoderDecoder(targetPair.getPrivate(), targetPair.getPublic(), serverPair.getPublic()); SessionInitMessage targetMessage = toSignedRequest(UUID.randomUUID(), ChannelType.SYNC_WITH_TIMEOUT, channelContextMock, targetRequest, responseBuilder, errorBuilder, targetCrypt); akkaService.process(targetMessage); // targetRequest Mockito.verify(operationsService, Mockito.timeout(TIMEOUT).atLeastOnce()).syncProfile(Mockito.any(SyncContext.class), Mockito.any(ProfileClientSync.class)); SyncResponse eventResponse = new SyncResponse(); eventResponse.setRequestId(REQUEST_ID); eventResponse.setStatus(SyncResponseResultType.SUCCESS); eventResponse.setEventSyncResponse(new EventSyncResponse()); eventResponse.getEventSyncResponse().setEvents(Arrays.asList(event)); AvroByteArrayConverter<SyncResponse> responseConverter = new AvroByteArrayConverter<>(SyncResponse.class); byte[] response = responseConverter.toByteArray(eventResponse); byte[] encodedData = targetCrypt.encodeData(response); Mockito.verify(responseBuilder, Mockito.timeout(TIMEOUT).atLeastOnce()).build(encodedData, true); } @Test public void testEndpointEventSeqNumberBasic() throws Exception { ChannelContext channelContextMock = Mockito.mock(ChannelContext.class); EndpointProfileDto sourceProfileMock = Mockito.mock(EndpointProfileDto.class); EventClassFamilyVersionStateDto ecfVdto = new EventClassFamilyVersionStateDto(); ecfVdto.setEcfId(ECF1_ID); ecfVdto.setVersion(ECF1_VERSION); SyncRequest sourceRequest = new SyncRequest(); sourceRequest.setRequestId(REQUEST_ID); sourceRequest.setSyncRequestMetaData(buildSyncRequestMetaData()); EventSyncRequest eventRequest = new EventSyncRequest(); eventRequest.setEventSequenceNumberRequest(new EventSequenceNumberRequest()); sourceRequest.setEventSyncRequest(eventRequest); ServerSync sourceResponse = new ServerSync(); sourceResponse.setRequestId(REQUEST_ID); sourceResponse.setStatus(org.kaaproject.kaa.server.sync.SyncStatus.SUCCESS); SyncContext sourceResponseHolder = new SyncContext(sourceResponse); sourceResponseHolder.setEndpointProfile(sourceProfileMock); whenSync(AvroEncDec.convert(sourceRequest), sourceResponseHolder); when(sourceProfileMock.getEndpointUserId()).thenReturn(USER_ID); when(sourceProfileMock.getEndpointKeyHash()).thenReturn(clientPublicKeyHash.array()); when(sourceProfileMock.getEcfVersionStates()).thenReturn(Arrays.asList(ecfVdto)); when(cacheService.getEventClassFamilyIdByEventClassFqn(new EventClassFqnKey(TENANT_ID, FQN1))).thenReturn(ECF1_ID); RouteTableKey routeKey = new RouteTableKey(APP_TOKEN, new EventClassFamilyVersion(ECF1_ID, ECF1_VERSION)); when(cacheService.getRouteKeys(new EventClassFqnVersion(TENANT_ID, FQN1, ECF1_VERSION))) .thenReturn(Collections.singleton(routeKey)); Assert.assertNotNull(akkaService.getActorSystem()); MessageBuilder responseBuilder = Mockito.mock(MessageBuilder.class); ErrorBuilder errorBuilder = Mockito.mock(ErrorBuilder.class); MessageEncoderDecoder sourceCrypt = new MessageEncoderDecoder(clientPair.getPrivate(), clientPair.getPublic(), serverPair.getPublic()); SessionInitMessage sourceMessage = toSignedRequest(UUID.randomUUID(), ChannelType.SYNC_WITH_TIMEOUT, channelContextMock, sourceRequest, responseBuilder, errorBuilder, sourceCrypt); akkaService.process(sourceMessage); // sourceRequest Mockito.verify(operationsService, Mockito.timeout(TIMEOUT).atLeastOnce()).syncProfile(Mockito.any(SyncContext.class), Mockito.any(ProfileClientSync.class)); SyncResponse eventResponse = new SyncResponse(); eventResponse.setRequestId(REQUEST_ID); eventResponse.setStatus(SyncResponseResultType.SUCCESS); eventResponse.setEventSyncResponse(new EventSyncResponse()); eventResponse.getEventSyncResponse().setEventSequenceNumberResponse(new EventSequenceNumberResponse(0)); AvroByteArrayConverter<SyncResponse> responseConverter = new AvroByteArrayConverter<>(SyncResponse.class); byte[] response = responseConverter.toByteArray(eventResponse); LOG.trace("Response to compare {}", Arrays.toString(response)); byte[] encodedData = sourceCrypt.encodeData(response); Mockito.verify(responseBuilder, Mockito.timeout(TIMEOUT).atLeastOnce()).build(encodedData, true); } @Test public void testRemoteIncomingEndpointEventBasic() throws Exception { ChannelContext channelContextMock = Mockito.mock(ChannelContext.class); EndpointProfileDto targetProfileMock = Mockito.mock(EndpointProfileDto.class); EventClassFamilyVersionStateDto ecfVdto = new EventClassFamilyVersionStateDto(); ecfVdto.setEcfId(ECF1_ID); ecfVdto.setVersion(ECF1_VERSION); SyncRequest targetRequest = new SyncRequest(); targetRequest.setRequestId(REQUEST_ID); targetRequest.setSyncRequestMetaData(buildSyncRequestMetaData(targetPublicKeyHash)); targetRequest.setEventSyncRequest(new EventSyncRequest()); ServerSync targetResponse = new ServerSync(); targetResponse.setStatus(org.kaaproject.kaa.server.sync.SyncStatus.SUCCESS); SyncContext targetResponseHolder = new SyncContext(targetResponse); targetResponseHolder.setEndpointProfile(targetProfileMock); whenSync(AvroEncDec.convert(targetRequest), targetResponseHolder); when(targetProfileMock.getEndpointUserId()).thenReturn(USER_ID); when(targetProfileMock.getEndpointKeyHash()).thenReturn(targetPublicKeyHash.array()); when(targetProfileMock.getEcfVersionStates()).thenReturn(Arrays.asList(ecfVdto)); when(cacheService.getEventClassFamilyIdByEventClassFqn(new EventClassFqnKey(TENANT_ID, FQN1))).thenReturn(ECF1_ID); RouteTableKey routeKey = new RouteTableKey(APP_TOKEN, new EventClassFamilyVersion(ECF1_ID, ECF1_VERSION)); when(cacheService.getRouteKeys(new EventClassFqnVersion(TENANT_ID, FQN1, ECF1_VERSION))) .thenReturn(Collections.singleton(routeKey)); Assert.assertNotNull(akkaService.getActorSystem()); MessageBuilder responseBuilder = Mockito.mock(MessageBuilder.class); ErrorBuilder errorBuilder = Mockito.mock(ErrorBuilder.class); MessageEncoderDecoder targetCrypt = new MessageEncoderDecoder(targetPair.getPrivate(), targetPair.getPublic(), serverPair.getPublic()); SessionInitMessage targetMessage = toSignedRequest(UUID.randomUUID(), ChannelType.SYNC_WITH_TIMEOUT, channelContextMock, targetRequest, responseBuilder, errorBuilder, targetCrypt); akkaService.process(targetMessage); Mockito.verify(operationsService, Mockito.timeout(TIMEOUT).atLeastOnce()).syncProfile(Mockito.any(SyncContext.class), Mockito.any(ProfileClientSync.class)); org.kaaproject.kaa.server.sync.Event event = new org.kaaproject.kaa.server.sync.Event(0, FQN1, ByteBuffer.wrap(new byte[0]), null, null); EndpointEvent endpointEvent = new EndpointEvent(EndpointObjectHash.fromBytes(clientPublicKeyHash.array()), event, UUID.randomUUID(), System.currentTimeMillis(), ECF1_VERSION); RemoteEndpointEvent remoteEvent = new RemoteEndpointEvent(TENANT_ID, USER_ID, endpointEvent, new RouteTableAddress( EndpointObjectHash.fromBytes(targetPublicKeyHash.array()), APP_TOKEN, "SERVER1")); akkaService.getListener().onEvent(remoteEvent); event = new org.kaaproject.kaa.server.sync.Event(0, FQN1, ByteBuffer.wrap(new byte[0]), null, Base64Util.encode(targetPublicKeyHash .array())); ServerSync eventResponse = new ServerSync(); eventResponse.setStatus(org.kaaproject.kaa.server.sync.SyncStatus.SUCCESS); eventResponse.setEventSync(new EventServerSync()); eventResponse.getEventSync().setEvents(Arrays.asList(event)); AvroByteArrayConverter<SyncResponse> responseConverter = new AvroByteArrayConverter<>(SyncResponse.class); byte[] response = responseConverter.toByteArray(AvroEncDec.convert(eventResponse)); byte[] encodedData = targetCrypt.encodeData(response); Mockito.verify(responseBuilder, Mockito.timeout(TIMEOUT).atLeastOnce()).build(encodedData, true); } @Test public void testRemoteOutcomingEndpointEventBasic() throws Exception { ChannelContext channelContextMock = Mockito.mock(ChannelContext.class); EndpointProfileDto sourceProfileMock = Mockito.mock(EndpointProfileDto.class); EventClassFamilyVersionStateDto ecfVdto = new EventClassFamilyVersionStateDto(); ecfVdto.setEcfId(ECF1_ID); ecfVdto.setVersion(ECF1_VERSION); Event event = new Event(0, FQN1, ByteBuffer.wrap(new byte[0]), Base64Util.encode(clientPublicKeyHash.array()), null); SyncRequest sourceRequest = new SyncRequest(); sourceRequest.setRequestId(REQUEST_ID); sourceRequest.setSyncRequestMetaData(buildSyncRequestMetaData(clientPublicKeyHash)); EventSyncRequest eventRequest = new EventSyncRequest(); eventRequest.setEvents(Arrays.asList(event)); sourceRequest.setEventSyncRequest(eventRequest); ServerSync sourceResponse = new ServerSync(); sourceResponse.setStatus(org.kaaproject.kaa.server.sync.SyncStatus.SUCCESS); SyncContext sourceResponseHolder = new SyncContext(sourceResponse); sourceResponseHolder.setEndpointProfile(sourceProfileMock); whenSync(AvroEncDec.convert(sourceRequest), sourceResponseHolder); when(sourceProfileMock.getEndpointUserId()).thenReturn(USER_ID); when(sourceProfileMock.getEndpointKeyHash()).thenReturn(clientPublicKeyHash.array()); when(sourceProfileMock.getEcfVersionStates()).thenReturn(Arrays.asList(ecfVdto)); when(cacheService.getEventClassFamilyIdByEventClassFqn(new EventClassFqnKey(TENANT_ID, FQN1))).thenReturn(ECF1_ID); RouteTableKey routeKey = new RouteTableKey(APP_TOKEN, new EventClassFamilyVersion(ECF1_ID, ECF1_VERSION)); when(cacheService.getRouteKeys(new EventClassFqnVersion(TENANT_ID, FQN1, ECF1_VERSION))) .thenReturn(Collections.singleton(routeKey)); Assert.assertNotNull(akkaService.getActorSystem()); MessageBuilder responseBuilder = Mockito.mock(MessageBuilder.class); ErrorBuilder errorBuilder = Mockito.mock(ErrorBuilder.class); MessageEncoderDecoder sourceCrypt = new MessageEncoderDecoder(clientPair.getPrivate(), clientPair.getPublic(), serverPair.getPublic()); SessionInitMessage sourceMessage = toSignedRequest(UUID.randomUUID(), ChannelType.SYNC_WITH_TIMEOUT, channelContextMock, sourceRequest, responseBuilder, errorBuilder, sourceCrypt); akkaService.process(sourceMessage); Mockito.verify(operationsService, Mockito.timeout(TIMEOUT).atLeastOnce()).syncProfile(Mockito.any(SyncContext.class), Mockito.any(ProfileClientSync.class)); UserRouteInfo userRouteInfo = new UserRouteInfo(TENANT_ID, USER_ID, SERVER2, RouteOperation.ADD); akkaService.getListener().onUserRouteInfo(userRouteInfo); RouteTableAddress remoteAddress = new RouteTableAddress(EndpointObjectHash.fromBytes(targetPublicKeyHash.array()), APP_TOKEN, SERVER2); RouteInfo routeInfo = new RouteInfo(TENANT_ID, USER_ID, remoteAddress, Arrays.asList(new EventClassFamilyVersion(ECF1_ID, ECF1_VERSION))); TimeUnit.SECONDS.sleep(2); akkaService.getListener().onRouteInfo(routeInfo); Mockito.verify(eventService, Mockito.timeout(TIMEOUT).atLeastOnce()).sendEvent(Mockito.any(RemoteEndpointEvent.class)); } @Test public void testLogSyncRequest() throws Exception { ChannelContext channelContextMock = Mockito.mock(ChannelContext.class); SyncRequest request = new SyncRequest(); request.setRequestId(REQUEST_ID); SyncRequestMetaData md = new SyncRequestMetaData(); md.setSdkToken(SDK_TOKEN); md.setEndpointPublicKeyHash(clientPublicKeyHash); md.setProfileHash(clientPublicKeyHash); md.setTimeout(1000l); request.setSyncRequestMetaData(md); LogSyncRequest logRequest = new LogSyncRequest(REQUEST_ID, Collections.singletonList(new LogEntry(ByteBuffer.wrap("String" .getBytes())))); request.setLogSyncRequest(logRequest); whenSync(noDeltaResponseWithTopicState); LogAppender mockAppender = Mockito.mock(LogAppender.class); Mockito.when(logAppenderService.getApplicationAppenders(APP_ID)).thenReturn(Collections.singletonList(mockAppender)); Mockito.when(logAppenderService.getLogSchema(Mockito.anyString(), Mockito.anyInt())).thenReturn(Mockito.mock(LogSchema.class)); Mockito.when(mockAppender.isSchemaVersionSupported(Mockito.anyInt())).thenReturn(true); MessageBuilder responseBuilder = Mockito.mock(MessageBuilder.class); ErrorBuilder errorBuilder = Mockito.mock(ErrorBuilder.class); SessionInitMessage message = toSignedRequest(UUID.randomUUID(), ChannelType.SYNC_WITH_TIMEOUT, channelContextMock, request, responseBuilder, errorBuilder); Assert.assertNotNull(akkaService.getActorSystem()); akkaService.process(message); Mockito.verify(operationsService, Mockito.timeout(TIMEOUT).atLeastOnce()).syncProfile(Mockito.any(SyncContext.class), Mockito.any(ProfileClientSync.class)); Mockito.verify(logAppenderService, Mockito.timeout(TIMEOUT).atLeastOnce()).getLogSchema(APP_ID, 44); Mockito.verify(mockAppender, Mockito.timeout(TIMEOUT).atLeastOnce()).doAppend(Mockito.any(LogEventPack.class), Mockito.any(LogDeliveryCallback.class)); Mockito.verify(responseBuilder, Mockito.timeout(TIMEOUT).atLeastOnce()) .build(Mockito.any(byte[].class), Mockito.any(boolean.class)); } @Test public void testUserChange() throws Exception { ChannelContext channelContextMock = Mockito.mock(ChannelContext.class); MessageEncoderDecoder targetCrypt = new MessageEncoderDecoder(targetPair.getPrivate(), targetPair.getPublic(), serverPair.getPublic()); EndpointProfileDto targetProfileMock = Mockito.mock(EndpointProfileDto.class); EventClassFamilyVersionStateDto ecfVdto = new EventClassFamilyVersionStateDto(); ecfVdto.setEcfId(ECF1_ID); ecfVdto.setVersion(ECF1_VERSION); SyncRequest targetRequest = new SyncRequest(); targetRequest.setRequestId(REQUEST_ID); targetRequest.setSyncRequestMetaData(buildSyncRequestMetaData(targetPublicKeyHash)); targetRequest.setEventSyncRequest(new EventSyncRequest()); ServerSync targetResponse = new ServerSync(); targetResponse.setStatus(org.kaaproject.kaa.server.sync.SyncStatus.SUCCESS); SyncContext targetResponseHolder = new SyncContext(targetResponse); targetResponseHolder.setEndpointProfile(targetProfileMock); whenSync(AvroEncDec.convert(targetRequest), targetResponseHolder); when(targetProfileMock.getEndpointUserId()).thenReturn(USER_ID); when(targetProfileMock.getEndpointKeyHash()).thenReturn(targetPublicKeyHash.array()); when(targetProfileMock.getEcfVersionStates()).thenReturn(Arrays.asList(ecfVdto)); when(cacheService.getEventClassFamilyIdByEventClassFqn(new EventClassFqnKey(TENANT_ID, FQN1))).thenReturn(ECF1_ID); RouteTableKey routeKey = new RouteTableKey(APP_TOKEN, new EventClassFamilyVersion(ECF1_ID, ECF1_VERSION)); when(cacheService.getRouteKeys(new EventClassFqnVersion(TENANT_ID, FQN1, ECF1_VERSION))) .thenReturn(Collections.singleton(routeKey)); Assert.assertNotNull(akkaService.getActorSystem()); MessageBuilder responseBuilder = Mockito.mock(MessageBuilder.class); ErrorBuilder errorBuilder = Mockito.mock(ErrorBuilder.class); SessionInitMessage message = toSignedRequest(UUID.randomUUID(), ChannelType.SYNC_WITH_TIMEOUT, channelContextMock, targetRequest, responseBuilder, errorBuilder, targetCrypt); akkaService.process(message); Mockito.verify(operationsService, Mockito.timeout(TIMEOUT).atLeastOnce()).syncProfile(Mockito.any(SyncContext.class), Mockito.any(ProfileClientSync.class)); Mockito.verify(eventService, Mockito.timeout(TIMEOUT).atLeastOnce()).sendUserRouteInfo(new UserRouteInfo(TENANT_ID, USER_ID)); UserRouteInfo userRouteInfo = new UserRouteInfo(TENANT_ID, USER_ID, SERVER2, RouteOperation.ADD); akkaService.getListener().onUserRouteInfo(userRouteInfo); TimeUnit.SECONDS.sleep(2); RouteTableAddress remoteAddress = new RouteTableAddress(EndpointObjectHash.fromBytes(clientPublicKeyHash.array()), APP_TOKEN, SERVER2); RouteInfo remoteRouteInfo = new RouteInfo(TENANT_ID, USER_ID, remoteAddress, Arrays.asList(new EventClassFamilyVersion(ECF1_ID, ECF1_VERSION))); TimeUnit.SECONDS.sleep(2); akkaService.getListener().onRouteInfo(remoteRouteInfo); RouteTableAddress localAddress = new RouteTableAddress(EndpointObjectHash.fromBytes(targetPublicKeyHash.array()), APP_TOKEN, null); RouteInfo localRouteInfo = new RouteInfo(TENANT_ID, USER_ID, localAddress, Arrays.asList(new EventClassFamilyVersion(ECF1_ID, ECF1_VERSION))); Mockito.verify(eventService, Mockito.timeout(TIMEOUT).atLeastOnce()).sendRouteInfo(Collections.singletonList(localRouteInfo), SERVER2); targetRequest = new SyncRequest(); targetRequest.setRequestId(REQUEST_ID); targetRequest.setSyncRequestMetaData(buildSyncRequestMetaData(targetPublicKeyHash)); targetResponse = new ServerSync(); targetResponse.setStatus(org.kaaproject.kaa.server.sync.SyncStatus.SUCCESS); targetResponseHolder = new SyncContext(targetResponse); targetResponseHolder.setEndpointProfile(targetProfileMock); when(targetProfileMock.getEndpointUserId()).thenReturn(USER_ID + "2"); whenSync(AvroEncDec.convert(targetRequest), targetResponseHolder); SessionInitMessage targetMessage = toSignedRequest(UUID.randomUUID(), ChannelType.SYNC_WITH_TIMEOUT, channelContextMock, targetRequest, responseBuilder, errorBuilder, targetCrypt); akkaService.process(targetMessage); Mockito.verify(eventService, Mockito.timeout(TIMEOUT).atLeastOnce()).sendUserRouteInfo(new UserRouteInfo(TENANT_ID, USER_ID + "2")); Mockito.verify(eventService, Mockito.timeout(TIMEOUT).atLeastOnce()).sendRouteInfo( RouteInfo.deleteRouteFromAddress(TENANT_ID, USER_ID, localAddress), SERVER2); } @Test public void testEndpointAttach() throws Exception { ChannelContext channelContextMock = Mockito.mock(ChannelContext.class); MessageEncoderDecoder targetCrypt = new MessageEncoderDecoder(targetPair.getPrivate(), targetPair.getPublic(), serverPair.getPublic()); EndpointProfileDto targetProfileMock = Mockito.mock(EndpointProfileDto.class); EventClassFamilyVersionStateDto ecfVdto = new EventClassFamilyVersionStateDto(); ecfVdto.setEcfId(ECF1_ID); ecfVdto.setVersion(ECF1_VERSION); SyncRequest targetRequest = new SyncRequest(); targetRequest.setRequestId(REQUEST_ID); targetRequest.setSyncRequestMetaData(buildSyncRequestMetaData(targetPublicKeyHash)); targetRequest.setEventSyncRequest(new EventSyncRequest()); ServerSync targetResponse = new ServerSync(); targetResponse.setRequestId(REQUEST_ID); targetResponse.setStatus(org.kaaproject.kaa.server.sync.SyncStatus.SUCCESS); targetResponse.setUserSync(new UserServerSync()); SyncContext targetResponseHolder = new SyncContext(targetResponse); targetResponseHolder.setEndpointProfile(targetProfileMock); whenSync(AvroEncDec.convert(targetRequest), targetResponseHolder); when(targetProfileMock.getEndpointUserId()).thenReturn(USER_ID); when(targetProfileMock.getEndpointKeyHash()).thenReturn(targetPublicKeyHash.array()); when(targetProfileMock.getEcfVersionStates()).thenReturn(Arrays.asList(ecfVdto)); when(cacheService.getEventClassFamilyIdByEventClassFqn(new EventClassFqnKey(TENANT_ID, FQN1))).thenReturn(ECF1_ID); RouteTableKey routeKey = new RouteTableKey(APP_TOKEN, new EventClassFamilyVersion(ECF1_ID, ECF1_VERSION)); when(cacheService.getRouteKeys(new EventClassFqnVersion(TENANT_ID, FQN1, ECF1_VERSION))) .thenReturn(Collections.singleton(routeKey)); Assert.assertNotNull(akkaService.getActorSystem()); MessageBuilder responseBuilder = Mockito.mock(MessageBuilder.class); ErrorBuilder errorBuilder = Mockito.mock(ErrorBuilder.class); SessionInitMessage targetMessage = toSignedRequest(UUID.randomUUID(), ChannelType.SYNC_WITH_TIMEOUT, channelContextMock, targetRequest, responseBuilder, errorBuilder, targetCrypt); akkaService.process(targetMessage); Mockito.verify(operationsService, Mockito.timeout(TIMEOUT).atLeastOnce()).syncProfile(Mockito.any(SyncContext.class), Mockito.any(ProfileClientSync.class)); Mockito.verify(eventService, Mockito.timeout(TIMEOUT).atLeastOnce()).sendUserRouteInfo(new UserRouteInfo(TENANT_ID, USER_ID)); EndpointProfileDto sourceProfileMock = Mockito.mock(EndpointProfileDto.class); SyncRequest sourceRequest = new SyncRequest(); sourceRequest.setRequestId(REQUEST_ID); sourceRequest.setSyncRequestMetaData(buildSyncRequestMetaData(clientPublicKeyHash)); sourceRequest.setEventSyncRequest(new EventSyncRequest()); UserSyncRequest userSyncRequest = new UserSyncRequest(); EndpointAttachRequest eaRequest = new EndpointAttachRequest(REQUEST_ID, "token"); userSyncRequest.setEndpointAttachRequests(Collections.singletonList(eaRequest)); sourceRequest.setUserSyncRequest(userSyncRequest); ServerSync sourceResponse = new ServerSync(); sourceResponse.setRequestId(REQUEST_ID); sourceResponse.setStatus(org.kaaproject.kaa.server.sync.SyncStatus.SUCCESS); UserServerSync userSyncResponse = new UserServerSync(); userSyncResponse.setEndpointAttachResponses(Collections.singletonList(new org.kaaproject.kaa.server.sync.EndpointAttachResponse( REQUEST_ID, Base64Util.encode(targetPublicKeyHash.array()), org.kaaproject.kaa.server.sync.SyncStatus.SUCCESS))); sourceResponse.setUserSync(userSyncResponse); SyncContext sourceResponseHolder = new SyncContext(sourceResponse); sourceResponseHolder.setEndpointProfile(sourceProfileMock); whenSync(AvroEncDec.convert(sourceRequest), sourceResponseHolder); when(sourceProfileMock.getEndpointUserId()).thenReturn(USER_ID); when(sourceProfileMock.getEndpointKeyHash()).thenReturn(clientPublicKeyHash.array()); when(sourceProfileMock.getEcfVersionStates()).thenReturn(Arrays.asList(ecfVdto)); MessageBuilder sourceResponseBuilder = Mockito.mock(MessageBuilder.class); ErrorBuilder sourceErrorBuilder = Mockito.mock(ErrorBuilder.class); SessionInitMessage sourceMessage = toSignedRequest(UUID.randomUUID(), ChannelType.SYNC_WITH_TIMEOUT, channelContextMock, sourceRequest, sourceResponseBuilder, sourceErrorBuilder); akkaService.process(sourceMessage); Mockito.verify(operationsService, Mockito.timeout(TIMEOUT).atLeastOnce()).syncProfile(Mockito.any(SyncContext.class), Mockito.any(ProfileClientSync.class)); SyncResponse targetSyncResponse = new SyncResponse(); targetSyncResponse.setRequestId(REQUEST_ID); targetSyncResponse.setStatus(SyncResponseResultType.SUCCESS); targetSyncResponse.setUserSyncResponse(new UserSyncResponse()); targetSyncResponse.getUserSyncResponse().setUserAttachNotification( new UserAttachNotification(USER_ID, Base64Util.encode(clientPublicKeyHash.array()))); AvroByteArrayConverter<SyncResponse> responseConverter = new AvroByteArrayConverter<>(SyncResponse.class); byte[] response = responseConverter.toByteArray(targetSyncResponse); LOG.trace("Expected response {}", Arrays.toString(response)); byte[] encodedData = targetCrypt.encodeData(response); Mockito.verify(responseBuilder, Mockito.timeout(TIMEOUT).atLeastOnce()).build(encodedData, true); } @Test public void testEndpointDetach() throws Exception { ChannelContext channelContextMock = Mockito.mock(ChannelContext.class); MessageEncoderDecoder targetCrypt = new MessageEncoderDecoder(targetPair.getPrivate(), targetPair.getPublic(), serverPair.getPublic()); EndpointProfileDto targetProfileMock = Mockito.mock(EndpointProfileDto.class); EventClassFamilyVersionStateDto ecfVdto = new EventClassFamilyVersionStateDto(); ecfVdto.setEcfId(ECF1_ID); ecfVdto.setVersion(ECF1_VERSION); SyncRequest targetRequest = new SyncRequest(); targetRequest.setRequestId(REQUEST_ID); targetRequest.setSyncRequestMetaData(buildSyncRequestMetaData(targetPublicKeyHash)); targetRequest.setEventSyncRequest(new EventSyncRequest()); ServerSync targetResponse = new ServerSync(); targetResponse.setRequestId(REQUEST_ID); targetResponse.setStatus(org.kaaproject.kaa.server.sync.SyncStatus.SUCCESS); targetResponse.setUserSync(new UserServerSync()); SyncContext targetResponseHolder = new SyncContext(targetResponse); targetResponseHolder.setEndpointProfile(targetProfileMock); whenSync(AvroEncDec.convert(targetRequest), targetResponseHolder); when(targetProfileMock.getEndpointUserId()).thenReturn(USER_ID); when(targetProfileMock.getEndpointKeyHash()).thenReturn(targetPublicKeyHash.array()); when(targetProfileMock.getEcfVersionStates()).thenReturn(Arrays.asList(ecfVdto)); when(cacheService.getEventClassFamilyIdByEventClassFqn(new EventClassFqnKey(TENANT_ID, FQN1))).thenReturn(ECF1_ID); RouteTableKey routeKey = new RouteTableKey(APP_TOKEN, new EventClassFamilyVersion(ECF1_ID, ECF1_VERSION)); when(cacheService.getRouteKeys(new EventClassFqnVersion(TENANT_ID, FQN1, ECF1_VERSION))) .thenReturn(Collections.singleton(routeKey)); Assert.assertNotNull(akkaService.getActorSystem()); MessageBuilder targetResponseBuilder = Mockito.mock(MessageBuilder.class); ErrorBuilder targetErrorBuilder = Mockito.mock(ErrorBuilder.class); SessionInitMessage targetMessage = toSignedRequest(UUID.randomUUID(), ChannelType.SYNC_WITH_TIMEOUT, channelContextMock, targetRequest, targetResponseBuilder, targetErrorBuilder, targetCrypt); akkaService.process(targetMessage); Mockito.verify(operationsService, Mockito.timeout(TIMEOUT).atLeastOnce()).syncProfile(Mockito.any(SyncContext.class), Mockito.any(ProfileClientSync.class)); Mockito.verify(eventService, Mockito.timeout(TIMEOUT).atLeastOnce()).sendUserRouteInfo(new UserRouteInfo(TENANT_ID, USER_ID)); EndpointProfileDto sourceProfileMock = Mockito.mock(EndpointProfileDto.class); SyncRequest sourceRequest = new SyncRequest(); sourceRequest.setRequestId(REQUEST_ID); sourceRequest.setSyncRequestMetaData(buildSyncRequestMetaData(clientPublicKeyHash)); sourceRequest.setEventSyncRequest(new EventSyncRequest()); UserSyncRequest userSyncRequest = new UserSyncRequest(); EndpointDetachRequest eaRequest = new EndpointDetachRequest(REQUEST_ID, Base64Util.encode(targetPublicKeyHash.array())); userSyncRequest.setEndpointDetachRequests(Collections.singletonList(eaRequest)); sourceRequest.setUserSyncRequest(userSyncRequest); ServerSync sourceResponse = new ServerSync(); sourceResponse.setRequestId(REQUEST_ID); sourceResponse.setStatus(org.kaaproject.kaa.server.sync.SyncStatus.SUCCESS); UserServerSync userSyncResponse = new UserServerSync(); userSyncResponse.setEndpointDetachResponses(Collections.singletonList(new org.kaaproject.kaa.server.sync.EndpointDetachResponse( REQUEST_ID, org.kaaproject.kaa.server.sync.SyncStatus.SUCCESS))); sourceResponse.setUserSync(userSyncResponse); SyncContext sourceResponseHolder = new SyncContext(sourceResponse); sourceResponseHolder.setEndpointProfile(sourceProfileMock); whenSync(AvroEncDec.convert(sourceRequest), sourceResponseHolder); when(sourceProfileMock.getEndpointUserId()).thenReturn(USER_ID); when(sourceProfileMock.getEndpointKeyHash()).thenReturn(clientPublicKeyHash.array()); when(sourceProfileMock.getEcfVersionStates()).thenReturn(Arrays.asList(ecfVdto)); MessageBuilder sourceResponseBuilder = Mockito.mock(MessageBuilder.class); ErrorBuilder sourceErrorBuilder = Mockito.mock(ErrorBuilder.class); SessionInitMessage sourceMessage = toSignedRequest(UUID.randomUUID(), ChannelType.SYNC_WITH_TIMEOUT, channelContextMock, sourceRequest, sourceResponseBuilder, sourceErrorBuilder); akkaService.process(sourceMessage); Mockito.verify(operationsService, Mockito.timeout(TIMEOUT).atLeastOnce()).syncProfile(Mockito.any(SyncContext.class), Mockito.any(ProfileClientSync.class)); SyncResponse targetSyncResponse = new SyncResponse(); targetSyncResponse.setRequestId(REQUEST_ID); targetSyncResponse.setStatus(SyncResponseResultType.SUCCESS); targetSyncResponse.setUserSyncResponse(new UserSyncResponse()); targetSyncResponse.getUserSyncResponse().setUserDetachNotification( new UserDetachNotification(Base64Util.encode(clientPublicKeyHash.array()))); AvroByteArrayConverter<SyncResponse> responseConverter = new AvroByteArrayConverter<>(SyncResponse.class); byte[] response = responseConverter.toByteArray(targetSyncResponse); byte[] encodedData = targetCrypt.encodeData(response); Mockito.verify(targetResponseBuilder, Mockito.timeout(TIMEOUT).atLeastOnce()).build(encodedData, true); } private SyncRequestMetaData buildSyncRequestMetaData() { return buildSyncRequestMetaData(clientPublicKeyHash); } private SyncRequestMetaData buildSyncRequestMetaData(ByteBuffer keyHash) { SyncRequestMetaData md = new SyncRequestMetaData(); md.setSdkToken(SDK_TOKEN); md.setEndpointPublicKeyHash(keyHash); md.setProfileHash(keyHash); md.setTimeout(2l * TIMEOUT); return md; } }
kallelzied/kaa
server/operations/src/test/java/org/kaaproject/kaa/server/operations/service/akka/DefaultAkkaServiceTest.java
Java
apache-2.0
79,687
![alt tag](img/assertj-db_icon.png) AssertJ-DB - Assertions for database ========== AssertJ-DB provides some assertions to test values in a database. The goal is to be an alternative to DBUnit for people who don't like to write XML. You can find all the informations you need in the [documentation](http://joel-costigliola.github.io/assertj/assertj-db.html).
otoniel-isidoro/assertj-db
README.md
Markdown
apache-2.0
362
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_45) on Thu Nov 13 21:22:01 UTC 2014 --> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <TITLE> Uses of Class org.apache.hadoop.net.ConnectTimeoutException (Apache Hadoop Main 2.6.0 API) </TITLE> <META NAME="date" CONTENT="2014-11-13"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.hadoop.net.ConnectTimeoutException (Apache Hadoop Main 2.6.0 API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/hadoop/net/ConnectTimeoutException.html" title="class in org.apache.hadoop.net"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?org/apache/hadoop/net//class-useConnectTimeoutException.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ConnectTimeoutException.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>org.apache.hadoop.net.ConnectTimeoutException</B></H2> </CENTER> No usage of org.apache.hadoop.net.ConnectTimeoutException <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/hadoop/net/ConnectTimeoutException.html" title="class in org.apache.hadoop.net"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?org/apache/hadoop/net//class-useConnectTimeoutException.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ConnectTimeoutException.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright &#169; 2014 <a href="http://www.apache.org">Apache Software Foundation</a>. All Rights Reserved. </BODY> </HTML>
SAT-Hadoop/hadoop-2.6.0
share/doc/hadoop/api/org/apache/hadoop/net/class-use/ConnectTimeoutException.html
HTML
apache-2.0
6,210
package root import ( "fmt" "github.com/kubernetes-incubator/kube-aws/awsconn" "github.com/kubernetes-incubator/kube-aws/cfnstack" "github.com/kubernetes-incubator/kube-aws/core/root/config" ) type DestroyOptions struct { AwsDebug bool Force bool } type ClusterDestroyer interface { Destroy() error } type clusterDestroyerImpl struct { underlying *cfnstack.Destroyer } func ClusterDestroyerFromFile(configPath string, opts DestroyOptions) (ClusterDestroyer, error) { cfg, err := config.ConfigFromFile(configPath) if err != nil { return nil, err } session, err := awsconn.NewSessionFromRegion(cfg.Region, opts.AwsDebug) if err != nil { return nil, fmt.Errorf("failed to establish aws session: %v", err) } cfnDestroyer := cfnstack.NewDestroyer(cfg.RootStackName(), session, cfg.CloudFormation.RoleARN) return clusterDestroyerImpl{ underlying: cfnDestroyer, }, nil } func (d clusterDestroyerImpl) Destroy() error { return d.underlying.Destroy() }
c-knowles/kube-aws
core/root/destroyer.go
GO
apache-2.0
980
<?php require_once __DIR__ . '/../src/prepend.inc.php'; use Scalr\Model\Entity\CloudLocation; //Cleans out cloud locations cache CloudLocation::warmUp();
kikov79/scalr
app/tools/warmup-cache.php
PHP
apache-2.0
156
// // sos.cc // sos // // Created by Pavan Kumar Sunkara on 20/01/15. // Copyright (c) 2015 Apiary Inc. All rights reserved. // #include "sos.h" sos::Base::Base(Base::Type type_) : type(type_) { m_object.reset(::new KeyValues); m_array.reset(::new Bases); } sos::Base::Base(const sos::Base& rhs) { this->type = rhs.type; this->str = rhs.str; this->number = rhs.number; this->boolean = rhs.boolean; this->keys = rhs.keys; this->m_object.reset(::new KeyValues(*rhs.m_object.get())); this->m_array.reset(::new Bases(*rhs.m_array.get())); } sos::Base& sos::Base::operator=(const sos::Base &rhs) { this->type = rhs.type; this->str = rhs.str; this->number = rhs.number; this->boolean = rhs.boolean; this->keys = rhs.keys; this->m_object.reset(::new KeyValues(*rhs.m_object.get())); this->m_array.reset(::new Bases(*rhs.m_array.get())); return *this; } sos::KeyValues& sos::Base::object() { if (!m_object.get()) throw "no object key-values set"; return *m_object; } const sos::KeyValues& sos::Base::object() const { if (!m_object.get()) throw "no object key-values set"; return *m_object; } sos::Bases& sos::Base::array() { if (!m_array.get()) throw "no array values set"; return *m_array; } const sos::Bases& sos::Base::array() const { if (!m_array.get()) throw "no array values set"; return *m_array; } sos::Null::Null() : Base(NullType) {} sos::String::String(std::string str_) { type = StringType; str = str_; } sos::Number::Number(double number_) { type = NumberType; number = number_; } sos::Boolean::Boolean(bool boolean_) { type = BooleanType; boolean = boolean_; } sos::Array::Array() : Base(ArrayType) {} void sos::Array::push(const sos::Base& value) { array().push_back(value); } void sos::Array::set(const size_t index, const sos::Base& value) { if (array().size() <= index) throw "not enough array values set"; array().at(index) = value; } bool sos::Array::empty() { return array().empty(); } sos::Object::Object() : Base(ObjectType) {} void sos::Object::set(const std::string& key, const sos::Base& value) { if (std::find(keys.begin(), keys.end(), key) != keys.end()) throw "key already present in the object"; keys.push_back(key); object().operator[](key) = value; } bool sos::Object::empty() { return keys.empty(); } sos::Serialize::Serialize() {} void sos::Serialize::process(const Base& root, std::ostream& os, size_t level) { sos::Base::Type type = root.type; switch (type) { case Base::NullType: null(os); break; case Base::StringType: string(root.str, os); break; case Base::NumberType: number(root.number, os); break; case Base::BooleanType: boolean(root.boolean, os); break; case Base::ArrayType: array(root, os, level); break; case Base::ObjectType: object(root, os, level); break; default: break; } } std::string sos::escapeNewlines(const std::string &input) { size_t pos = 0; std::string target(input); while ((pos = target.find("\n", pos)) != std::string::npos) { target.replace(pos, 1, "\\n"); pos += 2; } return target; } std::string sos::escapeDoubleQuotes(const std::string &input) { size_t pos = 0; std::string target(input); while ((pos = target.find("\"", pos)) != std::string::npos) { target.replace(pos, 1, "\\\""); pos += 2; } return target; }
SparkPost/on-prem-api-documentation-v4.2
node_modules/protagonist/drafter/ext/sos/src/sos.cc
C++
apache-2.0
3,734
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #pragma once #include <aws/directconnect/DirectConnect_EXPORTS.h> #include <aws/directconnect/DirectConnectRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <utility> namespace Aws { namespace DirectConnect { namespace Model { /** * <p>Container for the parameters to the DeleteBGPPeer operation.</p><p><h3>See * Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/DeleteBGPPeerRequest">AWS * API Reference</a></p> */ class AWS_DIRECTCONNECT_API DeleteBGPPeerRequest : public DirectConnectRequest { public: DeleteBGPPeerRequest(); Aws::String SerializePayload() const override; Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override; /** * <p>The ID of the virtual interface from which the BGP peer will be deleted.</p> * <p>Example: dxvif-456abc78</p> <p>Default: None</p> */ inline const Aws::String& GetVirtualInterfaceId() const{ return m_virtualInterfaceId; } /** * <p>The ID of the virtual interface from which the BGP peer will be deleted.</p> * <p>Example: dxvif-456abc78</p> <p>Default: None</p> */ inline void SetVirtualInterfaceId(const Aws::String& value) { m_virtualInterfaceIdHasBeenSet = true; m_virtualInterfaceId = value; } /** * <p>The ID of the virtual interface from which the BGP peer will be deleted.</p> * <p>Example: dxvif-456abc78</p> <p>Default: None</p> */ inline void SetVirtualInterfaceId(Aws::String&& value) { m_virtualInterfaceIdHasBeenSet = true; m_virtualInterfaceId = std::move(value); } /** * <p>The ID of the virtual interface from which the BGP peer will be deleted.</p> * <p>Example: dxvif-456abc78</p> <p>Default: None</p> */ inline void SetVirtualInterfaceId(const char* value) { m_virtualInterfaceIdHasBeenSet = true; m_virtualInterfaceId.assign(value); } /** * <p>The ID of the virtual interface from which the BGP peer will be deleted.</p> * <p>Example: dxvif-456abc78</p> <p>Default: None</p> */ inline DeleteBGPPeerRequest& WithVirtualInterfaceId(const Aws::String& value) { SetVirtualInterfaceId(value); return *this;} /** * <p>The ID of the virtual interface from which the BGP peer will be deleted.</p> * <p>Example: dxvif-456abc78</p> <p>Default: None</p> */ inline DeleteBGPPeerRequest& WithVirtualInterfaceId(Aws::String&& value) { SetVirtualInterfaceId(std::move(value)); return *this;} /** * <p>The ID of the virtual interface from which the BGP peer will be deleted.</p> * <p>Example: dxvif-456abc78</p> <p>Default: None</p> */ inline DeleteBGPPeerRequest& WithVirtualInterfaceId(const char* value) { SetVirtualInterfaceId(value); return *this;} inline int GetAsn() const{ return m_asn; } inline void SetAsn(int value) { m_asnHasBeenSet = true; m_asn = value; } inline DeleteBGPPeerRequest& WithAsn(int value) { SetAsn(value); return *this;} inline const Aws::String& GetCustomerAddress() const{ return m_customerAddress; } inline void SetCustomerAddress(const Aws::String& value) { m_customerAddressHasBeenSet = true; m_customerAddress = value; } inline void SetCustomerAddress(Aws::String&& value) { m_customerAddressHasBeenSet = true; m_customerAddress = std::move(value); } inline void SetCustomerAddress(const char* value) { m_customerAddressHasBeenSet = true; m_customerAddress.assign(value); } inline DeleteBGPPeerRequest& WithCustomerAddress(const Aws::String& value) { SetCustomerAddress(value); return *this;} inline DeleteBGPPeerRequest& WithCustomerAddress(Aws::String&& value) { SetCustomerAddress(std::move(value)); return *this;} inline DeleteBGPPeerRequest& WithCustomerAddress(const char* value) { SetCustomerAddress(value); return *this;} private: Aws::String m_virtualInterfaceId; bool m_virtualInterfaceIdHasBeenSet; int m_asn; bool m_asnHasBeenSet; Aws::String m_customerAddress; bool m_customerAddressHasBeenSet; }; } // namespace Model } // namespace DirectConnect } // namespace Aws
chiaming0914/awe-cpp-sdk
aws-cpp-sdk-directconnect/include/aws/directconnect/model/DeleteBGPPeerRequest.h
C
apache-2.0
4,750
<!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_03) on Tue Nov 06 09:34:23 CST 2012 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>Uses of Interface org.eclipse.jetty.http.Parser (Jetty :: Aggregate :: All core Jetty 8.1.8.v20121106 API)</title> <meta name="date" content="2012-11-06"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Interface org.eclipse.jetty.http.Parser (Jetty :: Aggregate :: All core Jetty 8.1.8.v20121106 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../org/eclipse/jetty/http/Parser.html" title="interface in org.eclipse.jetty.http">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/eclipse/jetty/http//class-useParser.html" target="_top">Frames</a></li> <li><a href="Parser.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Interface org.eclipse.jetty.http.Parser" class="title">Uses of Interface<br>org.eclipse.jetty.http.Parser</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../org/eclipse/jetty/http/Parser.html" title="interface in org.eclipse.jetty.http">Parser</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#org.eclipse.jetty.ajp">org.eclipse.jetty.ajp</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#org.eclipse.jetty.http">org.eclipse.jetty.http</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><a href="#org.eclipse.jetty.nested">org.eclipse.jetty.nested</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#org.eclipse.jetty.server">org.eclipse.jetty.server</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.eclipse.jetty.ajp"> <!-- --> </a> <h3>Uses of <a href="../../../../../org/eclipse/jetty/http/Parser.html" title="interface in org.eclipse.jetty.http">Parser</a> in <a href="../../../../../org/eclipse/jetty/ajp/package-summary.html">org.eclipse.jetty.ajp</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../../org/eclipse/jetty/ajp/package-summary.html">org.eclipse.jetty.ajp</a> that implement <a href="../../../../../org/eclipse/jetty/http/Parser.html" title="interface in org.eclipse.jetty.http">Parser</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../org/eclipse/jetty/ajp/Ajp13Parser.html" title="class in org.eclipse.jetty.ajp">Ajp13Parser</a></strong></code>&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.eclipse.jetty.http"> <!-- --> </a> <h3>Uses of <a href="../../../../../org/eclipse/jetty/http/Parser.html" title="interface in org.eclipse.jetty.http">Parser</a> in <a href="../../../../../org/eclipse/jetty/http/package-summary.html">org.eclipse.jetty.http</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../../org/eclipse/jetty/http/package-summary.html">org.eclipse.jetty.http</a> that implement <a href="../../../../../org/eclipse/jetty/http/Parser.html" title="interface in org.eclipse.jetty.http">Parser</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../org/eclipse/jetty/http/HttpParser.html" title="class in org.eclipse.jetty.http">HttpParser</a></strong></code>&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.eclipse.jetty.nested"> <!-- --> </a> <h3>Uses of <a href="../../../../../org/eclipse/jetty/http/Parser.html" title="interface in org.eclipse.jetty.http">Parser</a> in <a href="../../../../../org/eclipse/jetty/nested/package-summary.html">org.eclipse.jetty.nested</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../../org/eclipse/jetty/nested/package-summary.html">org.eclipse.jetty.nested</a> that implement <a href="../../../../../org/eclipse/jetty/http/Parser.html" title="interface in org.eclipse.jetty.http">Parser</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../org/eclipse/jetty/nested/NestedParser.html" title="class in org.eclipse.jetty.nested">NestedParser</a></strong></code>&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.eclipse.jetty.server"> <!-- --> </a> <h3>Uses of <a href="../../../../../org/eclipse/jetty/http/Parser.html" title="interface in org.eclipse.jetty.http">Parser</a> in <a href="../../../../../org/eclipse/jetty/server/package-summary.html">org.eclipse.jetty.server</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing fields, and an explanation"> <caption><span>Fields in <a href="../../../../../org/eclipse/jetty/server/package-summary.html">org.eclipse.jetty.server</a> declared as <a href="../../../../../org/eclipse/jetty/http/Parser.html" title="interface in org.eclipse.jetty.http">Parser</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>protected <a href="../../../../../org/eclipse/jetty/http/Parser.html" title="interface in org.eclipse.jetty.http">Parser</a></code></td> <td class="colLast"><span class="strong">AbstractHttpConnection.</span><code><strong><a href="../../../../../org/eclipse/jetty/server/AbstractHttpConnection.html#_parser">_parser</a></strong></code>&nbsp;</td> </tr> </tbody> </table> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../org/eclipse/jetty/server/package-summary.html">org.eclipse.jetty.server</a> that return <a href="../../../../../org/eclipse/jetty/http/Parser.html" title="interface in org.eclipse.jetty.http">Parser</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../org/eclipse/jetty/http/Parser.html" title="interface in org.eclipse.jetty.http">Parser</a></code></td> <td class="colLast"><span class="strong">AbstractHttpConnection.</span><code><strong><a href="../../../../../org/eclipse/jetty/server/AbstractHttpConnection.html#getParser()">getParser</a></strong>()</code>&nbsp;</td> </tr> </tbody> </table> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing constructors, and an explanation"> <caption><span>Constructors in <a href="../../../../../org/eclipse/jetty/server/package-summary.html">org.eclipse.jetty.server</a> with parameters of type <a href="../../../../../org/eclipse/jetty/http/Parser.html" title="interface in org.eclipse.jetty.http">Parser</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colLast"><code><strong><a href="../../../../../org/eclipse/jetty/server/AbstractHttpConnection.html#AbstractHttpConnection(org.eclipse.jetty.server.Connector, org.eclipse.jetty.io.EndPoint, org.eclipse.jetty.server.Server, org.eclipse.jetty.http.Parser, org.eclipse.jetty.http.Generator, org.eclipse.jetty.server.Request)">AbstractHttpConnection</a></strong>(<a href="../../../../../org/eclipse/jetty/server/Connector.html" title="interface in org.eclipse.jetty.server">Connector</a>&nbsp;connector, <a href="../../../../../org/eclipse/jetty/io/EndPoint.html" title="interface in org.eclipse.jetty.io">EndPoint</a>&nbsp;endpoint, <a href="../../../../../org/eclipse/jetty/server/Server.html" title="class in org.eclipse.jetty.server">Server</a>&nbsp;server, <a href="../../../../../org/eclipse/jetty/http/Parser.html" title="interface in org.eclipse.jetty.http">Parser</a>&nbsp;parser, <a href="../../../../../org/eclipse/jetty/http/Generator.html" title="interface in org.eclipse.jetty.http">Generator</a>&nbsp;generator, <a href="../../../../../org/eclipse/jetty/server/Request.html" title="class in org.eclipse.jetty.server">Request</a>&nbsp;request)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colLast"><code><strong><a href="../../../../../org/eclipse/jetty/server/BlockingHttpConnection.html#BlockingHttpConnection(org.eclipse.jetty.server.Connector, org.eclipse.jetty.io.EndPoint, org.eclipse.jetty.server.Server, org.eclipse.jetty.http.Parser, org.eclipse.jetty.http.Generator, org.eclipse.jetty.server.Request)">BlockingHttpConnection</a></strong>(<a href="../../../../../org/eclipse/jetty/server/Connector.html" title="interface in org.eclipse.jetty.server">Connector</a>&nbsp;connector, <a href="../../../../../org/eclipse/jetty/io/EndPoint.html" title="interface in org.eclipse.jetty.io">EndPoint</a>&nbsp;endpoint, <a href="../../../../../org/eclipse/jetty/server/Server.html" title="class in org.eclipse.jetty.server">Server</a>&nbsp;server, <a href="../../../../../org/eclipse/jetty/http/Parser.html" title="interface in org.eclipse.jetty.http">Parser</a>&nbsp;parser, <a href="../../../../../org/eclipse/jetty/http/Generator.html" title="interface in org.eclipse.jetty.http">Generator</a>&nbsp;generator, <a href="../../../../../org/eclipse/jetty/server/Request.html" title="class in org.eclipse.jetty.server">Request</a>&nbsp;request)</code>&nbsp;</td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../org/eclipse/jetty/http/Parser.html" title="interface in org.eclipse.jetty.http">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/eclipse/jetty/http//class-useParser.html" target="_top">Frames</a></li> <li><a href="Parser.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; 1995-2012 <a href="http://www.mortbay.com">Mort Bay Consulting</a>. All Rights Reserved.</small></p> </body> </html>
yayaratta/TP6_MVC
javadoc/org/eclipse/jetty/http/class-use/Parser.html
HTML
apache-2.0
14,338
/********************************************************************** // @@@ START COPYRIGHT @@@ // // 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. // // @@@ END COPYRIGHT @@@ **********************************************************************/ /* -*-C++-*- ***************************************************************************** * * File: ProcessEnv.C * Description: The implementation of the class ProcessEnv, used to process * the environment variables (defines, ...etc ) information. * passed by executor. * * * Created: 9/05/96 * Language: C++ * * * * ***************************************************************************** */ #include "Platform.h" // NT_PORT SK 02/08/97 #include "Collections.h" #include "ProcessEnv.h" #include "CmpCommon.h" #include <unistd.h> #include <string.h> #include <stdlib.h> #include <iostream> #include <fstream> extern char** environ; #define ENVIRON environ #define PUTENV putenv ProcessEnv::ProcessEnv(NAMemory *heap) : heap_(heap), envs_(heap, 64) { } ProcessEnv::~ProcessEnv() { cleanup(); } void ProcessEnv::cleanup() { for ( CollIndex i=0; i < envs_.entries(); i++ ) NADELETEBASIC(envs_[i], heap_); envs_.clear(); } // To make sure the environment variables are the same as in executor // (add new ones, delete the ones been deleted from executor.) // The best way will be to // 1. delete all environment variables first // 2. add all the environment variables from executor. // But PUTENV(system call) in NT creates a lot of memory leak, since this // operation is needed for every request, the leak accumulates. // // An alternative was explored that instead of using PUTENV, ENVIRON is // directly manipulated to save the memory and speed up execution, but // if later in the user's code, PUTENV is called, this system call will // manipulate the storage of ENVIRON which caused problems. // // To make sure the environment is the same as in executor and the code // linked into arkcmp is not limited to unable to call PUTENV, the following // is done : // . envs_ private member in ProcessEnv contains the environment variables // being passed over from executor last time. // . For newenvs coming in this time, it is compared against envs_ for // appropriate operations. // // For every entry in newenvs, if // . it is not the same as in envs_, or // . can't find it in envs_ // do a PUTENV and change the envs_ entries. // // For every entry in envs_, if it can't be found in newenvs // do a PUTENV to remove this entry of environment variable. // and delete this entry from envs_ array. // // This way, // . PUTENV is called only when there is any changes in the environment // variables, so the leak would not be too big. Of course, there are still // leaks, but since this is the only system call we can use, we really // have no other choice. // . If there is any components calling PUTENV, it will still be compatible // with the code. Note, that is why newenvs is compared against envs_ instead // of ENVIRON, because other components might set the environment variables // which makes the ENVIRON different, this info was not from executor to begin // with and can't be removed if not found in newenvs. void ProcessEnv::setEnv(char** newenvs, Lng32 nEnvs) { if (!newenvs) return; addOrChangeEnv(newenvs, nEnvs); removeEnv(newenvs, nEnvs); #ifdef _DEBUG dumpEnvs(); // only if debugging #endif } Int32 ProcessEnv::unsetEnv(char* env) { if (!env) return 0; Int32 i=0; while(strcmp(ENVIRON[i], env) != 0) i++; while(ENVIRON[i]) ENVIRON[i] = ENVIRON[++i]; return 0; } #ifdef NA_CMPDLL void ProcessEnv::resetEnv(const char* envName) { if (!envName) return; Int32 i; size_t nameLen=strlen(envName); CollHeap *stmtHeap = CmpCommon::statementHeap(); NAList<Int32> deleteArray(stmtHeap, 16); // 16 should be more than enough // find the env in existing env array for (i=0; i < envs_.getSize(); i++) { if (envs_.used(i)) { char* pTemp = strchr(envs_[i], '='); if (pTemp) // found '=' { Int32 envLen = (Int32)(pTemp - envs_[i]); if (envLen == nameLen && strncmp(envName, envs_[i], nameLen) == 0 ) { // found matching env var name *(pTemp) = '\0'; PUTENV(envs_[i]); NADELETEBASIC(envs_[i], heap_); deleteArray.insert(i); } } } } // remove from the env array for (Int32 j = 0; j < deleteArray.entries(); j++) { envs_.remove(deleteArray[j]); } } #endif // NA_CMPDLL Int32 ProcessEnv::chdir(char* dir) { if (!dir) return 0; return ::chdir(dir); } #ifndef NDEBUG void ProcessEnv::dumpEnvs() { // To test the PUTENV still works const char* aString = "DUMPENV=ddd"; PUTENV((char *)aString); ofstream outStream("DUMPENVS"); Int32 i=0; outStream << "ProcessEnv::dumpEnvs() " << endl << flush; while (ENVIRON[i]) { char tempstr[2048]; strncpy( tempstr, ENVIRON[i], sizeof(tempstr)); char* p = strchr(tempstr, '='); if ( p ) *p = 0; char *s; if (s = getenv(tempstr)) outStream << "environ[" << i << "] ---- " << tempstr << " ---> " << s << endl; i++; } } #endif // NDEBUG // For every entry in newenvs search envs_, if // . not found, add a entry in envs_, do PUTENV // . found but not the same, change the entry in envs_, do PUTENV void ProcessEnv::addOrChangeEnv(char **newenvs, Lng32 nEnvs) { Lng32 i,j; for (i=0; i < nEnvs; i++) { char* pTemp = strchr(newenvs[i], '='); if (pTemp) { NABoolean sameValue = FALSE; Int32 envNameLen = pTemp - (newenvs[i]) + 1; // including '=' char* envName = new char[envNameLen+1]; strncpy(envName, newenvs[i], envNameLen); envName[envNameLen] = '\0'; NABoolean envChanged = FALSE; CollIndex entriesChecked = 0; for (j=0; entriesChecked < envs_.entries(); j++) { if ( envs_.used(j) ) { if (strcmp(newenvs[i], envs_[j]) == 0) { sameValue = TRUE; break; } else if (strncmp(envName, envs_[j], envNameLen) == 0) { envChanged = TRUE; break; } entriesChecked++; } } if (!sameValue) { CollIndex index = j; // Put to the same location if value changed if ( envChanged ) { NADELETEBASIC(envs_[j], heap_); envs_.remove(j); } else index = envs_.unusedIndex(); // Insert a new env string UInt32 len = strlen(newenvs[i]); char *copyEnv = new (heap_) char[len + 1]; strcpy(copyEnv, newenvs[i]); copyEnv[len] = 0; PUTENV(copyEnv); envs_.insertAt(index, copyEnv); } delete[] envName; } } } // For every entry in envs_, if it can't be found in newenvs // do a PUTENV to remove this entry of environment variable. // and delete this entry from envs_ array. void ProcessEnv::removeEnv(char **newenvs, Lng32 nEnvs) { Lng32 i,j; CollHeap *stmtHeap = CmpCommon::statementHeap(); NAList<Lng32> deleteArray(stmtHeap, 16); #pragma warning (disable : 4018) //warning elimination for (j=0; j < envs_.getSize(); j++) #pragma warning (default : 4018) //warning elimination { if (envs_.used(j)) { for (i=0; i < nEnvs; i++) if (strcmp(newenvs[i], envs_[j]) ==0 ) break; if ( i >= nEnvs ) { // can't find it in newenvs, envs_[j] must have been deleted char* pTemp = strchr(envs_[j], '='); if (pTemp) { *(pTemp+1) = '\0'; PUTENV(envs_[j]); NADELETEBASIC(envs_[j], heap_); deleteArray.insert(j); } } } } #pragma warning (disable : 4018) //warning elimination for (j=0; j < deleteArray.entries(); j++) { #pragma warning (default : 4018) //warning elimination envs_.remove(deleteArray[j]); } }
rlugojr/incubator-trafodion
core/sql/arkcmp/ProcessEnv.cpp
C++
apache-2.0
8,874
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package test.soap; import junit.framework.TestCase; import org.apache.axis.SimpleChain; import org.apache.axis.client.Call; import org.apache.axis.client.Service; import org.apache.axis.configuration.SimpleProvider; import org.apache.axis.handlers.soap.SOAPService; import org.apache.axis.message.SOAPEnvelope; import org.apache.axis.message.SOAPHeaderElement; import org.apache.axis.providers.java.RPCProvider; import org.apache.axis.server.AxisServer; import org.apache.axis.transport.local.LocalTransport; import java.util.Vector; /** * Confirm OnFault() header processing + additions work right. * * @author Glen Daniels (gdaniels@apache.org) */ public class TestOnFaultHeaders extends TestCase { public static String TRIGGER_NS = "http://trigger-fault"; public static String TRIGGER_NAME = "faultPlease"; public static String RESP_NAME = "okHeresYourFault"; private SimpleProvider provider = new SimpleProvider(); private AxisServer engine = new AxisServer(provider); private LocalTransport localTransport = new LocalTransport(engine); static final String localURL = "local:///testService"; public void setUp() throws Exception { engine.init(); localTransport.setUrl(localURL); SimpleChain chain = new SimpleChain(); chain.addHandler(new TestFaultHandler()); chain.addHandler(new TestHandler()); SOAPService service = new SOAPService(chain, new RPCProvider(), null); service.setOption("className", TestService.class.getName()); service.setOption("allowedMethods", "*"); provider.deployService("testService", service); } /** * Add a header which will trigger a fault in the TestHandler, and * therefore trigger the onFault() in the TestFaultHandler. That should * put a header in the outgoing message, which we check for when we get * the fault. * * @throws Exception */ public void testOnFaultHeaders() throws Exception { Call call = new Call(new Service()); call.setTransport(localTransport); SOAPHeaderElement header = new SOAPHeaderElement(TRIGGER_NS, TRIGGER_NAME, "do it"); call.addHeader(header); try { call.invoke("countChars", new Object [] { "foo" }); } catch (Exception e) { SOAPEnvelope env = call.getResponseMessage().getSOAPEnvelope(); Vector headers = env.getHeaders(); assertEquals("Wrong # of headers in fault!", 1, headers.size()); SOAPHeaderElement respHeader = (SOAPHeaderElement)headers.get(0); assertEquals("Wrong namespace for header", TRIGGER_NS, respHeader.getNamespaceURI()); assertEquals("Wrong localName for response header", RESP_NAME, respHeader.getName()); return; } fail("We should have gotten a fault!"); } }
apache/axis1-java
axis-rt-core/src/test/java/test/soap/TestOnFaultHeaders.java
Java
apache-2.0
3,826
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.10"/> <title>Labyrinttipeli: Class Members</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">Labyrinttipeli </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.10 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li class="current"><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <div id="navrow3" class="tabs2"> <ul class="tablist"> <li class="current"><a href="functions.html"><span>All</span></a></li> <li><a href="functions_func.html"><span>Functions</span></a></li> <li><a href="functions_vars.html"><span>Variables</span></a></li> <li><a href="functions_enum.html"><span>Enumerations</span></a></li> <li><a href="functions_eval.html"><span>Enumerator</span></a></li> </ul> </div> <div id="navrow4" class="tabs3"> <ul class="tablist"> <li><a href="functions.html#index_a"><span>a</span></a></li> <li><a href="functions_b.html#index_b"><span>b</span></a></li> <li><a href="functions_d.html#index_d"><span>d</span></a></li> <li><a href="functions_e.html#index_e"><span>e</span></a></li> <li><a href="functions_f.html#index_f"><span>f</span></a></li> <li><a href="functions_h.html#index_h"><span>h</span></a></li> <li><a href="functions_i.html#index_i"><span>i</span></a></li> <li><a href="functions_j.html#index_j"><span>j</span></a></li> <li><a href="functions_k.html#index_k"><span>k</span></a></li> <li><a href="functions_l.html#index_l"><span>l</span></a></li> <li><a href="functions_m.html#index_m"><span>m</span></a></li> <li><a href="functions_n.html#index_n"><span>n</span></a></li> <li><a href="functions_o.html#index_o"><span>o</span></a></li> <li><a href="functions_p.html#index_p"><span>p</span></a></li> <li><a href="functions_r.html#index_r"><span>r</span></a></li> <li class="current"><a href="functions_s.html#index_s"><span>s</span></a></li> <li><a href="functions_t.html#index_t"><span>t</span></a></li> <li><a href="functions_u.html#index_u"><span>u</span></a></li> <li><a href="functions_v.html#index_v"><span>v</span></a></li> <li><a href="functions_y.html#index_y"><span>y</span></a></li> <li><a href="functions_~.html#index_~"><span>~</span></a></li> </ul> </div> </div><!-- top --> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="contents"> <div class="textblock">Here is a list of all documented class members with links to the class documentation for each member:</div> <h3><a class="anchor" id="index_s"></a>- s -</h3><ul> <li>suorakaide() : <a class="el" href="class_bittikartta.html#a3c01a7b0f71cc48899b1a300c3f5dfb9">Bittikartta</a> </li> </ul> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.10 </small></address> </body> </html>
SanteriHetekivi/Labyrinttipeli
html/functions_s.html
HTML
apache-2.0
6,061
// Copyright (C) 2014 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gitiles; import static com.google.common.collect.Iterables.getOnlyElement; import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import com.google.common.collect.ImmutableList; import com.google.common.io.BaseEncoding; import org.eclipse.jgit.diff.DiffEntry; import org.eclipse.jgit.diff.DiffEntry.ChangeType; import org.eclipse.jgit.diff.DiffEntry.Side; import org.eclipse.jgit.diff.Edit; import org.eclipse.jgit.diff.Edit.Type; import org.eclipse.jgit.diff.RawText; import org.eclipse.jgit.internal.storage.dfs.DfsRepository; import org.eclipse.jgit.internal.storage.dfs.DfsRepositoryDescription; import org.eclipse.jgit.internal.storage.dfs.InMemoryRepository; import org.eclipse.jgit.junit.TestRepository; import org.eclipse.jgit.patch.FileHeader; import org.eclipse.jgit.patch.Patch; import org.eclipse.jgit.revwalk.RevCommit; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class DiffServletTest { private TestRepository<DfsRepository> repo; private GitilesServlet servlet; @Before public void setUp() throws Exception { DfsRepository r = new InMemoryRepository(new DfsRepositoryDescription("test")); repo = new TestRepository<>(r); servlet = TestGitilesServlet.create(repo); } @Test public void diffFileOneParentHtml() throws Exception { String contents1 = "foo\n"; String contents2 = "foo\ncontents\n"; RevCommit c1 = repo.update("master", repo.commit().add("foo", contents1)); RevCommit c2 = repo.update("master", repo.commit().parent(c1).add("foo", contents2)); FakeHttpServletRequest req = FakeHttpServletRequest.newRequest(); req.setPathInfo("/test/+diff/" + c2.name() + "^!/foo"); FakeHttpServletResponse res = new FakeHttpServletResponse(); servlet.service(req, res); String diffHeader = String.format( "diff --git <a href=\"/b/test/+/%s/foo\">a/foo</a> <a href=\"/b/test/+/%s/foo\">b/foo</a>", c1.name(), c2.name()); String actual = res.getActualBodyString(); assertTrue(String.format("Expected diff body to contain [%s]:\n%s", diffHeader, actual), actual.contains(diffHeader)); } @Test public void diffFileNoParentsText() throws Exception { String contents = "foo\ncontents\n"; RevCommit c = repo.update("master", repo.commit().add("foo", contents)); FakeHttpServletRequest req = FakeHttpServletRequest.newRequest(); req.setPathInfo("/test/+diff/" + c.name() + "^!/foo"); req.setQueryString("format=TEXT"); FakeHttpServletResponse res = new FakeHttpServletResponse(); servlet.service(req, res); Patch p = parsePatch(res.getActualBody()); FileHeader f = getOnlyElement(p.getFiles()); assertEquals(ChangeType.ADD, f.getChangeType()); assertEquals(DiffEntry.DEV_NULL, f.getPath(Side.OLD)); assertEquals("foo", f.getPath(Side.NEW)); RawText rt = new RawText(contents.getBytes(UTF_8)); Edit e = getOnlyElement(getOnlyElement(f.getHunks()).toEditList()); assertEquals(Type.INSERT, e.getType()); assertEquals(contents, rt.getString(e.getBeginB(), e.getEndB(), false)); } @Test public void diffFileOneParentText() throws Exception { String contents1 = "foo\n"; String contents2 = "foo\ncontents\n"; RevCommit c1 = repo.update("master", repo.commit().add("foo", contents1)); RevCommit c2 = repo.update("master", repo.commit().parent(c1).add("foo", contents2)); FakeHttpServletRequest req = FakeHttpServletRequest.newRequest(); req.setPathInfo("/test/+diff/" + c2.name() + "^!/foo"); req.setQueryString("format=TEXT"); FakeHttpServletResponse res = new FakeHttpServletResponse(); servlet.service(req, res); Patch p = parsePatch(res.getActualBody()); FileHeader f = getOnlyElement(p.getFiles()); assertEquals(ChangeType.MODIFY, f.getChangeType()); assertEquals("foo", f.getPath(Side.OLD)); assertEquals("foo", f.getPath(Side.NEW)); RawText rt2 = new RawText(contents2.getBytes(UTF_8)); Edit e = getOnlyElement(getOnlyElement(f.getHunks()).toEditList()); assertEquals(Type.INSERT, e.getType()); assertEquals("contents\n", rt2.getString(e.getBeginB(), e.getEndB(), false)); } @Test public void diffDirectoryText() throws Exception { String contents = "contents\n"; RevCommit c = repo.update("master", repo.commit() .add("dir/foo", contents) .add("dir/bar", contents) .add("baz", contents)); FakeHttpServletRequest req = FakeHttpServletRequest.newRequest(); req.setPathInfo("/test/+diff/" + c.name() + "^!/dir"); req.setQueryString("format=TEXT"); FakeHttpServletResponse res = new FakeHttpServletResponse(); servlet.service(req, res); Patch p = parsePatch(res.getActualBody()); assertEquals(2, p.getFiles().size()); assertEquals("dir/bar", p.getFiles().get(0).getPath(Side.NEW)); assertEquals("dir/foo", p.getFiles().get(1).getPath(Side.NEW)); } private static Patch parsePatch(byte[] enc) { byte[] buf = BaseEncoding.base64().decode(new String(enc, UTF_8)); Patch p = new Patch(); p.parse(buf, 0, buf.length); assertEquals(ImmutableList.of(), p.getErrors()); return p; } }
estebank/gitiles
gitiles-servlet/src/test/java/com/google/gitiles/DiffServletTest.java
Java
apache-2.0
5,952
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/macie2/model/GetAdministratorAccountResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::Macie2::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; GetAdministratorAccountResult::GetAdministratorAccountResult() { } GetAdministratorAccountResult::GetAdministratorAccountResult(const Aws::AmazonWebServiceResult<JsonValue>& result) { *this = result; } GetAdministratorAccountResult& GetAdministratorAccountResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result) { JsonView jsonValue = result.GetPayload().View(); if(jsonValue.ValueExists("administrator")) { m_administrator = jsonValue.GetObject("administrator"); } return *this; }
awslabs/aws-sdk-cpp
aws-cpp-sdk-macie2/source/model/GetAdministratorAccountResult.cpp
C++
apache-2.0
1,023
/* * Copyright 2009-2016 DigitalGlobe, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and limitations under the License. * */ package org.mrgeo.hdfs.vector.shp.util; import java.util.Random; import java.util.StringTokenizer; import java.util.Vector; @SuppressWarnings("unchecked") public class StringUtils { public static String capitalizeFirst(String str) { if (str == null) return null; if (str.length() > 1) { return str.substring(0, 1).toUpperCase() + str.substring(1); } else if (str.length() == 1) { return str.toUpperCase(); } else { return str; } } public static String center(String str, int length) { if (str == null) return pad(length); int len = str.length(); int diff = length - len; if (diff <= 0) return str; int left = diff / 2; int right = diff - left; String temp = ""; temp += pad(left) + str + pad(right); return temp; } public static String getLeft(String str, int length) { return getLeft(str, length, false); } public static String getLeft(String str, int length, boolean indicator) { if (length < 0) return str; if (str == null) return null; if (str.length() > length) { if (indicator && length > 3) { return str.substring(0, length - 3) + "..."; } return str.substring(0, length); } return str; } public static String getPaddedLeft(String str, int length) { if (str == null) return null; String temp = ""; if (str.length() > length) { temp += str; return temp.substring(0, length); } temp = pad(str, length, ' '); return temp; } public static String getTableFormat(String str, int length) { if (str == null) return pad("<null>", length); String temp = getLeft(str, length, true); return pad(temp, length); } public static String insert(String str, int pos, String insertion) { if (str == null) return null; if (insertion == null) return str; StringBuffer result = new StringBuffer(); result.append(str); result.insert(pos, insertion); return result.toString(); } public static Object[] pack(String str) { return pack(str, ","); } public static Object[] pack(String str, String separator) { StringTokenizer st = new StringTokenizer(str, separator); Object[] temp = new Object[st.countTokens()]; int i = 0; while (st.hasMoreTokens()) { temp[i++] = st.nextToken(); } return temp; } public static String pad(int length) { return pad("", length, ' '); } public static String pad(int length, char padding) { return pad("", length, padding); } public static String pad(String str, int length) { return pad(str, length, ' '); } public static String pad(String str, int length, boolean random) { if (str == null) return null; StringBuffer result = new StringBuffer(); result.append(str); Random r = null; if (random) r = new Random(); if (result.length() < length) { int n = length - result.length(); for (int i = 0; i < n; i++) result.append((r != null) ? (char) (r.nextInt(126 - 32) + 32 + 1) : ' '); } return result.toString(); } public static String pad(String str, int length, char padding) { if (str == null) return null; StringBuffer result = new StringBuffer(); result.append(str); if (result.length() < length) { int n = length - result.length(); for (int i = 0; i < n; i++) result.append(padding); } return result.toString(); } public static String removeExtraInnerSpaces(String str) { if (str == null) return null; String temp = "" + str; while (temp.indexOf(" ") != -1) temp = replace(temp, " ", " "); return temp; } public static String removeInnerSpaces(String str) { return replace(str, " ", ""); } public static String replace(String str, String pattern, String replace) { if (str == null) return null; int s = 0; int e = 0; StringBuffer result = new StringBuffer(); while ((e = str.indexOf(pattern, s)) >= 0) { result.append(str.substring(s, e)); result.append(replace); s = e + pattern.length(); } result.append(str.substring(s)); return result.toString(); } public static String[] split(String str, String delimiter) { if (str == null) return null; String[] temp = null; if (delimiter == null || delimiter.length() == 0) { temp = new String[0]; temp[0] = str; } else { @SuppressWarnings("rawtypes") Vector v = new Vector(1); int pos = 0; int next = str.indexOf(delimiter); while (next != -1) { String fragment = str.substring(pos, next); v.add(fragment); pos += fragment.length() + delimiter.length(); next = str.indexOf(delimiter, pos); } v.add(str.substring(pos)); temp = new String[v.size()]; v.toArray(temp); } // return return temp; } public static String trimExtended(String str) { if (str == null) return null; StringBuffer result = new StringBuffer(); str = str.trim(); int s = 0; int e = 0; while ((e = str.indexOf(" ", s)) >= 0) { result.append(str.substring(s, e)); s = e + 1; } result.append(str.substring(s)); return result.toString(); } public static String trimLeft(String str, int length) { if (str == null) return null; if (str.length() <= length) return ""; StringBuffer result = new StringBuffer(); result.append(str.substring(str.length() - length)); return result.toString(); } public static String trimRight(String str, int length) { if (str == null) return null; if (str.length() <= length) return ""; if (length <= 0) return "" + str; StringBuffer result = new StringBuffer(); result.append(str.substring(0, str.length() - length)); return result.toString(); } }
ttislerdg/mrgeo
mrgeo-core/src/main/java/org/mrgeo/hdfs/vector/shp/util/StringUtils.java
Java
apache-2.0
6,682
/** * 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.catalog.exception; /** * Exception used when an attempt is made to create a resource which already exists. */ public class ResourceAlreadyExistsException extends CatalogException { public ResourceAlreadyExistsException(String message) { super(message, 409); } }
jnhagelberg/incubator-atlas
catalog/src/main/java/org/apache/atlas/catalog/exception/ResourceAlreadyExistsException.java
Java
apache-2.0
1,120
/** * @author Wei */ #include <boost/test/unit_test.hpp> #include <util/ustring/UString.h> //#include <la/analyzer/CharAnalyzer.h> #include <ilplib.hpp> #include "test_def.h" using namespace la; using namespace std; using namespace izenelib::util; BOOST_AUTO_TEST_SUITE( AnalyzerTest ) BOOST_AUTO_TEST_CASE(test_NotExtractSpecialChar) { CharAnalyzer analyzer; analyzer.setExtractSpecialChar(false); TermList termList; analyzer.analyze(UString("互联网(the Internet)中国 2010。", UString::UTF_8), termList); BOOST_CHECK_EQUAL(termList.size(), 8U); BOOST_CHECK_EQUAL( termList[0].text_, UString("互", UString::UTF_8) ); BOOST_CHECK_EQUAL( termList[1].text_, UString("联", UString::UTF_8) ); BOOST_CHECK_EQUAL( termList[2].text_, UString("网", UString::UTF_8) ); BOOST_CHECK_EQUAL( termList[3].text_, UString("the", UString::UTF_8) ); BOOST_CHECK_EQUAL( termList[4].text_, UString("Internet", UString::UTF_8) ); BOOST_CHECK_EQUAL( termList[5].text_, UString("中", UString::UTF_8) ); BOOST_CHECK_EQUAL( termList[6].text_, UString("国", UString::UTF_8) ); BOOST_CHECK_EQUAL( termList[7].text_, UString("2010", UString::UTF_8) ); } BOOST_AUTO_TEST_CASE(test_NotConvertToPlaceholder) { CharAnalyzer analyzer; analyzer.setExtractSpecialChar(true, false); TermList termList; analyzer.analyze(UString("互联网(the Internet)中国 2010。", UString::UTF_8), termList); BOOST_CHECK_EQUAL(termList.size(), 11U); BOOST_CHECK_EQUAL( termList[0].text_, UString("互", UString::UTF_8) ); BOOST_CHECK_EQUAL( termList[1].text_, UString("联", UString::UTF_8) ); BOOST_CHECK_EQUAL( termList[2].text_, UString("网", UString::UTF_8) ); BOOST_CHECK_EQUAL( termList[3].text_, UString("(", UString::UTF_8) ); BOOST_CHECK_EQUAL( termList[4].text_, UString("the", UString::UTF_8) ); BOOST_CHECK_EQUAL( termList[5].text_, UString("Internet", UString::UTF_8) ); BOOST_CHECK_EQUAL( termList[6].text_, UString(")", UString::UTF_8) ); BOOST_CHECK_EQUAL( termList[7].text_, UString("中", UString::UTF_8) ); BOOST_CHECK_EQUAL( termList[8].text_, UString("国", UString::UTF_8) ); BOOST_CHECK_EQUAL( termList[9].text_, UString("2010", UString::UTF_8) ); BOOST_CHECK_EQUAL( termList[10].text_, UString("。", UString::UTF_8) ); } BOOST_AUTO_TEST_SUITE_END()
pombredanne/ilplib
test/la/t_Analyzer.cpp
C++
apache-2.0
2,366
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2021-2021 ArangoDB GmbH, Cologne, Germany /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Lars Maier //////////////////////////////////////////////////////////////////////////////// #include "FakeReplicatedState.h" using namespace arangodb; using namespace arangodb::replication2; using namespace arangodb::replication2::replicated_state; void replicated_state::EntrySerializer<test::DefaultEntryType>::operator()( streams::serializer_tag_t<test::DefaultEntryType>, const test::DefaultEntryType& e, velocypack::Builder& b) const { velocypack::ObjectBuilder ob(&b); b.add("key", velocypack::Value(e.key)); b.add("value", velocypack::Value(e.value)); } auto replicated_state::EntryDeserializer<test::DefaultEntryType>::operator()( streams::serializer_tag_t<test::DefaultEntryType>, velocypack::Slice s) const -> test::DefaultEntryType { auto key = s.get("key").copyString(); auto value = s.get("value").copyString(); return test::DefaultEntryType{.key = key, .value = value}; }
wiltonlazary/arangodb
tests/Replication2/Mocks/FakeReplicatedState.cpp
C++
apache-2.0
1,720
<?php /** * Copyright (c) 2014 ScientiaMobile, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * Refer to the COPYING.txt file distributed with this package. * * @category WURFL * @package WURFL_Request * @copyright ScientiaMobile, Inc. * @license GNU Affero General Public License * @author Fantayeneh Asres Gizaw * @version $id$ */ /** * Generic WURFL Request object containing User Agent, UAProf and xhtml device data; its id * property is the MD5 hash of the user agent * @package WURFL_Request * * @property string $userAgent * @property string $userAgentProfile * @property boolean $xhtmlDevice true if the device is known to be XHTML-MP compatible * @property string $id Unique ID used for caching: MD5($userAgent) * @property WURFL_Request_MatchInfo $matchInfo Information about the match (available after matching) */ class WURFL_Request_GenericRequest { private $_request; private $_userAgent; private $_userAgentProfile; private $_xhtmlDevice; private $_id; private $_matchInfo; /** * @param array $request Original HTTP headers * @param string $userAgent * @param string $userAgentProfile * @param string $xhtmlDevice */ public function __construct(array $request, $userAgent, $userAgentProfile=null, $xhtmlDevice=null) { $this->_request = $request; $this->_userAgent = $userAgent; $this->_userAgentProfile = $userAgentProfile; $this->_xhtmlDevice = $xhtmlDevice; $this->_id = md5($userAgent); $this->_matchInfo = new WURFL_Request_MatchInfo(); } public function __get($name) { $name = '_'.$name; return $this->$name; } /** * Get the original HTTP header value from the request * @param string $name * @return string */ public function getOriginalHeader($name) { return array_key_exists($name, $this->_request)? $this->_request[$name]: null; } public function originalHeaderExists($name) { return array_key_exists($name, $this->_request); } }
ahoken/phptest
src/zend_test/library/wurfl-php/WURFL/Request/GenericRequest.php
PHP
apache-2.0
2,167
// SPDX-License-Identifier: Apache-2.0 // Copyright 2017-2019 Authors of Cilium package cmd import ( "archive/tar" "bytes" "compress/gzip" "crypto/sha256" "encoding/hex" "fmt" "io" "os" "path/filepath" "regexp" "strings" ) type tarWriter interface { io.Writer WriteHeader(hdr *tar.Header) error } type walker struct { baseDir, dbgDir string output tarWriter log io.Writer } func newWalker(baseDir, dbgDir string, output tarWriter, logger io.Writer) *walker { return &walker{ baseDir: baseDir, dbgDir: dbgDir, output: output, log: logger, } } func (w *walker) walkPath(path string, info os.FileInfo, err error) error { if err != nil { fmt.Fprintf(w.log, "Error while walking path %s: %s", path, err) return nil } if info == nil { fmt.Fprintf(w.log, "No file info available") return nil } file, err := os.Open(path) if err != nil { fmt.Fprintf(w.log, "Failed to open %s: %s\n", path, err) // TODO: Write an empty file here, just to hint that this file // existed by there was some problem attempting to add it. return nil } defer file.Close() if info.IsDir() { fmt.Fprintf(w.log, "Skipping directory %s\n", info.Name()) return nil } // Just get the latest fileInfo to make sure that the size is correctly // when the file is write to tar file fpInfo, err := file.Stat() if err != nil { fpInfo, err = os.Lstat(file.Name()) if err != nil { fmt.Fprintf(w.log, "Failed to retrieve file information: %s\n", err) return nil } } header, err := tar.FileInfoHeader(fpInfo, fpInfo.Name()) if err != nil { fmt.Fprintf(w.log, "Failed to prepare file info %s: %s\n", fpInfo.Name(), err) return nil } if w.baseDir != "" { header.Name = filepath.Join(w.baseDir, strings.TrimPrefix(path, w.dbgDir)) } if err := w.output.WriteHeader(header); err != nil { fmt.Fprintf(w.log, "Failed to write header: %s\n", err) return nil } _, err = io.Copy(w.output, file) return err } func createArchive(dbgDir string, sendArchiveToStdout bool) (string, error) { // Based on http://blog.ralch.com/tutorial/golang-working-with-tar-and-gzip/ file := os.Stdout archivePath := "STDOUT" if !sendArchiveToStdout { archivePath = fmt.Sprintf("%s.tar", dbgDir) var err error file, err = os.Create(archivePath) if err != nil { return "", err } defer file.Close() } writer := tar.NewWriter(file) defer writer.Close() var baseDir string if info, err := os.Stat(dbgDir); os.IsNotExist(err) { fmt.Fprintf(os.Stderr, "Debug directory does not exist %s\n", err) return "", err } else if err == nil && info.IsDir() { baseDir = filepath.Base(dbgDir) } walker := newWalker(baseDir, dbgDir, writer, os.Stderr) return archivePath, filepath.Walk(dbgDir, walker.walkPath) } func createGzip(dbgDir string, sendArchiveToStdout bool) (string, error) { // Based on http://blog.ralch.com/tutorial/golang-working-with-tar-and-gzip/ source, err := createArchive(dbgDir, false) if err != nil { return "", err } reader, err := os.Open(source) if err != nil { return "", err } writer := os.Stdout filename := "STDOUT" target := filename if !sendArchiveToStdout { filename = filepath.Base(source) target = fmt.Sprintf("%s.gz", source) writer, err = os.Create(target) if err != nil { return "", err } defer writer.Close() } archiver := gzip.NewWriter(writer) archiver.Name = filename defer archiver.Close() _, err = io.Copy(archiver, reader) if err != nil { return "", err } return target, nil } // Note that `auth-trunc` is also a relevant pattern, but we already match on the more generic // `auth` pattern. var isEncryptionKey = regexp.MustCompile("(auth|enc|aead|comp)(.*[[:blank:]](0[xX][[:xdigit:]]+))?") // hashEncryptionKeys processes the buffer containing the output of `ip -s xfrm state`. // It searches for IPsec keys in the output and replaces them by their hash. func hashEncryptionKeys(output []byte) []byte { var b bytes.Buffer lines := bytes.Split(output, []byte("\n")) // Search for lines containing encryption keys. for i, line := range lines { // isEncryptionKey.FindStringSubmatchIndex(line) will return: // - [], if the global pattern is not found // - a slice of integers, if the global pattern is found. The // first two integers are the start and end offsets of the // global pattern. The remaining integers are the start and // end offset of each submatch group (delimited in the // regular expressions by parenthesis). // // If the global pattern is found, the start and end offset of // the hexadecimal string (the third submatch) will be at index // 6 and 7 in the slice. They may be equal to -1 if the // submatch, marked as optional ('?'), is not found. matched := isEncryptionKey.FindSubmatchIndex(line) if matched != nil && matched[6] > 0 { key := line[matched[6]:matched[7]] h := sha256.New() h.Write(key) sum := h.Sum(nil) hashedKey := make([]byte, hex.EncodedLen(len(sum))) hex.Encode(hashedKey, sum) fmt.Fprintf(&b, "%s[hash:%s]%s", line[:matched[6]], hashedKey, line[matched[7]:]) } else if matched != nil && matched[6] < 0 { b.WriteString("[redacted]") } else { b.Write(line) } if i < len(lines)-1 { b.WriteByte('\n') } } return b.Bytes() }
tklauser/cilium
bugtool/cmd/helper.go
GO
apache-2.0
5,312
/* * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.configurationprocessor; import org.junit.jupiter.api.Test; import org.springframework.boot.configurationprocessor.metadata.ConfigurationMetadata; import org.springframework.boot.configurationprocessor.metadata.Metadata; import org.springframework.boot.configurationsample.generic.AbstractGenericProperties; import org.springframework.boot.configurationsample.generic.ComplexGenericProperties; import org.springframework.boot.configurationsample.generic.GenericConfig; import org.springframework.boot.configurationsample.generic.SimpleGenericProperties; import org.springframework.boot.configurationsample.generic.UnresolvedGenericProperties; import org.springframework.boot.configurationsample.generic.UpperBoundGenericPojo; import org.springframework.boot.configurationsample.generic.WildcardConfig; import static org.assertj.core.api.Assertions.assertThat; /** * Metadata generation tests for generics handling. * * @author Stephane Nicoll */ class GenericsMetadataGenerationTests extends AbstractMetadataGenerationTests { @Test void simpleGenericProperties() { ConfigurationMetadata metadata = compile(AbstractGenericProperties.class, SimpleGenericProperties.class); assertThat(metadata).has(Metadata.withGroup("generic").fromSource(SimpleGenericProperties.class)); assertThat(metadata).has(Metadata.withProperty("generic.name", String.class) .fromSource(SimpleGenericProperties.class).withDescription("Generic name.").withDefaultValue(null)); assertThat(metadata).has(Metadata .withProperty("generic.mappings", "java.util.Map<java.lang.Integer,java.time.Duration>") .fromSource(SimpleGenericProperties.class).withDescription("Generic mappings.").withDefaultValue(null)); assertThat(metadata.getItems()).hasSize(3); } @Test void complexGenericProperties() { ConfigurationMetadata metadata = compile(ComplexGenericProperties.class); assertThat(metadata).has(Metadata.withGroup("generic").fromSource(ComplexGenericProperties.class)); assertThat(metadata).has(Metadata.withGroup("generic.test").ofType(UpperBoundGenericPojo.class) .fromSource(ComplexGenericProperties.class)); assertThat(metadata) .has(Metadata.withProperty("generic.test.mappings", "java.util.Map<java.lang.Enum<T>,java.lang.String>") .fromSource(UpperBoundGenericPojo.class)); assertThat(metadata.getItems()).hasSize(3); } @Test void unresolvedGenericProperties() { ConfigurationMetadata metadata = compile(AbstractGenericProperties.class, UnresolvedGenericProperties.class); assertThat(metadata).has(Metadata.withGroup("generic").fromSource(UnresolvedGenericProperties.class)); assertThat(metadata).has(Metadata.withProperty("generic.name", String.class) .fromSource(UnresolvedGenericProperties.class).withDescription("Generic name.").withDefaultValue(null)); assertThat(metadata) .has(Metadata.withProperty("generic.mappings", "java.util.Map<java.lang.Number,java.lang.Object>") .fromSource(UnresolvedGenericProperties.class).withDescription("Generic mappings.") .withDefaultValue(null)); assertThat(metadata.getItems()).hasSize(3); } @Test void genericTypes() { ConfigurationMetadata metadata = compile(GenericConfig.class); assertThat(metadata).has(Metadata.withGroup("generic") .ofType("org.springframework.boot.configurationsample.generic.GenericConfig")); assertThat(metadata).has(Metadata.withGroup("generic.foo") .ofType("org.springframework.boot.configurationsample.generic.GenericConfig$Foo")); assertThat(metadata).has(Metadata.withGroup("generic.foo.bar") .ofType("org.springframework.boot.configurationsample.generic.GenericConfig$Bar")); assertThat(metadata).has(Metadata.withGroup("generic.foo.bar.biz") .ofType("org.springframework.boot.configurationsample.generic.GenericConfig$Bar$Biz")); assertThat(metadata).has( Metadata.withProperty("generic.foo.name").ofType(String.class).fromSource(GenericConfig.Foo.class)); assertThat(metadata).has(Metadata.withProperty("generic.foo.string-to-bar").ofType( "java.util.Map<java.lang.String,org.springframework.boot.configurationsample.generic.GenericConfig$Bar<java.lang.Integer>>") .fromSource(GenericConfig.Foo.class)); assertThat(metadata).has(Metadata.withProperty("generic.foo.string-to-integer") .ofType("java.util.Map<java.lang.String,java.lang.Integer>").fromSource(GenericConfig.Foo.class)); assertThat(metadata).has(Metadata.withProperty("generic.foo.bar.name").ofType("java.lang.String") .fromSource(GenericConfig.Bar.class)); assertThat(metadata).has(Metadata.withProperty("generic.foo.bar.biz.name").ofType("java.lang.String") .fromSource(GenericConfig.Bar.Biz.class)); assertThat(metadata.getItems()).hasSize(9); } @Test void wildcardTypes() { ConfigurationMetadata metadata = compile(WildcardConfig.class); assertThat(metadata).has(Metadata.withGroup("wildcard").ofType(WildcardConfig.class)); assertThat(metadata).has(Metadata.withProperty("wildcard.string-to-number") .ofType("java.util.Map<java.lang.String,? extends java.lang.Number>").fromSource(WildcardConfig.class)); assertThat(metadata).has(Metadata.withProperty("wildcard.integers") .ofType("java.util.List<? super java.lang.Integer>").fromSource(WildcardConfig.class)); assertThat(metadata.getItems()).hasSize(3); } }
wilkinsona/spring-boot
spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/GenericsMetadataGenerationTests.java
Java
apache-2.0
5,965
<!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_111) on Thu Aug 18 01:51:17 UTC 2016 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Class org.apache.hadoop.yarn.logaggregation.AggregatedLogFormat.LogKey (Apache Hadoop Main 2.7.3 API)</title> <meta name="date" content="2016-08-18"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.hadoop.yarn.logaggregation.AggregatedLogFormat.LogKey (Apache Hadoop Main 2.7.3 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/hadoop/yarn/logaggregation/AggregatedLogFormat.LogKey.html" title="class in org.apache.hadoop.yarn.logaggregation">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/hadoop/yarn/logaggregation/class-use/AggregatedLogFormat.LogKey.html" target="_top">Frames</a></li> <li><a href="AggregatedLogFormat.LogKey.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.apache.hadoop.yarn.logaggregation.AggregatedLogFormat.LogKey" class="title">Uses of Class<br>org.apache.hadoop.yarn.logaggregation.AggregatedLogFormat.LogKey</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../org/apache/hadoop/yarn/logaggregation/AggregatedLogFormat.LogKey.html" title="class in org.apache.hadoop.yarn.logaggregation">AggregatedLogFormat.LogKey</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#org.apache.hadoop.yarn.logaggregation">org.apache.hadoop.yarn.logaggregation</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.apache.hadoop.yarn.logaggregation"> <!-- --> </a> <h3>Uses of <a href="../../../../../../org/apache/hadoop/yarn/logaggregation/AggregatedLogFormat.LogKey.html" title="class in org.apache.hadoop.yarn.logaggregation">AggregatedLogFormat.LogKey</a> in <a href="../../../../../../org/apache/hadoop/yarn/logaggregation/package-summary.html">org.apache.hadoop.yarn.logaggregation</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../org/apache/hadoop/yarn/logaggregation/package-summary.html">org.apache.hadoop.yarn.logaggregation</a> with parameters of type <a href="../../../../../../org/apache/hadoop/yarn/logaggregation/AggregatedLogFormat.LogKey.html" title="class in org.apache.hadoop.yarn.logaggregation">AggregatedLogFormat.LogKey</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="http://docs.oracle.com/javase/7/docs/api/java/io/DataInputStream.html?is-external=true" title="class or interface in java.io">DataInputStream</a></code></td> <td class="colLast"><span class="strong">AggregatedLogFormat.LogReader.</span><code><strong><a href="../../../../../../org/apache/hadoop/yarn/logaggregation/AggregatedLogFormat.LogReader.html#next(org.apache.hadoop.yarn.logaggregation.AggregatedLogFormat.LogKey)">next</a></strong>(<a href="../../../../../../org/apache/hadoop/yarn/logaggregation/AggregatedLogFormat.LogKey.html" title="class in org.apache.hadoop.yarn.logaggregation">AggregatedLogFormat.LogKey</a>&nbsp;key)</code> <div class="block">Read the next key and return the value-stream.</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/hadoop/yarn/logaggregation/AggregatedLogFormat.LogKey.html" title="class in org.apache.hadoop.yarn.logaggregation">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/hadoop/yarn/logaggregation/class-use/AggregatedLogFormat.LogKey.html" target="_top">Frames</a></li> <li><a href="AggregatedLogFormat.LogKey.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; 2016 <a href="http://www.apache.org">Apache Software Foundation</a>. All rights reserved.</small></p> </body> </html>
TK-TarunW/ecosystem
hadoop-2.7.3/share/doc/hadoop/api/org/apache/hadoop/yarn/logaggregation/class-use/AggregatedLogFormat.LogKey.html
HTML
apache-2.0
7,363
<span> <mathjax-bind mathjax-data="latexAnswer"> </mathjax-bind> </span>
AllanYangZhou/oppia
extensions/interactions/MathExpressionInput/directives/math_expression_input_short_response_directive.html
HTML
apache-2.0
77
/* * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.actuate.autoconfigure.metrics.export.atlas; import com.netflix.spectator.atlas.AtlasConfig; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link AtlasProperties}. * * @author Stephane Nicoll */ public class AtlasPropertiesTests { @Test public void defaultValuesAreConsistent() { AtlasProperties properties = new AtlasProperties(); AtlasConfig config = (key) -> null; assertThat(properties.getStep()).isEqualTo(config.step()); assertThat(properties.isEnabled()).isEqualTo(config.enabled()); assertThat(properties.getConnectTimeout()).isEqualTo(config.connectTimeout()); assertThat(properties.getReadTimeout()).isEqualTo(config.readTimeout()); assertThat(properties.getNumThreads()).isEqualTo(config.numThreads()); assertThat(properties.getBatchSize()).isEqualTo(config.batchSize()); assertThat(properties.getUri()).isEqualTo(config.uri()); assertThat(properties.getMeterTimeToLive()).isEqualTo(config.meterTTL()); assertThat(properties.isLwcEnabled()).isEqualTo(config.lwcEnabled()); assertThat(properties.getConfigRefreshFrequency()) .isEqualTo(config.configRefreshFrequency()); assertThat(properties.getConfigTimeToLive()).isEqualTo(config.configTTL()); assertThat(properties.getConfigUri()).isEqualTo(config.configUri()); assertThat(properties.getEvalUri()).isEqualTo(config.evalUri()); } }
hello2009chen/spring-boot
spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/atlas/AtlasPropertiesTests.java
Java
apache-2.0
2,045
{% extends "base_statdev.html" %} {% block page_content_inner %} <div class="container-fluid"> <div class="row"> <h1>Communication for {{ object.application.get_app_type_display }} - {{ object.pk }}</h1> <p><a href="{% url "organisation_details_actions" object.pk "company" %}">Return to organisation details</a></p> <h2>communication log</h2> <table class="table table-bordered table-striped"> <thead> <tr> <th>Date & time</th> <th>Comms Type</th> <th>To</th> <th>From</th> <th>Subject</th> <th>Details</th> <th>Documents</th> </tr> </thead> {% if communications.exists %} <tbody> {% for communication in communications %} <tr> <td>{{ communication.created|date:"d-M-Y H:i" }}</td> <td>{{ communication.get_comms_type_display }}</td> <td>{{ communication.comms_to }}</td> <td>{{ communication.comms_from }}</td> <td>{{ communication.subject }}</td> <td>{{ communication.details }}</td> <td> {% if communication.record.exists %} {% for doc in communication.records %} <div class="col-sm-12 col-md-12 col-lg-12"><A HREF='{{ doc.file_url }}' target="new_tab_{{ doc.id }}">{{ doc.path_short }}</A></div> {% endfor %} {% endif %} </td> </tr> {% endfor %} {% endif %} </table> <p><a href="{% url "person_details_actions" object.pk "personal" %}">Return to organisation details</a></p> </div> </div> {% endblock page_content_inner %}
xzzy/statdev
applications/templates/applications/organisation_comms.html
HTML
apache-2.0
1,928
/* * Copyright 2017 Google * * 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 <Foundation/Foundation.h> #import "FirebaseDatabase/Sources/Persistence/FStorageEngine.h" @interface FMockStorageEngine : NSObject <FStorageEngine> @end
firebase/firebase-ios-sdk
FirebaseDatabase/Tests/Helpers/FMockStorageEngine.h
C
apache-2.0
756
--- page_title: Docker Swarm page_description: Swarm: a Docker-native clustering system page_keywords: docker, swarm, clustering --- # Docker Swarm Docker Swarm is native clustering for Docker. It allows you create and access to a pool of Docker hosts using the full suite of Docker tools. Because Docker Swarm serves the standard Docker API, any tool that already communicates with a Docker daemon can use Swarm to transparently scale to multiple hosts. Supported tools include, but are not limited to, the following: - Dokku - Docker Compose - Krane - Jenkins And of course, the Docker client itself is also supported. Like other Docker projects, Docker Swarm follows the "swap, plug, and play" principle. As initial development settles, an API will develop to enable pluggable backends. This means you can swap out the scheduling backend Docker Swarm uses out-of-the-box with a backend you prefer. Swarm's swappable design provides a smooth out-of-box experience for most use cases, and allows large-scale production deployments to swap for more powerful backends, like Mesos. > **Note**: Swarm is currently in BETA, so things are likely to change. We > don't recommend you use it in production yet. ## Understand swarm creation The first step to creating a swarm on your network is to pull the Docker Swarm image. Then, using Docker, you configure the swarm manager and all the nodes to run Docker Swarm. This method requires that you: * open a TCP port on each node for communication with the swarm manager * install Docker on each node * create and manage TLS certificates to secure your swarm As a starting point, the manual method is is best suited for experienced administrators or programmers contributing to Docker Swarm. The alternative is to use `docker-machine` to install a swarm. Using Docker Machine, you can quickly install a Docker Swarm on cloud providers or inside your own data center. If you have VirtualBox installed on your local machine, you can quickly build and explore Docker Swarm in your local environment. This method automatically generates a certificate to secure your swarm. Using Docker Machine is the best method for users getting started with Swarm for the first time. To try the recommended method of getting started, see [Get Started with Docker Swarm](install-w-machine.md). If you are interested manually installing or interested in contributing, see [Create a swarm for development](install-manual.md). ## Discovery services To dynamically configure and manage the services in your containers, you use a discovery backend with Docker Swarm. For information on which backends are available, see the [Discovery service](https://docs.docker.com/swarm/discovery/) documentation. ## Advanced Scheduling See [filters](https://docs.docker.com/swarm/scheduler/filter/) and [strategies](https://docs.docker.com/swarm/scheduler/strategy/) to learn more about advanced scheduling. ## Swarm API The [Docker Swarm API](https://docs.docker.com/swarm/API/) is compatible with the [Docker remote API](http://docs.docker.com/reference/api/docker_remote_api/), and extends it with some new endpoints. # Getting help Docker Swarm is still in its infancy and under active development. If you need help, would like to contribute, or simply want to talk about the project with like-minded individuals, we have a number of open channels for communication. * To report bugs or file feature requests: please use the [issue tracker on Github](https://github.com/docker/machine/issues). * To talk about the project with people in real time: please join the `#docker-swarm` channel on IRC. * To contribute code or documentation changes: please submit a [pull request on Github](https://github.com/docker/machine/pulls). For more information and resources, please visit the [Getting Help project page](https://docs.docker.com/project/get-help/).
affo/swarm
docs/index.md
Markdown
apache-2.0
3,890
//****************************************************************** // // Copyright 2016 Samsung Electronics 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 a // // 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. // //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= #include <limits.h> #include <stdlib.h> #include <string.h> #ifdef RD_SERVER #include "sqlite3.h" #endif #include "octypes.h" #include "ocstack.h" #include "experimental/ocrandom.h" #include "experimental/logger.h" #include "ocpayload.h" #include "ocendpoint.h" #include "oic_malloc.h" #include "oic_string.h" #include "oic_time.h" #include "cainterface.h" #define TAG "OIC_RI_RESOURCEDIRECTORY" #define VERIFY_NON_NULL(arg) \ if (!(arg)) \ { \ OIC_LOG(ERROR, TAG, #arg " is NULL"); \ result = OC_STACK_NO_MEMORY; \ goto exit; \ } #ifdef RD_SERVER static const char *gRDPath = "RD.db"; static sqlite3 *gRDDB = NULL; /* Column indices of RD_DEVICE_LINK_LIST table */ static const uint8_t ins_index = 0; static const uint8_t href_index = 1; static const uint8_t rel_index = 2; static const uint8_t anchor_index = 3; static const uint8_t bm_index = 4; static const uint8_t d_index = 5; /* Column indices of RD_LINK_RT table */ static const uint8_t rt_value_index = 0; /* Column indices of RD_LINK_IF table */ static const uint8_t if_value_index = 0; /* Column indices of RD_LINK_EP table */ static const uint8_t ep_value_index = 0; static const uint8_t pri_value_index = 1; #define VERIFY_SQLITE(arg) \ if (SQLITE_OK != (arg)) \ { \ OIC_LOG_V(ERROR, TAG, "Error in " #arg ", Error Message: %s", sqlite3_errmsg(gRDDB)); \ result = OC_STACK_ERROR; \ goto exit; \ } OCStackResult OC_CALL OCRDDatabaseSetStorageFilename(const char *filename) { if (!filename) { OIC_LOG(ERROR, TAG, "The persistent storage filename is invalid"); return OC_STACK_INVALID_PARAM; } gRDPath = filename; return OC_STACK_OK; } const char *OC_CALL OCRDDatabaseGetStorageFilename() { return gRDPath; } static void errorCallback(void *arg, int errCode, const char *errMsg) { OC_UNUSED(arg); OC_UNUSED(errCode); OC_UNUSED(errMsg); OIC_LOG_V(ERROR, TAG, "SQLLite Error: %s : %d", errMsg, errCode); } static OCStackResult appendStringLL(OCStringLL **type, const unsigned char *value) { OCStackResult result; OCStringLL *temp= (OCStringLL*)OICCalloc(1, sizeof(OCStringLL)); VERIFY_NON_NULL(temp); temp->value = OICStrdup((char *)value); VERIFY_NON_NULL(temp->value); temp->next = NULL; if (!*type) { *type = temp; } else { OCStringLL *tmp = *type; for (; tmp->next; tmp = tmp->next); tmp->next = temp; } temp = NULL; result = OC_STACK_OK; exit: if (temp) { OICFree(temp->value); OICFree(temp); } return result; } /* stmt is of form "SELECT * FROM RD_DEVICE_LINK_LIST ..." */ static OCStackResult ResourcePayloadCreate(sqlite3_stmt *stmt, OCDevAddr *devAddr, OCDiscoveryPayload *discPayload) { int res = sqlite3_step(stmt); if (SQLITE_ROW != res) { return OC_STACK_NO_RESOURCE; } OCStackResult result; OCResourcePayload *resourcePayload = NULL; OCEndpointPayload *epPayload = NULL; sqlite3_stmt *stmtRT = NULL; sqlite3_stmt *stmtIF = NULL; sqlite3_stmt *stmtEP = NULL; sqlite3_stmt *stmtDI = NULL; while (SQLITE_ROW == res) { resourcePayload = (OCResourcePayload *)OICCalloc(1, sizeof(OCResourcePayload)); VERIFY_NON_NULL(resourcePayload); sqlite3_int64 id = sqlite3_column_int64(stmt, ins_index); const unsigned char *uri = sqlite3_column_text(stmt, href_index); const unsigned char *rel = sqlite3_column_text(stmt, rel_index); const unsigned char *anchor = sqlite3_column_text(stmt, anchor_index); sqlite3_int64 bitmap = sqlite3_column_int64(stmt, bm_index); sqlite3_int64 deviceId = sqlite3_column_int64(stmt, d_index); OIC_LOG_V(DEBUG, TAG, " %s %" PRId64, uri, (int64_t) deviceId); resourcePayload->uri = OICStrdup((char *)uri); VERIFY_NON_NULL(resourcePayload->uri) if (rel) { resourcePayload->rel = OICStrdup((char *)rel); VERIFY_NON_NULL(resourcePayload->rel); } if (anchor) { resourcePayload->anchor = OICStrdup((char *)anchor); VERIFY_NON_NULL(resourcePayload->anchor); } const char rt[] = "SELECT rt FROM RD_LINK_RT WHERE LINK_ID=@id"; int rtSize = (int)sizeof(rt); VERIFY_SQLITE(sqlite3_prepare_v2(gRDDB, rt, rtSize, &stmtRT, NULL)); VERIFY_SQLITE(sqlite3_bind_int64(stmtRT, sqlite3_bind_parameter_index(stmtRT, "@id"), id)); while (SQLITE_ROW == sqlite3_step(stmtRT)) { const unsigned char *tempRt = sqlite3_column_text(stmtRT, rt_value_index); result = appendStringLL(&resourcePayload->types, tempRt); if (OC_STACK_OK != result) { goto exit; } } VERIFY_SQLITE(sqlite3_finalize(stmtRT)); stmtRT = NULL; const char itf[] = "SELECT if FROM RD_LINK_IF WHERE LINK_ID=@id"; int itfSize = (int)sizeof(itf); VERIFY_SQLITE(sqlite3_prepare_v2(gRDDB, itf, itfSize, &stmtIF, NULL)); VERIFY_SQLITE(sqlite3_bind_int64(stmtIF, sqlite3_bind_parameter_index(stmtIF, "@id"), id)); while (SQLITE_ROW == sqlite3_step(stmtIF)) { const unsigned char *tempItf = sqlite3_column_text(stmtIF, if_value_index); result = appendStringLL(&resourcePayload->interfaces, tempItf); if (OC_STACK_OK != result) { goto exit; } } VERIFY_SQLITE(sqlite3_finalize(stmtIF)); stmtIF = NULL; resourcePayload->bitmap = (uint8_t)(bitmap & (OC_OBSERVABLE | OC_DISCOVERABLE)); CAEndpoint_t *networkInfo = NULL; size_t infoSize = 0; if (devAddr) { CAResult_t caResult = CAGetNetworkInformation(&networkInfo, &infoSize); if (CA_STATUS_FAILED == caResult) { OIC_LOG(WARNING, TAG, "CAGetNetworkInformation has error on parsing network infomation"); } } const char ep[] = "SELECT ep,pri FROM RD_LINK_EP WHERE LINK_ID=@id"; int epSize = (int)sizeof(ep); VERIFY_SQLITE(sqlite3_prepare_v2(gRDDB, ep, epSize, &stmtEP, NULL)); VERIFY_SQLITE(sqlite3_bind_int64(stmtEP, sqlite3_bind_parameter_index(stmtEP, "@id"), id)); while (SQLITE_ROW == sqlite3_step(stmtEP)) { epPayload = (OCEndpointPayload *)OICCalloc(1, sizeof(OCEndpointPayload)); VERIFY_NON_NULL(epPayload); const unsigned char *tempEp = sqlite3_column_text(stmtEP, ep_value_index); result = OCParseEndpointString((const char *)tempEp, epPayload); if (OC_STACK_OK != result) { goto exit; } sqlite3_int64 pri = sqlite3_column_int64(stmtEP, pri_value_index); epPayload->pri = (uint16_t)pri; bool includeEp = true; if (devAddr) { CAEndpoint_t *info = NULL; for (size_t i = 0; i < infoSize; ++i) { if (!strcmp(epPayload->addr, networkInfo[i].addr)) { info = &networkInfo[i]; break; } } includeEp = info && (((OC_ADAPTER_IP | OC_ADAPTER_TCP) & (devAddr->adapter)) && ((((CA_ADAPTER_IP | CA_ADAPTER_TCP) & info->adapter) && (info->ifindex == devAddr->ifindex)) || info->adapter == CA_ADAPTER_RFCOMM_BTEDR)); } if (includeEp) { OCEndpointPayload **tmp = &resourcePayload->eps; while (*tmp) { tmp = &(*tmp)->next; } *tmp = epPayload; } else { OICFree(epPayload); } epPayload = NULL; } VERIFY_SQLITE(sqlite3_finalize(stmtEP)); stmtEP = NULL; if (networkInfo) { OICFree(networkInfo); } const char di[] = "SELECT di FROM RD_DEVICE_LIST " "INNER JOIN RD_DEVICE_LINK_LIST ON RD_DEVICE_LINK_LIST.DEVICE_ID = RD_DEVICE_LIST.ID " "WHERE RD_DEVICE_LINK_LIST.DEVICE_ID=@deviceId"; int diSize = (int)sizeof(di); const uint8_t di_index = 0; VERIFY_SQLITE(sqlite3_prepare_v2(gRDDB, di, diSize, &stmtDI, NULL)); VERIFY_SQLITE(sqlite3_bind_int64(stmtDI, sqlite3_bind_parameter_index(stmtDI, "@deviceId"), deviceId)); res = sqlite3_step(stmtDI); if (SQLITE_ROW == res || SQLITE_DONE == res) { const unsigned char *tempDi = sqlite3_column_text(stmtDI, di_index); OIC_LOG_V(DEBUG, TAG, " %s", tempDi); discPayload->sid = OICStrdup((char *)tempDi); VERIFY_NON_NULL(discPayload->sid); } VERIFY_SQLITE(sqlite3_finalize(stmtDI)); stmtDI = NULL; OCDiscoveryPayloadAddNewResource(discPayload, resourcePayload); resourcePayload = NULL; res = sqlite3_step(stmt); } result = OC_STACK_OK; exit: sqlite3_finalize(stmtDI); sqlite3_finalize(stmtEP); sqlite3_finalize(stmtIF); sqlite3_finalize(stmtRT); OICFree(epPayload); OCDiscoveryResourceDestroy(resourcePayload); return result; } static OCStackResult CheckResources(const char *interfaceType, const char *resourceType, OCDevAddr *devAddr, OCDiscoveryPayload *discPayload) { if (!interfaceType && !resourceType) { return OC_STACK_INVALID_QUERY; } if (!discPayload || !discPayload->sid) { return OC_STACK_INTERNAL_SERVER_ERROR; } size_t sidLength = strlen(discPayload->sid); size_t resourceTypeLength = resourceType ? strlen(resourceType) : 0; size_t interfaceTypeLength = interfaceType ? strlen(interfaceType) : 0; if ((sidLength > INT_MAX) || (resourceTypeLength > INT_MAX) || (interfaceTypeLength > INT_MAX)) { return OC_STACK_INVALID_QUERY; } OCStackResult result = OC_STACK_OK; sqlite3_stmt *stmt = NULL; if (resourceType) { if (!interfaceType || 0 == strcmp(interfaceType, OC_RSRVD_INTERFACE_LL) || 0 == strcmp(interfaceType, OC_RSRVD_INTERFACE_DEFAULT)) { const char input[] = "SELECT * FROM RD_DEVICE_LINK_LIST " "INNER JOIN RD_DEVICE_LIST ON RD_DEVICE_LINK_LIST.DEVICE_ID=RD_DEVICE_LIST.ID " "INNER JOIN RD_LINK_RT ON RD_DEVICE_LINK_LIST.INS=RD_LINK_RT.LINK_ID " "WHERE RD_DEVICE_LIST.di LIKE @di AND RD_LINK_RT.rt LIKE @resourceType"; int inputSize = (int)sizeof(input); VERIFY_SQLITE(sqlite3_prepare_v2(gRDDB, input, inputSize, &stmt, NULL)); VERIFY_SQLITE(sqlite3_bind_text(stmt, sqlite3_bind_parameter_index(stmt, "@di"), discPayload->sid, (int)sidLength, SQLITE_STATIC)); VERIFY_SQLITE(sqlite3_bind_text(stmt, sqlite3_bind_parameter_index(stmt, "@resourceType"), resourceType, (int)resourceTypeLength, SQLITE_STATIC)); } else { const char input[] = "SELECT * FROM RD_DEVICE_LINK_LIST " "INNER JOIN RD_DEVICE_LIST ON RD_DEVICE_LINK_LIST.DEVICE_ID=RD_DEVICE_LIST.ID " "INNER JOIN RD_LINK_RT ON RD_DEVICE_LINK_LIST.INS=RD_LINK_RT.LINK_ID " "INNER JOIN RD_LINK_IF ON RD_DEVICE_LINK_LIST.INS=RD_LINK_IF.LINK_ID " "WHERE RD_DEVICE_LIST.di LIKE @di " "AND RD_LINK_RT.rt LIKE @resourceType " "AND RD_LINK_IF.if LIKE @interfaceType"; int inputSize = (int)sizeof(input); VERIFY_SQLITE(sqlite3_prepare_v2(gRDDB, input, inputSize, &stmt, NULL)); VERIFY_SQLITE(sqlite3_bind_text(stmt, sqlite3_bind_parameter_index(stmt, "@di"), discPayload->sid, (int)sidLength, SQLITE_STATIC)); VERIFY_SQLITE(sqlite3_bind_text(stmt, sqlite3_bind_parameter_index(stmt, "@resourceType"), resourceType, (int)resourceTypeLength, SQLITE_STATIC)); VERIFY_SQLITE(sqlite3_bind_text(stmt, sqlite3_bind_parameter_index(stmt, "@interfaceType"), interfaceType, (int)interfaceTypeLength, SQLITE_STATIC)); } result = ResourcePayloadCreate(stmt, devAddr, discPayload); } else if (interfaceType) { if (0 == strcmp(interfaceType, OC_RSRVD_INTERFACE_LL) || 0 == strcmp(interfaceType, OC_RSRVD_INTERFACE_DEFAULT)) { const char input[] = "SELECT * FROM RD_DEVICE_LINK_LIST " "INNER JOIN RD_DEVICE_LIST ON RD_DEVICE_LINK_LIST.DEVICE_ID=RD_DEVICE_LIST.ID " "WHERE RD_DEVICE_LIST.di LIKE @di"; int inputSize = (int)sizeof(input); VERIFY_SQLITE(sqlite3_prepare_v2(gRDDB, input, inputSize, &stmt, NULL)); VERIFY_SQLITE(sqlite3_bind_text(stmt, sqlite3_bind_parameter_index(stmt, "@di"), discPayload->sid, (int)sidLength, SQLITE_STATIC)); } else { const char input[] = "SELECT * FROM RD_DEVICE_LINK_LIST " "INNER JOIN RD_DEVICE_LIST ON RD_DEVICE_LINK_LIST.DEVICE_ID=RD_DEVICE_LIST.ID " "INNER JOIN RD_LINK_IF ON RD_DEVICE_LINK_LIST.INS=RD_LINK_IF.LINK_ID " "WHERE RD_DEVICE_LIST.di LIKE @di AND RD_LINK_IF.if LIKE @interfaceType"; int inputSize = (int)sizeof(input); VERIFY_SQLITE(sqlite3_prepare_v2(gRDDB, input, inputSize, &stmt, NULL)); VERIFY_SQLITE(sqlite3_bind_text(stmt, sqlite3_bind_parameter_index(stmt, "@di"), discPayload->sid, (int)sidLength, SQLITE_STATIC)); VERIFY_SQLITE(sqlite3_bind_text(stmt, sqlite3_bind_parameter_index(stmt, "@interfaceType"), interfaceType, (int)interfaceTypeLength, SQLITE_STATIC)); } result = ResourcePayloadCreate(stmt, devAddr, discPayload); } exit: sqlite3_finalize(stmt); return result; } static OCStackResult deleteResources(const char *deviceId, const int64_t *instanceIds, uint16_t nInstanceIds) { char *delResource = NULL; sqlite3_stmt *stmt = NULL; OCStackResult result; VERIFY_SQLITE(sqlite3_exec(gRDDB, "BEGIN TRANSACTION", NULL, NULL, NULL)); if (!instanceIds || !nInstanceIds) { static const char delDevice[] = "DELETE FROM RD_DEVICE_LIST WHERE di=@deviceId"; int delDeviceSize = (int)sizeof(delDevice); VERIFY_SQLITE(sqlite3_prepare_v2(gRDDB, delDevice, delDeviceSize, &stmt, NULL)); VERIFY_SQLITE(sqlite3_bind_text(stmt, sqlite3_bind_parameter_index(stmt, "@deviceId"), deviceId, (int)strlen(deviceId), SQLITE_STATIC)); } else { static const char pre[] = "DELETE FROM RD_DEVICE_LINK_LIST " "WHERE ins IN (" "SELECT RD_DEVICE_LINK_LIST.ins FROM RD_DEVICE_LINK_LIST " "INNER JOIN RD_DEVICE_LIST ON RD_DEVICE_LINK_LIST.DEVICE_ID=RD_DEVICE_LIST.ID " "WHERE RD_DEVICE_LINK_LIST.ins IN ("; size_t inLen = nInstanceIds + (nInstanceIds - 1); static const char post[] = "))"; size_t delResourceSize = sizeof(pre) + inLen + (sizeof(post) - 1); delResource = OICCalloc(delResourceSize, 1); VERIFY_NON_NULL(delResource); OICStrcat(delResource, delResourceSize, pre); OICStrcat(delResource, delResourceSize, "?"); for (uint16_t i = 1; i < nInstanceIds; ++i) { OICStrcat(delResource, delResourceSize, ",?"); } OICStrcat(delResource, delResourceSize, post); VERIFY_SQLITE(sqlite3_prepare_v2(gRDDB, delResource, (int)delResourceSize, &stmt, NULL)); for (uint16_t i = 0; i < nInstanceIds; ++i) { VERIFY_SQLITE(sqlite3_bind_int64(stmt, 1 + i, instanceIds[i])); } } int res = sqlite3_step(stmt); if (SQLITE_DONE != res) { result = OC_STACK_ERROR; goto exit; } VERIFY_SQLITE(sqlite3_finalize(stmt)); stmt = NULL; VERIFY_SQLITE(sqlite3_exec(gRDDB, "COMMIT", NULL, NULL, NULL)); result = OC_STACK_OK; exit: OICFree(delResource); sqlite3_finalize(stmt); if (OC_STACK_OK != result) { sqlite3_exec(gRDDB, "ROLLBACK", NULL, NULL, NULL); } return result; } static OCStackResult DeleteExpiredResources() { sqlite3_stmt *stmt = NULL; OCStackResult result; uint64_t ttl = OICGetCurrentTime(TIME_IN_US); static const char lapsed[] = "SELECT di FROM RD_DEVICE_LIST WHERE ttl < @ttl"; int lapsedSize = (int)sizeof(lapsed); VERIFY_SQLITE(sqlite3_prepare_v2(gRDDB, lapsed, lapsedSize, &stmt, NULL)); VERIFY_SQLITE(sqlite3_bind_int64(stmt, sqlite3_bind_parameter_index(stmt, "@ttl"), (int64_t)ttl)); while (SQLITE_ROW == sqlite3_step(stmt)) { const unsigned char *di = sqlite3_column_text(stmt, 0); if (SQLITE_OK != deleteResources((const char *)di, NULL, 0)) { OIC_LOG_V(WARNING, TAG, "Error in deleteResources, Error Message: %s", sqlite3_errmsg(gRDDB)); } else { OIC_LOG_V(INFO, TAG, "Deleted resources with di=%s", di); } } VERIFY_SQLITE(sqlite3_finalize(stmt)); stmt = NULL; result = OC_STACK_OK; exit: sqlite3_finalize(stmt); return result; } OCStackResult OC_CALL OCRDDatabaseDiscoveryPayloadCreate(const char *interfaceType, const char *resourceType, OCDiscoveryPayload **payload) { return OCRDDatabaseDiscoveryPayloadCreateWithEp(interfaceType, resourceType, NULL, payload); } OCStackResult OC_CALL OCRDDatabaseDiscoveryPayloadCreateWithEp(const char *interfaceType, const char *resourceType, OCDevAddr *endpoint, OCDiscoveryPayload **payload) { OCStackResult result; OCDiscoveryPayload *head = NULL; OCDiscoveryPayload **tail = &head; sqlite3_stmt *stmt = NULL; if (*payload) { /* * This is an error of the caller, return here instead of touching the * caller provided payload. */ OIC_LOG_V(ERROR, TAG, "Payload is already allocated"); result = OC_STACK_INTERNAL_SERVER_ERROR; goto exit; } if (SQLITE_OK == sqlite3_config(SQLITE_CONFIG_LOG, errorCallback)) { OIC_LOG_V(INFO, TAG, "SQLite debugging log initialized."); } sqlite3_open_v2(OCRDDatabaseGetStorageFilename(), &gRDDB, SQLITE_OPEN_READWRITE, NULL); if (!gRDDB) { result = OC_STACK_ERROR; goto exit; } DeleteExpiredResources(); const char *serverID = OCGetServerInstanceIDString(); const char input[] = "SELECT di, external_host FROM RD_DEVICE_LIST"; int inputSize = (int)sizeof(input); const uint8_t di_index = 0; const uint8_t external_host_index = 1; VERIFY_SQLITE(sqlite3_prepare_v2(gRDDB, input, inputSize, &stmt, NULL)); while (SQLITE_ROW == sqlite3_step(stmt)) { const unsigned char *di = sqlite3_column_text(stmt, di_index); if (0 == strcmp((const char *)di, serverID)) { continue; } sqlite3_int64 externalHost = sqlite3_column_int64(stmt, external_host_index); *tail = OCDiscoveryPayloadCreate(); result = OC_STACK_INTERNAL_SERVER_ERROR; VERIFY_NON_NULL(*tail); (*tail)->sid = (char *)OICCalloc(1, UUID_STRING_SIZE); VERIFY_NON_NULL((*tail)->sid); memcpy((*tail)->sid, di, UUID_STRING_SIZE); result = CheckResources(interfaceType, resourceType, externalHost ? NULL : endpoint, *tail); if (OC_STACK_OK == result) { tail = &(*tail)->next; } else { OCPayloadDestroy((OCPayload *) *tail); *tail = NULL; } } result = head ? OC_STACK_OK : OC_STACK_NO_RESOURCE; exit: if (OC_STACK_OK != result) { OCPayloadDestroy((OCPayload *) head); head = NULL; } *payload = head; sqlite3_finalize(stmt); sqlite3_close(gRDDB); return result; } #endif
iotivity/iotivity
resource/csdk/stack/src/oicresourcedirectory.c
C
apache-2.0
21,540
/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * 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. * ***************************************************************/ #include "classad/common.h" #include "classad/source.h" #include "classad/matchClassad.h" using namespace std; static char const *ATTR_UNOPTIMIZED_REQUIREMENTS = "UnoptimizedRequirements"; namespace classad { MatchClassAd:: MatchClassAd() { lCtx = rCtx = NULL; lad = rad = NULL; ladParent = radParent = NULL; symmetric_match = NULL; right_matches_left = NULL; left_matches_right = NULL; InitMatchClassAd( NULL, NULL ); } MatchClassAd:: MatchClassAd( ClassAd *adl, ClassAd *adr ) : ClassAd() { lad = rad = lCtx = rCtx = NULL; ladParent = radParent = NULL; InitMatchClassAd( adl, adr ); } MatchClassAd:: ~MatchClassAd() { } MatchClassAd* MatchClassAd:: MakeMatchClassAd( ClassAd *adl, ClassAd *adr ) { return( new MatchClassAd( adl, adr ) ); } bool MatchClassAd:: InitMatchClassAd( ClassAd *adl, ClassAd *adr ) { ClassAdParser parser; // clear out old info Clear( ); lad = rad = NULL; lCtx = rCtx = NULL; // convenience expressions ClassAd *upd; if( !( upd = parser.ParseClassAd( "[symmetricMatch = RIGHT.requirements && LEFT.requirements ;" "leftMatchesRight = RIGHT.requirements ;" "rightMatchesLeft = LEFT.requirements ;" "leftRankValue = LEFT.rank ;" "rightRankValue = RIGHT.rank]" ) ) ) { Clear( ); lCtx = NULL; rCtx = NULL; return( false ); } Update( *upd ); delete upd; // In the following, global-scope references to LEFT and RIGHT // are used to make things slightly more efficient. That means // that this match ad should not be nested inside other ads. // Also for effiency, the left and right ads are actually // inserted as .LEFT and .RIGHT (ie at the top level) but // their parent scope is set to the lCtx and rCtx ads as // though they were inserted as lCtx.ad and rCtx.ad. This way, // the most direct way to reference the ads is through the // top-level global names .LEFT and .RIGHT. // the left context if( !( lCtx = parser.ParseClassAd( "[other=.RIGHT;target=.RIGHT;my=.LEFT;ad=.LEFT]" ) ) ) { Clear( ); lCtx = NULL; rCtx = NULL; return( false ); } // the right context if( !( rCtx = parser.ParseClassAd( "[other=.LEFT;target=.LEFT;my=.RIGHT;ad=.RIGHT]" ) ) ) { delete lCtx; lCtx = rCtx = NULL; return( false ); } // Insert the Ad resolver but also lookup before using b/c // there are no gaurentees not to collide. Insert( "lCtx", lCtx, false ); Insert( "rCtx", rCtx, false ); symmetric_match = Lookup("symmetricMatch"); right_matches_left = Lookup("rightMatchesLeft"); left_matches_right = Lookup("leftMatchesRight"); if( !adl ) { adl = new ClassAd(); } if( !adr ) { adr = new ClassAd(); } ReplaceLeftAd( adl ); ReplaceRightAd( adr ); return( true ); } bool MatchClassAd:: ReplaceLeftAd( ClassAd *ad ) { lad = ad; ladParent = ad ? ad->GetParentScope( ) : (ClassAd*)NULL; if( ad ) { if( !Insert( "LEFT", ad, false ) ) { lad = NULL; ladParent = NULL; Delete( "LEFT" ); return false; } // For the ability to efficiently reference the ad via // .LEFT, it is inserted in the top match ad, but we want // its parent scope to be the context ad. lCtx->SetParentScope(this); lad->SetParentScope(lCtx); } else { Delete( "LEFT" ); } return true; } bool MatchClassAd:: ReplaceRightAd( ClassAd *ad ) { rad = ad; radParent = ad ? ad->GetParentScope( ) : (ClassAd*)NULL; if( ad ) { if( !Insert( "RIGHT", ad , false ) ) { rad = NULL; radParent = NULL; Delete( "RIGHT" ); return false; } // For the ability to efficiently reference the ad via // .RIGHT, it is inserted in the top match ad, but we want // its parent scope to be the context ad. rCtx->SetParentScope(this); rad->SetParentScope(rCtx); } else { Delete( "RIGHT" ); } return true; } ClassAd *MatchClassAd:: GetLeftAd() { return( lad ); } ClassAd *MatchClassAd:: GetRightAd() { return( rad ); } ClassAd *MatchClassAd:: GetLeftContext( ) { return( lCtx ); } ClassAd *MatchClassAd:: GetRightContext( ) { return( rCtx ); } ClassAd *MatchClassAd:: RemoveLeftAd( ) { ClassAd *ad = lad; Remove( "LEFT" ); if( lad ) { lad->SetParentScope( ladParent ); } ladParent = NULL; lad = NULL; return( ad ); } ClassAd *MatchClassAd:: RemoveRightAd( ) { ClassAd *ad = rad; Remove( "RIGHT" ); if( rad ) { rad->SetParentScope( radParent ); } radParent = NULL; rad = NULL; return( ad ); } bool MatchClassAd:: OptimizeRightAdForMatchmaking( ClassAd *ad, std::string *error_msg ) { return MatchClassAd::OptimizeAdForMatchmaking( ad, true, error_msg ); } bool MatchClassAd:: OptimizeLeftAdForMatchmaking( ClassAd *ad, std::string *error_msg ) { return MatchClassAd::OptimizeAdForMatchmaking( ad, false, error_msg ); } bool MatchClassAd:: OptimizeAdForMatchmaking( ClassAd *ad, bool is_right, std::string *error_msg ) { if( ad->Lookup("my") || ad->Lookup("target") || ad->Lookup("other") || ad->Lookup(ATTR_UNOPTIMIZED_REQUIREMENTS) ) { if( error_msg ) { *error_msg = "Optimization of matchmaking requirements failed, because ad already contains one of my, target, other, or UnoptimizedRequirements."; } return false; } ExprTree *requirements = ad->Lookup(ATTR_REQUIREMENTS); if( !requirements ) { if( error_msg ) { *error_msg = "No requirements found in ad to be optimized."; } return false; } // insert "my" into this ad so that references that use it // can be flattened if ( !_useOldClassAdSemantics ) { Value me; ExprTree * pLit; me.SetClassAdValue( ad ); ad->Insert("my",(pLit=Literal::MakeLiteral(me))); } // insert "target" and "other" into this ad so references can be // _partially_ flattened to the more efficient .RIGHT or .LEFT char const *other = is_right ? "LEFT" : "RIGHT"; ExprTree *target = AttributeReference::MakeAttributeReference(NULL,other,true); ExprTree *t2 = AttributeReference::MakeAttributeReference(NULL,other,true); ad->Insert("target",target); ad->Insert("other",t2); ExprTree *flat_requirements = NULL; Value flat_val; if( ad->FlattenAndInline(requirements,flat_val,flat_requirements) ) { if( !flat_requirements ) { // flattened to a value flat_requirements = Literal::MakeLiteral(flat_val); } if( flat_requirements ) { // save original requirements ExprTree *orig_requirements = ad->Remove(ATTR_REQUIREMENTS); if( orig_requirements ) { if( !ad->Insert(ATTR_UNOPTIMIZED_REQUIREMENTS,orig_requirements) ) { // Now we have no requirements. Very bad! if( error_msg ) { *error_msg = "Failed to rename original requirements."; } delete orig_requirements; delete flat_requirements; return false; } } // insert new flattened requirements if( !ad->Insert(ATTR_REQUIREMENTS,flat_requirements) ) { if( error_msg ) { *error_msg = "Failed to insert optimized requirements."; } delete flat_requirements; return false; } } } // After flatenning, no references should remain to MY or TARGET. // Even if there are, those can be resolved by the context ads, so // we don't need to leave these attributes in the ad. if ( !_useOldClassAdSemantics ) { ad->Delete("my"); } ad->Delete("other"); ad->Delete("target"); return true; } bool MatchClassAd:: UnoptimizeAdForMatchmaking( ClassAd *ad ) { ExprTree *orig_requirements = ad->Remove(ATTR_UNOPTIMIZED_REQUIREMENTS); if( orig_requirements ) { if( !ad->Insert(ATTR_REQUIREMENTS,orig_requirements) ) { return false; } } return true; } bool MatchClassAd:: EvalMatchExpr(ExprTree *match_expr) { Value val; if( !match_expr ) { return false; } if( EvaluateExpr( match_expr, val ) ) { bool result = false; if( val.IsBooleanValueEquiv( result ) ) { return result; } long long int_result = 0; if( val.IsIntegerValue( int_result ) ) { return int_result != 0; } } return false; } bool MatchClassAd:: symmetricMatch() { return EvalMatchExpr( symmetric_match ); } bool MatchClassAd:: rightMatchesLeft() { return EvalMatchExpr( right_matches_left ); } bool MatchClassAd:: leftMatchesRight() { return EvalMatchExpr( left_matches_right ); } } // classad
neurodebian/htcondor
src/classad/matchClassad.cpp
C++
apache-2.0
8,943
<?php /* Smarty version 2.6.18, created on 2013-11-03 20:07:53 compiled from tpls/v_30/footer.html */ ?> <?php if (! $this->_tpl_vars['ismap']): ?><div class="body_footer" style="position:fixed;"><ul> <li><a title="返回首页" href="<?php echo $this->_tpl_vars['homeurl']; ?> "><dl> <dt><img alt="返回首页" src="smarty/templates/tpls/<?php echo $this->_tpl_vars['site']['template']; ?> /icon_1.png"></dt> <dd>返回首页</dd> </dl></a></li> <li><a title="地图" href="?token=<?php echo $this->_tpl_vars['token']; ?> &m=site&c=home&a=map" rel="external"><dl> <dt><img alt="地图" src="smarty/templates/tpls/<?php echo $this->_tpl_vars['site']['template']; ?> /icon_3.png"></dt> <dd>网站地图</dd> </dl></a></li> <li><a title="热线电话" href="tel:<?php echo $this->_tpl_vars['company']['tel']; ?> "><dl> <dt><img alt="热线电话" src="smarty/templates/tpls/<?php echo $this->_tpl_vars['site']['template']; ?> /icon_4.png"></dt> <dd>热线电话</dd> </dl></a></li> <li><a title="发短信" href="sms:<?php echo $this->_tpl_vars['company']['mp']; ?> " data-ajax="false"><dl> <dt><img alt="发短信" src="smarty/templates/tpls/<?php echo $this->_tpl_vars['site']['template']; ?> /icon_5.png"></dt> <dd>发短信</dd> </dl></a></li> </ul></div></div></div></div> <!--menu start--> <?php if ($this->_tpl_vars['showPlugMenu']): ?> <link rel="stylesheet" href="/tpl/Wap/default/common/css/flash/css/plugmenu.css"> <div class="plug-div"> <div class="plug-phone"> <div class="plug-menu themeStyle" style="background:<?php echo $this->_tpl_vars['site']['plugmenucolor']; ?> "><span class="close"></span></div> <?php $_from = $this->_tpl_vars['plugmenus']; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array'); }if (count($_from)): foreach ($_from as $this->_tpl_vars['k'] => $this->_tpl_vars['vo']): ?> <div class="themeStyle plug-btn plug-btn<?php echo $this->_tpl_vars['k']+1; ?> close" style="background:<?php echo $this->_tpl_vars['site']['plugmenucolor']; ?> "> <a href="<?php echo $this->_tpl_vars['vo']['url']; ?> "> <span style="background-image: url(/tpl/Wap/default/common/css/flash/images/img/<?php echo $this->_tpl_vars['vo']['name']; ?> .png);" ></span> </a> </div> <?php endforeach; endif; unset($_from); ?> <div class="plug-btn plug-btn5 close"></div> </div> </div> <script src="/tpl/Wap/default/common/css/flash/js/zepto.min.js" type="text/javascript"></script> <script src="/tpl/Wap/default/common/css/flash/js/plugmenu.js" type="text/javascript"></script> <?php endif; ?> <!--menu end--> </body><script type="text/javascript"> <?php echo ' window.onload = function () { initUserStyleData(); modifyAllImage(); }'; ?> </script></html><?php endif; ?>
royalwang/saivi
cms/smarty/templates_c/%%F3/F31/F310BC85%%footer.html.php
PHP
apache-2.0
2,992
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.river.test.spec.jeri.connection; import java.util.logging.Level; //harness related imports import org.apache.river.qa.harness.TestException; //utility classes import org.apache.river.test.spec.jeri.connection.util.AbstractConnectionTest; import org.apache.river.test.spec.jeri.connection.util.ConnectionTransportListener; import org.apache.river.test.spec.jeri.connection.util.ListenOperation; import org.apache.river.test.spec.jeri.connection.util.TestEndpoint; import org.apache.river.test.spec.jeri.connection.util.TestServerEndpoint; import org.apache.river.test.spec.jeri.connection.util.TestService; import org.apache.river.test.spec.jeri.connection.util.TestServiceImpl; import org.apache.river.test.spec.jeri.connection.util.TransportListener; //jeri imports import net.jini.jeri.BasicILFactory; import net.jini.jeri.BasicJeriExporter; import net.jini.jeri.connection.ConnectionManager; //java.util import java.util.HashMap; /** * The purpose of this test is to verify the following behavior of * <code>net.jini.jeri.connection.ConnectionManager</code>: * 1. The <code>connect</code> method on the <code>ConnectionEnpoint</code> * passed in to the constructor is called when * <code>ConnectionManager.newRequest</code> is called * 2. The <code>connect</code> method that takes active and idle connections * is called first on <code>ConnectionEndpoint</code> and only if that * method returns null is the single-argument <code>connect</code> method * called. * 3. If a <code>Connection</code> is returned by the * <code>ConnectionEndpoint</code>, the <code>writeRequestData</code> * method is invoked on that connection passing in the * <code>OutboundRequestHandle</code> used in the * <code>ConnectionManager.newRequest</code> call * 4. An exception thrown by <code>ConnectionEndpoint.connect</code> or * <code>Connection.writeRequestData</code> is returned to the caller of * <code>ConnectionManager.newRequest</code> * 5. <code>Connection.readResponseData</code> is called before any * data is read from the <code>OutboundRequest</code> response input * stream * 6. Calls to <code>populateContext</code> and * <code>getUnfulfilledConstraints</code> are delegated to the * <code>Connection</code> associated with the * <code>OutboundRequestHandle</code> * * Test Design: * 1. Construct a connection manager passing in an instrumented * <code>ConnectionEndpoint</code> implementation. * 2. Call <code>newRequest</code> on the connection manager created in * step 1. * 3. Verify that the <code>connect</code> method that takes active and * idle connections is called. * 4. In the instrumented endpoint return a connection object. * 5. Verify that the single argument <code>connect</code> method is not * called. * 6. Construct a second connection manager. * 7. In the instrumented endpoint return null from the first call to * <code>connect</code>. * 8. Verify that the single-argument <code>connect</code> method is * called on the instrumented connection endpoint. * 9. Call <code>newRequest</code> again and throw an exception in the * instrumented connection endpoint. * 10. Verfiy that the exception is propagated to the called of * <code>ConnectionManager.newRequest</code>. * 11. Extract an outbound request instance from the iterator returned by * the connection manager constructed in step 1. * 12. Make a request over the outbound request. * 13. Verify that <code>Connection.writeRequestData</code> is called. * 14. Make a second call. * 15. This time, inside the instrumented connection object, throw an * exception. * 16. Verify that the exception is propagated to the caller of * <code>ConnectionManager.newRequest</code>. * 17. Make a third call that returns data from the server side of the * connection. * 18. Verify that <code>Connection.readResponseData</code> is called and * that the data in the stream is intact; i.e. no data has been read. * 19. Call <code>populateContext</code> and * <code>getUnfulfilledConstraints>/code> on the outbound request. * 20. Verify that the corresponding methods are called on the instrumented * connection. * * Additional Utilities: * 1. Instrumented connection endpoint implementation */ public class ConnectionManagerTest extends AbstractConnectionTest implements TransportListener { //Method calls checked by this test private HashMap methodCalls = new HashMap(); private static final String connect1 = "connect1"; private static final String connect2 = "connect2"; private static final String populateContext = "populateContext"; private static final String getUnfulfilledConstraints = "getUnfulfilledConstraints"; private static final String readResponseData = "readResponseData"; private static final String writeRequestData = "writeRequestData"; private static final String[] methodNames = new String[]{connect1, connect2, populateContext, getUnfulfilledConstraints, readResponseData, writeRequestData}; //inherit javadoc public void run() throws Exception { //Register for instrumentation calls from the transport ConnectionTransportListener.registerListener(this); //initiate a listen operation TestServerEndpoint tse = new TestServerEndpoint(getListenPort()); BasicJeriExporter exporter = new BasicJeriExporter(tse, new BasicILFactory()); TestServiceImpl service = new TestServiceImpl(); TestService stub = (TestService) exporter.export(service); TestEndpoint te = tse.getTestEndpoint(); //make a call stub.doSomething(); //Verify that the 3-arg connect method is called if (methodCalls.get(connect2)==null) { throw new TestException("The ConnectionManager" + " did not call 3-arg connect on the ConnectionEndpoint"); } //Verify that the 1-arg connect method is called if (methodCalls.get(connect1)==null) { throw new TestException("The ConnectionManager" + " did not call 1-arg connect on the ConnectionEndpoint"); } //Verify that writeRequestData is called if (methodCalls.get(writeRequestData)==null) { throw new TestException("The ConnectionManager" + " did not call writeRequestData on the Connection"); } //Verify that readResponseData is called if (methodCalls.get(readResponseData)==null) { throw new TestException("The ConnectionManager" + " did not call readResponseData on the Connection"); } //Verify that populateContext is called if (methodCalls.get(populateContext)==null) { throw new TestException("The ConnectionManager" + " did not call populateContext on the Connection"); } //Verify that getUnfulfilledConstraints is called if (methodCalls.get(getUnfulfilledConstraints)==null) { throw new TestException("The ConnectionManager" + " did not call getUnfulfilledConstraints on the" + " Connection"); } //Verify that the single-arg connect is not called if the 3-arg //connect is called clearMethodCalls(); stub.doSomething(); //Verify that the 3-arg connect method is called if (methodCalls.get(connect2)==null) { throw new TestException("The ConnectionManager" + " did not call 3-arg connect on the ConnectionEndpoint"); } //Verify that the single-arg connect method is not called if (methodCalls.get(connect1)!=null) { throw new TestException("The ConnectionManager called" + " 1-arg connect even though a connection was returned on" + " call to 3-arg connect"); } //Check exceptions clearMethodCalls(); te.setException("connect"); boolean exceptionThrown = false; try { stub.doSomething(); } catch (Exception e) { if (e.getMessage().equals("Bogus Exception")) { exceptionThrown = true; } else { e.printStackTrace(); } } if (!exceptionThrown) { throw new TestException("The ConnectionManager" + " does not propagate an exception thrown in" + " ConnectionEndpoint.connect"); } clearMethodCalls(); te.setException("writeRequestData"); exceptionThrown = false; try { stub.doSomething(); } catch (Exception e) { if (e.getMessage().equals("Bogus Exception")) { exceptionThrown = true; } else { e.printStackTrace(); } } if (!exceptionThrown) { throw new TestException("The ConnectionManager" + " does not propagate an exception thrown in" + " Connection.writeRequestData"); } } //inherit javadoc public synchronized void called (String methodName) { for (int i=0;i<methodNames.length;i++) { if (methodNames[i].equals(methodName)) { methodCalls.put(methodNames[i],methodName); } } } /** * Clears the methodNames hashmap. */ private synchronized void clearMethodCalls() { methodCalls = new HashMap(); } }
pfirmstone/JGDMS
qa/src/org/apache/river/test/spec/jeri/connection/ConnectionManagerTest.java
Java
apache-2.0
10,551
import {Component,OnInit} from '@angular/core'; import {ROUTER_DIRECTIVES} from '@angular/router'; import {HTTP_PROVIDERS} from '@angular/http'; import {DataTable} from '../../../components/datatable/datatable'; import {CodeHighlighter} from '../../../components/codehighlighter/codehighlighter'; import {TabView} from '../../../components/tabview/tabview'; import {TabPanel} from '../../../components/tabview/tabpanel'; import {Car} from '../domain/car'; import {Column} from '../../../components/column/column'; import {DataTableSubmenu} from './datatablesubmenu.component'; import {CarService} from '../service/carservice'; @Component({ templateUrl: 'showcase/demo/datatable/datatablecolresizedemo.html', directives: [DataTable,Column,DataTableSubmenu,TabPanel,TabView,CodeHighlighter,ROUTER_DIRECTIVES], providers: [HTTP_PROVIDERS,CarService] }) export class DataTableColResizeDemo implements OnInit { cars: Car[]; constructor(private carService: CarService) { } ngOnInit() { this.carService.getCarsSmall().then(cars => this.cars = cars); } }
AjaySharm/primeng
showcase/demo/datatable/datatablecolresizedemo.ts
TypeScript
apache-2.0
1,089
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="de"> <head> <!-- Generated by javadoc (version 1.7.0_06) on Sun Oct 14 20:05:14 CEST 2012 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>org.togglz.servlet.user (Togglz 1.1.0.Final API)</title> <meta name="date" content="2012-10-14"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="org.togglz.servlet.user (Togglz 1.1.0.Final 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 class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-use.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../org/togglz/servlet/spi/package-summary.html">Prev Package</a></li> <li><a href="../../../../org/togglz/servlet/util/package-summary.html">Next Package</a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/togglz/servlet/user/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.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 title="Package" class="title">Package&nbsp;org.togglz.servlet.user</h1> </div> <div class="contentContainer"> <ul class="blockList"> <li class="blockList"> <table class="packageSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation"> <caption><span>Class Summary</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Class</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="../../../../org/togglz/servlet/user/ServletUserProvider.html" title="class in org.togglz.servlet.user">ServletUserProvider</a></td> <td class="colLast"> <div class="block">Implementation of <a href="../../../../org/togglz/core/user/UserProvider.html" title="interface in org.togglz.core.user"><code>UserProvider</code></a> that uses <a href="http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html?is-external=true#getUserPrincipal()" title="class or interface in javax.servlet.http"><code>HttpServletRequest.getUserPrincipal()</code></a> to obtain the user.</div> </td> </tr> </tbody> </table> </li> </ul> </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 class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-use.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../org/togglz/servlet/spi/package-summary.html">Prev Package</a></li> <li><a href="../../../../org/togglz/servlet/util/package-summary.html">Next Package</a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/togglz/servlet/user/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.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; 2012. All Rights Reserved.</small></p> </body> </html>
togglz/togglz-site
apidocs/1.1.0.Final/org/togglz/servlet/user/package-summary.html
HTML
apache-2.0
5,247
package daemon import ( "fmt" "io" "io/ioutil" "os" "path" "regexp" "runtime" "strings" "sync" "time" "github.com/docker/libcontainer/label" "github.com/docker/docker/archive" "github.com/docker/docker/daemon/execdriver" "github.com/docker/docker/daemon/execdriver/execdrivers" "github.com/docker/docker/daemon/execdriver/lxc" "github.com/docker/docker/daemon/graphdriver" _ "github.com/docker/docker/daemon/graphdriver/vfs" _ "github.com/docker/docker/daemon/networkdriver/bridge" "github.com/docker/docker/daemon/networkdriver/portallocator" "github.com/docker/docker/dockerversion" "github.com/docker/docker/engine" "github.com/docker/docker/graph" "github.com/docker/docker/image" "github.com/docker/docker/pkg/broadcastwriter" "github.com/docker/docker/pkg/graphdb" "github.com/docker/docker/pkg/log" "github.com/docker/docker/pkg/namesgenerator" "github.com/docker/docker/pkg/networkfs/resolvconf" "github.com/docker/docker/pkg/parsers" "github.com/docker/docker/pkg/parsers/kernel" "github.com/docker/docker/pkg/sysinfo" "github.com/docker/docker/pkg/truncindex" "github.com/docker/docker/runconfig" "github.com/docker/docker/utils" ) var ( DefaultDns = []string{"8.8.8.8", "8.8.4.4"} validContainerNameChars = `[a-zA-Z0-9_.-]` validContainerNamePattern = regexp.MustCompile(`^/?` + validContainerNameChars + `+$`) ) type contStore struct { s map[string]*Container sync.Mutex } func (c *contStore) Add(id string, cont *Container) { c.Lock() c.s[id] = cont c.Unlock() } func (c *contStore) Get(id string) *Container { c.Lock() res := c.s[id] c.Unlock() return res } func (c *contStore) Delete(id string) { c.Lock() delete(c.s, id) c.Unlock() } func (c *contStore) List() []*Container { containers := new(History) c.Lock() for _, cont := range c.s { containers.Add(cont) } c.Unlock() containers.Sort() return *containers } type Daemon struct { repository string sysInitPath string containers *contStore graph *graph.Graph repositories *graph.TagStore idIndex *truncindex.TruncIndex sysInfo *sysinfo.SysInfo volumes *graph.Graph eng *engine.Engine config *Config containerGraph *graphdb.Database driver graphdriver.Driver execDriver execdriver.Driver } // Install installs daemon capabilities to eng. func (daemon *Daemon) Install(eng *engine.Engine) error { // FIXME: rename "delete" to "rm" for consistency with the CLI command // FIXME: rename ContainerDestroy to ContainerRm for consistency with the CLI command // FIXME: remove ImageDelete's dependency on Daemon, then move to graph/ for name, method := range map[string]engine.Handler{ "attach": daemon.ContainerAttach, "build": daemon.CmdBuild, "commit": daemon.ContainerCommit, "container_changes": daemon.ContainerChanges, "container_copy": daemon.ContainerCopy, "container_inspect": daemon.ContainerInspect, "containers": daemon.Containers, "create": daemon.ContainerCreate, "delete": daemon.ContainerDestroy, "export": daemon.ContainerExport, "info": daemon.CmdInfo, "kill": daemon.ContainerKill, "logs": daemon.ContainerLogs, "pause": daemon.ContainerPause, "resize": daemon.ContainerResize, "restart": daemon.ContainerRestart, "start": daemon.ContainerStart, "stop": daemon.ContainerStop, "top": daemon.ContainerTop, "unpause": daemon.ContainerUnpause, "wait": daemon.ContainerWait, "image_delete": daemon.ImageDelete, // FIXME: see above } { if err := eng.Register(name, method); err != nil { return err } } if err := daemon.Repositories().Install(eng); err != nil { return err } // FIXME: this hack is necessary for legacy integration tests to access // the daemon object. eng.Hack_SetGlobalVar("httpapi.daemon", daemon) return nil } // Get looks for a container by the specified ID or name, and returns it. // If the container is not found, or if an error occurs, nil is returned. func (daemon *Daemon) Get(name string) *Container { if id, err := daemon.idIndex.Get(name); err == nil { return daemon.containers.Get(id) } if c, _ := daemon.GetByName(name); c != nil { return c } return nil } // Exists returns a true if a container of the specified ID or name exists, // false otherwise. func (daemon *Daemon) Exists(id string) bool { return daemon.Get(id) != nil } func (daemon *Daemon) containerRoot(id string) string { return path.Join(daemon.repository, id) } // Load reads the contents of a container from disk // This is typically done at startup. func (daemon *Daemon) load(id string) (*Container, error) { container := &Container{root: daemon.containerRoot(id), State: NewState()} if err := container.FromDisk(); err != nil { return nil, err } if container.ID != id { return container, fmt.Errorf("Container %s is stored at %s", container.ID, id) } container.readHostConfig() return container, nil } // Register makes a container object usable by the daemon as <container.ID> // This is a wrapper for register func (daemon *Daemon) Register(container *Container) error { return daemon.register(container, true) } // register makes a container object usable by the daemon as <container.ID> func (daemon *Daemon) register(container *Container, updateSuffixarray bool) error { if container.daemon != nil || daemon.Exists(container.ID) { return fmt.Errorf("Container is already loaded") } if err := validateID(container.ID); err != nil { return err } if err := daemon.ensureName(container); err != nil { return err } container.daemon = daemon // Attach to stdout and stderr container.stderr = broadcastwriter.New() container.stdout = broadcastwriter.New() // Attach to stdin if container.Config.OpenStdin { container.stdin, container.stdinPipe = io.Pipe() } else { container.stdinPipe = utils.NopWriteCloser(ioutil.Discard) // Silently drop stdin } // done daemon.containers.Add(container.ID, container) // don't update the Suffixarray if we're starting up // we'll waste time if we update it for every container daemon.idIndex.Add(container.ID) // FIXME: if the container is supposed to be running but is not, auto restart it? // if so, then we need to restart monitor and init a new lock // If the container is supposed to be running, make sure of it if container.State.IsRunning() { log.Debugf("killing old running container %s", container.ID) existingPid := container.State.Pid container.State.SetStopped(0) // We only have to handle this for lxc because the other drivers will ensure that // no processes are left when docker dies if container.ExecDriver == "" || strings.Contains(container.ExecDriver, "lxc") { lxc.KillLxc(container.ID, 9) } else { // use the current driver and ensure that the container is dead x.x cmd := &execdriver.Command{ ID: container.ID, } var err error cmd.Process, err = os.FindProcess(existingPid) if err != nil { log.Debugf("cannot find existing process for %d", existingPid) } daemon.execDriver.Terminate(cmd) } if err := container.Unmount(); err != nil { log.Debugf("unmount error %s", err) } if err := container.ToDisk(); err != nil { log.Debugf("saving stopped state to disk %s", err) } info := daemon.execDriver.Info(container.ID) if !info.IsRunning() { log.Debugf("Container %s was supposed to be running but is not.", container.ID) log.Debugf("Marking as stopped") container.State.SetStopped(-127) if err := container.ToDisk(); err != nil { return err } } } return nil } func (daemon *Daemon) ensureName(container *Container) error { if container.Name == "" { name, err := daemon.generateNewName(container.ID) if err != nil { return err } container.Name = name if err := container.ToDisk(); err != nil { log.Debugf("Error saving container name %s", err) } } return nil } func (daemon *Daemon) LogToDisk(src *broadcastwriter.BroadcastWriter, dst, stream string) error { log, err := os.OpenFile(dst, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0600) if err != nil { return err } src.AddWriter(log, stream) return nil } func (daemon *Daemon) restore() error { var ( debug = (os.Getenv("DEBUG") != "" || os.Getenv("TEST") != "") containers = make(map[string]*Container) currentDriver = daemon.driver.String() ) if !debug { log.Infof("Loading containers: ") } dir, err := ioutil.ReadDir(daemon.repository) if err != nil { return err } for _, v := range dir { id := v.Name() container, err := daemon.load(id) if !debug { fmt.Print(".") } if err != nil { log.Errorf("Failed to load container %v: %v", id, err) continue } // Ignore the container if it does not support the current driver being used by the graph if (container.Driver == "" && currentDriver == "aufs") || container.Driver == currentDriver { log.Debugf("Loaded container %v", container.ID) containers[container.ID] = container } else { log.Debugf("Cannot load container %s because it was created with another graph driver.", container.ID) } } registeredContainers := []*Container{} if entities := daemon.containerGraph.List("/", -1); entities != nil { for _, p := range entities.Paths() { if !debug { fmt.Print(".") } e := entities[p] if container, ok := containers[e.ID()]; ok { if err := daemon.register(container, false); err != nil { log.Debugf("Failed to register container %s: %s", container.ID, err) } registeredContainers = append(registeredContainers, container) // delete from the map so that a new name is not automatically generated delete(containers, e.ID()) } } } // Any containers that are left over do not exist in the graph for _, container := range containers { // Try to set the default name for a container if it exists prior to links container.Name, err = daemon.generateNewName(container.ID) if err != nil { log.Debugf("Setting default id - %s", err) } if err := daemon.register(container, false); err != nil { log.Debugf("Failed to register container %s: %s", container.ID, err) } registeredContainers = append(registeredContainers, container) } // check the restart policy on the containers and restart any container with // the restart policy of "always" if daemon.config.AutoRestart { log.Debugf("Restarting containers...") for _, container := range registeredContainers { if container.hostConfig.RestartPolicy.Name == "always" || (container.hostConfig.RestartPolicy.Name == "on-failure" && container.State.ExitCode != 0) { log.Debugf("Starting container %s", container.ID) if err := container.Start(); err != nil { log.Debugf("Failed to start container %s: %s", container.ID, err) } } } } if !debug { log.Infof(": done.") } return nil } func (daemon *Daemon) checkDeprecatedExpose(config *runconfig.Config) bool { if config != nil { if config.PortSpecs != nil { for _, p := range config.PortSpecs { if strings.Contains(p, ":") { return true } } } } return false } func (daemon *Daemon) mergeAndVerifyConfig(config *runconfig.Config, img *image.Image) ([]string, error) { warnings := []string{} if daemon.checkDeprecatedExpose(img.Config) || daemon.checkDeprecatedExpose(config) { warnings = append(warnings, "The mapping to public ports on your host via Dockerfile EXPOSE (host:port:port) has been deprecated. Use -p to publish the ports.") } if img.Config != nil { if err := runconfig.Merge(config, img.Config); err != nil { return nil, err } } if len(config.Entrypoint) == 0 && len(config.Cmd) == 0 { return nil, fmt.Errorf("No command specified") } return warnings, nil } func (daemon *Daemon) generateIdAndName(name string) (string, string, error) { var ( err error id = utils.GenerateRandomID() ) if name == "" { if name, err = daemon.generateNewName(id); err != nil { return "", "", err } return id, name, nil } if name, err = daemon.reserveName(id, name); err != nil { return "", "", err } return id, name, nil } func (daemon *Daemon) reserveName(id, name string) (string, error) { if !validContainerNamePattern.MatchString(name) { return "", fmt.Errorf("Invalid container name (%s), only %s are allowed", name, validContainerNameChars) } if name[0] != '/' { name = "/" + name } if _, err := daemon.containerGraph.Set(name, id); err != nil { if !graphdb.IsNonUniqueNameError(err) { return "", err } conflictingContainer, err := daemon.GetByName(name) if err != nil { if strings.Contains(err.Error(), "Could not find entity") { return "", err } // Remove name and continue starting the container if err := daemon.containerGraph.Delete(name); err != nil { return "", err } } else { nameAsKnownByUser := strings.TrimPrefix(name, "/") return "", fmt.Errorf( "Conflict, The name %s is already assigned to %s. You have to delete (or rename) that container to be able to assign %s to a container again.", nameAsKnownByUser, utils.TruncateID(conflictingContainer.ID), nameAsKnownByUser) } } return name, nil } func (daemon *Daemon) generateNewName(id string) (string, error) { var name string for i := 0; i < 6; i++ { name = namesgenerator.GetRandomName(i) if name[0] != '/' { name = "/" + name } if _, err := daemon.containerGraph.Set(name, id); err != nil { if !graphdb.IsNonUniqueNameError(err) { return "", err } continue } return name, nil } name = "/" + utils.TruncateID(id) if _, err := daemon.containerGraph.Set(name, id); err != nil { return "", err } return name, nil } func (daemon *Daemon) generateHostname(id string, config *runconfig.Config) { // Generate default hostname // FIXME: the lxc template no longer needs to set a default hostname if config.Hostname == "" { config.Hostname = id[:12] } } func (daemon *Daemon) getEntrypointAndArgs(config *runconfig.Config) (string, []string) { var ( entrypoint string args []string ) if len(config.Entrypoint) != 0 { entrypoint = config.Entrypoint[0] args = append(config.Entrypoint[1:], config.Cmd...) } else { entrypoint = config.Cmd[0] args = config.Cmd[1:] } return entrypoint, args } func (daemon *Daemon) newContainer(name string, config *runconfig.Config, img *image.Image) (*Container, error) { var ( id string err error ) id, name, err = daemon.generateIdAndName(name) if err != nil { return nil, err } daemon.generateHostname(id, config) entrypoint, args := daemon.getEntrypointAndArgs(config) container := &Container{ // FIXME: we should generate the ID here instead of receiving it as an argument ID: id, Created: time.Now().UTC(), Path: entrypoint, Args: args, //FIXME: de-duplicate from config Config: config, hostConfig: &runconfig.HostConfig{}, Image: img.ID, // Always use the resolved image id NetworkSettings: &NetworkSettings{}, Name: name, Driver: daemon.driver.String(), ExecDriver: daemon.execDriver.Name(), State: NewState(), } container.root = daemon.containerRoot(container.ID) if container.ProcessLabel, container.MountLabel, err = label.GenLabels(""); err != nil { return nil, err } return container, nil } func (daemon *Daemon) createRootfs(container *Container, img *image.Image) error { // Step 1: create the container directory. // This doubles as a barrier to avoid race conditions. if err := os.Mkdir(container.root, 0700); err != nil { return err } initID := fmt.Sprintf("%s-init", container.ID) if err := daemon.driver.Create(initID, img.ID); err != nil { return err } initPath, err := daemon.driver.Get(initID, "") if err != nil { return err } defer daemon.driver.Put(initID) if err := graph.SetupInitLayer(initPath); err != nil { return err } if err := daemon.driver.Create(container.ID, initID); err != nil { return err } return nil } func GetFullContainerName(name string) (string, error) { if name == "" { return "", fmt.Errorf("Container name cannot be empty") } if name[0] != '/' { name = "/" + name } return name, nil } func (daemon *Daemon) GetByName(name string) (*Container, error) { fullName, err := GetFullContainerName(name) if err != nil { return nil, err } entity := daemon.containerGraph.Get(fullName) if entity == nil { return nil, fmt.Errorf("Could not find entity for %s", name) } e := daemon.containers.Get(entity.ID()) if e == nil { return nil, fmt.Errorf("Could not find container for entity id %s", entity.ID()) } return e, nil } func (daemon *Daemon) Children(name string) (map[string]*Container, error) { name, err := GetFullContainerName(name) if err != nil { return nil, err } children := make(map[string]*Container) err = daemon.containerGraph.Walk(name, func(p string, e *graphdb.Entity) error { c := daemon.Get(e.ID()) if c == nil { return fmt.Errorf("Could not get container for name %s and id %s", e.ID(), p) } children[p] = c return nil }, 0) if err != nil { return nil, err } return children, nil } func (daemon *Daemon) RegisterLink(parent, child *Container, alias string) error { fullName := path.Join(parent.Name, alias) if !daemon.containerGraph.Exists(fullName) { _, err := daemon.containerGraph.Set(fullName, child.ID) return err } return nil } func (daemon *Daemon) RegisterLinks(container *Container, hostConfig *runconfig.HostConfig) error { if hostConfig != nil && hostConfig.Links != nil { for _, l := range hostConfig.Links { parts, err := parsers.PartParser("name:alias", l) if err != nil { return err } child, err := daemon.GetByName(parts["name"]) if err != nil { return err } if child == nil { return fmt.Errorf("Could not get container for %s", parts["name"]) } if err := daemon.RegisterLink(container, child, parts["alias"]); err != nil { return err } } // After we load all the links into the daemon // set them to nil on the hostconfig hostConfig.Links = nil if err := container.WriteHostConfig(); err != nil { return err } } return nil } // FIXME: harmonize with NewGraph() func NewDaemon(config *Config, eng *engine.Engine) (*Daemon, error) { daemon, err := NewDaemonFromDirectory(config, eng) if err != nil { return nil, err } return daemon, nil } func NewDaemonFromDirectory(config *Config, eng *engine.Engine) (*Daemon, error) { // Apply configuration defaults if config.Mtu == 0 { // FIXME: GetDefaultNetwork Mtu doesn't need to be public anymore config.Mtu = GetDefaultNetworkMtu() } // Check for mutually incompatible config options if config.BridgeIface != "" && config.BridgeIP != "" { return nil, fmt.Errorf("You specified -b & --bip, mutually exclusive options. Please specify only one.") } if !config.EnableIptables && !config.InterContainerCommunication { return nil, fmt.Errorf("You specified --iptables=false with --icc=false. ICC uses iptables to function. Please set --icc or --iptables to true.") } // FIXME: DisableNetworkBidge doesn't need to be public anymore config.DisableNetwork = config.BridgeIface == DisableNetworkBridge // Claim the pidfile first, to avoid any and all unexpected race conditions. // Some of the init doesn't need a pidfile lock - but let's not try to be smart. if config.Pidfile != "" { if err := utils.CreatePidFile(config.Pidfile); err != nil { return nil, err } eng.OnShutdown(func() { // Always release the pidfile last, just in case utils.RemovePidFile(config.Pidfile) }) } // Check that the system is supported and we have sufficient privileges // FIXME: return errors instead of calling Fatal if runtime.GOOS != "linux" { log.Fatalf("The Docker daemon is only supported on linux") } if os.Geteuid() != 0 { log.Fatalf("The Docker daemon needs to be run as root") } if err := checkKernelAndArch(); err != nil { log.Fatalf(err.Error()) } // set up the TempDir to use a canonical path tmp, err := utils.TempDir(config.Root) if err != nil { log.Fatalf("Unable to get the TempDir under %s: %s", config.Root, err) } realTmp, err := utils.ReadSymlinkedDirectory(tmp) if err != nil { log.Fatalf("Unable to get the full path to the TempDir (%s): %s", tmp, err) } os.Setenv("TMPDIR", realTmp) if !config.EnableSelinuxSupport { selinuxSetDisabled() } // get the canonical path to the Docker root directory var realRoot string if _, err := os.Stat(config.Root); err != nil && os.IsNotExist(err) { realRoot = config.Root } else { realRoot, err = utils.ReadSymlinkedDirectory(config.Root) if err != nil { log.Fatalf("Unable to get the full path to root (%s): %s", config.Root, err) } } config.Root = realRoot // Create the root directory if it doesn't exists if err := os.MkdirAll(config.Root, 0700); err != nil && !os.IsExist(err) { return nil, err } // Set the default driver graphdriver.DefaultDriver = config.GraphDriver // Load storage driver driver, err := graphdriver.New(config.Root, config.GraphOptions) if err != nil { return nil, err } log.Debugf("Using graph driver %s", driver) // As Docker on btrfs and SELinux are incompatible at present, error on both being enabled if config.EnableSelinuxSupport && driver.String() == "btrfs" { return nil, fmt.Errorf("SELinux is not supported with the BTRFS graph driver!") } daemonRepo := path.Join(config.Root, "containers") if err := os.MkdirAll(daemonRepo, 0700); err != nil && !os.IsExist(err) { return nil, err } // Migrate the container if it is aufs and aufs is enabled if err = migrateIfAufs(driver, config.Root); err != nil { return nil, err } log.Debugf("Creating images graph") g, err := graph.NewGraph(path.Join(config.Root, "graph"), driver) if err != nil { return nil, err } // We don't want to use a complex driver like aufs or devmapper // for volumes, just a plain filesystem volumesDriver, err := graphdriver.GetDriver("vfs", config.Root, config.GraphOptions) if err != nil { return nil, err } log.Debugf("Creating volumes graph") volumes, err := graph.NewGraph(path.Join(config.Root, "volumes"), volumesDriver) if err != nil { return nil, err } log.Debugf("Creating repository list") repositories, err := graph.NewTagStore(path.Join(config.Root, "repositories-"+driver.String()), g) if err != nil { return nil, fmt.Errorf("Couldn't create Tag store: %s", err) } if !config.DisableNetwork { job := eng.Job("init_networkdriver") job.SetenvBool("EnableIptables", config.EnableIptables) job.SetenvBool("InterContainerCommunication", config.InterContainerCommunication) job.SetenvBool("EnableIpForward", config.EnableIpForward) job.Setenv("BridgeIface", config.BridgeIface) job.Setenv("BridgeIP", config.BridgeIP) job.Setenv("DefaultBindingIP", config.DefaultIp.String()) if err := job.Run(); err != nil { return nil, err } } graphdbPath := path.Join(config.Root, "linkgraph.db") graph, err := graphdb.NewSqliteConn(graphdbPath) if err != nil { return nil, err } localCopy := path.Join(config.Root, "init", fmt.Sprintf("dockerinit-%s", dockerversion.VERSION)) sysInitPath := utils.DockerInitPath(localCopy) if sysInitPath == "" { return nil, fmt.Errorf("Could not locate dockerinit: This usually means docker was built incorrectly. See http://docs.docker.com/contributing/devenvironment for official build instructions.") } if sysInitPath != localCopy { // When we find a suitable dockerinit binary (even if it's our local binary), we copy it into config.Root at localCopy for future use (so that the original can go away without that being a problem, for example during a package upgrade). if err := os.Mkdir(path.Dir(localCopy), 0700); err != nil && !os.IsExist(err) { return nil, err } if _, err := utils.CopyFile(sysInitPath, localCopy); err != nil { return nil, err } if err := os.Chmod(localCopy, 0700); err != nil { return nil, err } sysInitPath = localCopy } sysInfo := sysinfo.New(false) ed, err := execdrivers.NewDriver(config.ExecDriver, config.Root, sysInitPath, sysInfo) if err != nil { return nil, err } daemon := &Daemon{ repository: daemonRepo, containers: &contStore{s: make(map[string]*Container)}, graph: g, repositories: repositories, idIndex: truncindex.NewTruncIndex([]string{}), sysInfo: sysInfo, volumes: volumes, config: config, containerGraph: graph, driver: driver, sysInitPath: sysInitPath, execDriver: ed, eng: eng, } if err := daemon.checkLocaldns(); err != nil { return nil, err } if err := daemon.restore(); err != nil { return nil, err } // Setup shutdown handlers // FIXME: can these shutdown handlers be registered closer to their source? eng.OnShutdown(func() { // FIXME: if these cleanup steps can be called concurrently, register // them as separate handlers to speed up total shutdown time // FIXME: use engine logging instead of log.Errorf if err := daemon.shutdown(); err != nil { log.Errorf("daemon.shutdown(): %s", err) } if err := portallocator.ReleaseAll(); err != nil { log.Errorf("portallocator.ReleaseAll(): %s", err) } if err := daemon.driver.Cleanup(); err != nil { log.Errorf("daemon.driver.Cleanup(): %s", err.Error()) } if err := daemon.containerGraph.Close(); err != nil { log.Errorf("daemon.containerGraph.Close(): %s", err.Error()) } }) return daemon, nil } func (daemon *Daemon) shutdown() error { group := sync.WaitGroup{} log.Debugf("starting clean shutdown of all containers...") for _, container := range daemon.List() { c := container if c.State.IsRunning() { log.Debugf("stopping %s", c.ID) group.Add(1) go func() { defer group.Done() if err := c.KillSig(15); err != nil { log.Debugf("kill 15 error for %s - %s", c.ID, err) } c.State.WaitStop(-1 * time.Second) log.Debugf("container stopped %s", c.ID) }() } } group.Wait() return nil } func (daemon *Daemon) Mount(container *Container) error { dir, err := daemon.driver.Get(container.ID, container.GetMountLabel()) if err != nil { return fmt.Errorf("Error getting container %s from driver %s: %s", container.ID, daemon.driver, err) } if container.basefs == "" { container.basefs = dir } else if container.basefs != dir { return fmt.Errorf("Error: driver %s is returning inconsistent paths for container %s ('%s' then '%s')", daemon.driver, container.ID, container.basefs, dir) } return nil } func (daemon *Daemon) Unmount(container *Container) error { daemon.driver.Put(container.ID) return nil } func (daemon *Daemon) Changes(container *Container) ([]archive.Change, error) { if differ, ok := daemon.driver.(graphdriver.Differ); ok { return differ.Changes(container.ID) } cDir, err := daemon.driver.Get(container.ID, "") if err != nil { return nil, fmt.Errorf("Error getting container rootfs %s from driver %s: %s", container.ID, container.daemon.driver, err) } defer daemon.driver.Put(container.ID) initDir, err := daemon.driver.Get(container.ID+"-init", "") if err != nil { return nil, fmt.Errorf("Error getting container init rootfs %s from driver %s: %s", container.ID, container.daemon.driver, err) } defer daemon.driver.Put(container.ID + "-init") return archive.ChangesDirs(cDir, initDir) } func (daemon *Daemon) Diff(container *Container) (archive.Archive, error) { if differ, ok := daemon.driver.(graphdriver.Differ); ok { return differ.Diff(container.ID) } changes, err := daemon.Changes(container) if err != nil { return nil, err } cDir, err := daemon.driver.Get(container.ID, "") if err != nil { return nil, fmt.Errorf("Error getting container rootfs %s from driver %s: %s", container.ID, container.daemon.driver, err) } archive, err := archive.ExportChanges(cDir, changes) if err != nil { return nil, err } return utils.NewReadCloserWrapper(archive, func() error { err := archive.Close() daemon.driver.Put(container.ID) return err }), nil } func (daemon *Daemon) Run(c *Container, pipes *execdriver.Pipes, startCallback execdriver.StartCallback) (int, error) { return daemon.execDriver.Run(c.command, pipes, startCallback) } func (daemon *Daemon) Pause(c *Container) error { if err := daemon.execDriver.Pause(c.command); err != nil { return err } c.State.SetPaused() return nil } func (daemon *Daemon) Unpause(c *Container) error { if err := daemon.execDriver.Unpause(c.command); err != nil { return err } c.State.SetUnpaused() return nil } func (daemon *Daemon) Kill(c *Container, sig int) error { return daemon.execDriver.Kill(c.command, sig) } // Nuke kills all containers then removes all content // from the content root, including images, volumes and // container filesystems. // Again: this will remove your entire docker daemon! // FIXME: this is deprecated, and only used in legacy // tests. Please remove. func (daemon *Daemon) Nuke() error { var wg sync.WaitGroup for _, container := range daemon.List() { wg.Add(1) go func(c *Container) { c.Kill() wg.Done() }(container) } wg.Wait() return os.RemoveAll(daemon.config.Root) } // FIXME: this is a convenience function for integration tests // which need direct access to daemon.graph. // Once the tests switch to using engine and jobs, this method // can go away. func (daemon *Daemon) Graph() *graph.Graph { return daemon.graph } func (daemon *Daemon) Repositories() *graph.TagStore { return daemon.repositories } func (daemon *Daemon) Config() *Config { return daemon.config } func (daemon *Daemon) SystemConfig() *sysinfo.SysInfo { return daemon.sysInfo } func (daemon *Daemon) SystemInitPath() string { return daemon.sysInitPath } func (daemon *Daemon) GraphDriver() graphdriver.Driver { return daemon.driver } func (daemon *Daemon) ExecutionDriver() execdriver.Driver { return daemon.execDriver } func (daemon *Daemon) Volumes() *graph.Graph { return daemon.volumes } func (daemon *Daemon) ContainerGraph() *graphdb.Database { return daemon.containerGraph } func (daemon *Daemon) checkLocaldns() error { resolvConf, err := resolvconf.Get() if err != nil { return err } if len(daemon.config.Dns) == 0 && utils.CheckLocalDns(resolvConf) { log.Infof("Local (127.0.0.1) DNS resolver found in resolv.conf and containers can't use it. Using default external servers : %v", DefaultDns) daemon.config.Dns = DefaultDns } return nil } func (daemon *Daemon) ImageGetCached(imgID string, config *runconfig.Config) (*image.Image, error) { // Retrieve all images images, err := daemon.Graph().Map() if err != nil { return nil, err } // Store the tree in a map of map (map[parentId][childId]) imageMap := make(map[string]map[string]struct{}) for _, img := range images { if _, exists := imageMap[img.Parent]; !exists { imageMap[img.Parent] = make(map[string]struct{}) } imageMap[img.Parent][img.ID] = struct{}{} } // Loop on the children of the given image and check the config var match *image.Image for elem := range imageMap[imgID] { img, err := daemon.Graph().Get(elem) if err != nil { return nil, err } if runconfig.Compare(&img.ContainerConfig, config) { if match == nil || match.Created.Before(img.Created) { match = img } } } return match, nil } func checkKernelAndArch() error { // Check for unsupported architectures if runtime.GOARCH != "amd64" { return fmt.Errorf("The Docker runtime currently only supports amd64 (not %s). This will change in the future. Aborting.", runtime.GOARCH) } // Check for unsupported kernel versions // FIXME: it would be cleaner to not test for specific versions, but rather // test for specific functionalities. // Unfortunately we can't test for the feature "does not cause a kernel panic" // without actually causing a kernel panic, so we need this workaround until // the circumstances of pre-3.8 crashes are clearer. // For details see http://github.com/docker/docker/issues/407 if k, err := kernel.GetKernelVersion(); err != nil { log.Infof("WARNING: %s", err) } else { if kernel.CompareKernelVersion(k, &kernel.KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0}) < 0 { if os.Getenv("DOCKER_NOWARN_KERNEL_VERSION") == "" { log.Infof("WARNING: You are running linux kernel version %s, which might be unstable running docker. Please upgrade your kernel to 3.8.0.", k.String()) } } } return nil }
LoeAple/docker
daemon/daemon.go
GO
apache-2.0
32,807
# -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2016-03-17 19:21 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('tilecache', '0002_auto_20160317_1519'), ] operations = [ migrations.AlterModelOptions( name='channel', options={'managed': True}, ), migrations.AlterModelTable( name='channel', table='channels', ), ]
openconnectome/ocptilecache
tilecache/migrations/0003_auto_20160317_1521.py
Python
apache-2.0
512
/* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.dataflow.server.repository; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import javax.sql.DataSource; import org.springframework.cloud.dataflow.core.StreamDefinition; import org.springframework.jdbc.core.RowMapper; import org.springframework.util.Assert; /** * RDBMS implementation of {@link StreamDefinitionRepository}. * * @author Ilayaperumal Gopinathan */ public class RdbmsStreamDefinitionRepository extends AbstractRdbmsKeyValueRepository<StreamDefinition> implements StreamDefinitionRepository { public RdbmsStreamDefinitionRepository(DataSource dataSource) { super(dataSource, "STREAM_", "DEFINITIONS", new RowMapper<StreamDefinition>() { @Override public StreamDefinition mapRow(ResultSet resultSet, int i) throws SQLException { return new StreamDefinition(resultSet.getString("DEFINITION_NAME"), resultSet.getString("DEFINITION")); } }, "DEFINITION_NAME", "DEFINITION"); } @Override public <S extends StreamDefinition> S save(S definition) { Assert.notNull(definition, "definition must not be null"); if (exists(definition.getName())) { throw new DuplicateStreamDefinitionException(String.format( "Cannot create stream %s because another one has already " + "been created with the same name", definition.getName())); } Object[] insertParameters = new Object[] { definition.getName(), definition.getDslText() }; jdbcTemplate.update(saveRow, insertParameters, new int[] { Types.VARCHAR, Types.CLOB }); return definition; } @Override public void delete(StreamDefinition definition) { Assert.notNull(definition, "definition must not null"); delete(definition.getName()); } }
markfisher/spring-cloud-dataflow
spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/repository/RdbmsStreamDefinitionRepository.java
Java
apache-2.0
2,334
/* * 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.sis.metadata.iso.quality; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlRootElement; import org.opengis.metadata.quality.RelativeInternalPositionalAccuracy; /** * Closeness of the relative positions of features in the scope to their respective * relative positions accepted as or being true. * The following property is mandatory in a well-formed metadata according ISO 19115: * * <div class="preformat">{@code DQ_RelativeInternalPositionalAccuracy} * {@code   └─result……………} Value obtained from applying a data quality measure.</div> * * <h2>Limitations</h2> * <ul> * <li>Instances of this class are not synchronized for multi-threading. * Synchronization, if needed, is caller's responsibility.</li> * <li>Serialized objects of this class are not guaranteed to be compatible with future Apache SIS releases. * Serialization support is appropriate for short term storage or RMI between applications running the * same version of Apache SIS. For long term storage, use {@link org.apache.sis.xml.XML} instead.</li> * </ul> * * @author Martin Desruisseaux (IRD, Geomatys) * @author Touraïvane (IRD) * @version 1.0 * @since 0.3 * @module */ @XmlType(name = "DQ_RelativeInternalPositionalAccuracy_Type") @XmlRootElement(name = "DQ_RelativeInternalPositionalAccuracy") public class DefaultRelativeInternalPositionalAccuracy extends AbstractPositionalAccuracy implements RelativeInternalPositionalAccuracy { /** * Serial number for inter-operability with different versions. */ private static final long serialVersionUID = 8385667875833802576L; /** * Constructs an initially empty relative internal positional accuracy. */ public DefaultRelativeInternalPositionalAccuracy() { } /** * Constructs a new instance initialized with the values from the specified metadata object. * This is a <cite>shallow</cite> copy constructor, since the other metadata contained in the * given object are not recursively copied. * * @param object the metadata to copy values from, or {@code null} if none. * * @see #castOrCopy(RelativeInternalPositionalAccuracy) */ public DefaultRelativeInternalPositionalAccuracy(final RelativeInternalPositionalAccuracy object) { super(object); } /** * Returns a SIS metadata implementation with the values of the given arbitrary implementation. * This method performs the first applicable action in the following choices: * * <ul> * <li>If the given object is {@code null}, then this method returns {@code null}.</li> * <li>Otherwise if the given object is already an instance of * {@code DefaultRelativeInternalPositionalAccuracy}, then it is returned unchanged.</li> * <li>Otherwise a new {@code DefaultRelativeInternalPositionalAccuracy} instance is created using the * {@linkplain #DefaultRelativeInternalPositionalAccuracy(RelativeInternalPositionalAccuracy) copy constructor} * and returned. Note that this is a <cite>shallow</cite> copy operation, since the other * metadata contained in the given object are not recursively copied.</li> * </ul> * * @param object the object to get as a SIS implementation, or {@code null} if none. * @return a SIS implementation containing the values of the given object (may be the * given object itself), or {@code null} if the argument was null. */ public static DefaultRelativeInternalPositionalAccuracy castOrCopy(final RelativeInternalPositionalAccuracy object) { if (object == null || object instanceof DefaultRelativeInternalPositionalAccuracy) { return (DefaultRelativeInternalPositionalAccuracy) object; } return new DefaultRelativeInternalPositionalAccuracy(object); } }
apache/sis
core/sis-metadata/src/main/java/org/apache/sis/metadata/iso/quality/DefaultRelativeInternalPositionalAccuracy.java
Java
apache-2.0
4,741
//----------------------------------------------------------------------- // <copyright file="RealMessageEnvelope.cs" company="Akka.NET Project"> // Copyright (C) 2009-2020 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2020 .NET Foundation <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using Akka.Actor; namespace Akka.TestKit { /// <summary> /// TBD /// </summary> public class RealMessageEnvelope : MessageEnvelope { private readonly object _message; private readonly IActorRef _sender; /// <summary> /// TBD /// </summary> /// <param name="message">TBD</param> /// <param name="sender">TBD</param> public RealMessageEnvelope(object message, IActorRef sender) { _message = message; _sender = sender; } /// <summary> /// TBD /// </summary> public override object Message { get { return _message; } } /// <summary> /// TBD /// </summary> public override IActorRef Sender{get { return _sender; }} /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> public override string ToString() { return "<" + (Message ?? "null") + "> from " + (Sender == ActorRefs.NoSender ? "NoSender" : Sender.ToString()); } } }
simonlaroche/akka.net
src/core/Akka.TestKit/RealMessageEnvelope.cs
C#
apache-2.0
1,493
/* * Copyright 2022 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thoughtworks.go.server.util; import java.util.UUID; import org.springframework.stereotype.Component; /** * @understands generating random uuid */ @Component public class UuidGenerator { public String randomUuid() { return UUID.randomUUID().toString(); } }
gocd/gocd
common/src/main/java/com/thoughtworks/go/server/util/UuidGenerator.java
Java
apache-2.0
891
/* * Copyright 2013 Robert von Burg <eitch@eitchnet.ch> * * 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 li.strolch.agent.api; import li.strolch.privilege.model.Restrictable; /** * A simple implementation for the {@link Restrictable} interface * * @author Robert von Burg <eitch@eitchnet.ch> */ public class RestrictableElement implements Restrictable { private String name; private Object value; public RestrictableElement(String name, Object value) { super(); this.name = name; this.value = value; } @Override public String getPrivilegeName() { return this.name; } @Override public Object getPrivilegeValue() { return this.value; } public static Restrictable restrictableFor(String name, Object value) { return new RestrictableElement(name, value); } }
4treesCH/strolch
li.strolch.agent/src/main/java/li/strolch/agent/api/RestrictableElement.java
Java
apache-2.0
1,316
/* * Copyright 2014 Splunk, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"): you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ namespace Splunk.Client { using System.Runtime.Serialization; /// <summary> /// Specifies the type of a Splunk search <see cref="Job"/>. /// </summary> public enum ExecutionMode { /// <summary> /// No sort direction is set. /// </summary> None, /// <summary> /// Specifies an asynchronous <see cref="Job"/>. /// </summary> /// <remarks> /// A Search ID (SID) is returned as soon as the job starts. In this /// case you must poll back for results. This is the default. /// </remarks> [EnumMember(Value="normal")] Normal, /// <summary> /// Specifies that a Search ID (SID) should be returned when the /// <see cref="job"/> is complete. /// </summary> [EnumMember(Value = "blocking")] Blocking, /// <summary> /// Specifies that search results should be returned when the job is /// complete. /// </summary> /// <remarks> /// In this case you can specify the format for the output (for example, /// JSON output) using the OutputMode parameter as described in <a href= /// "http://goo.gl/vJvIXv">GET search/jobs/export</a>. Default format for /// output is XML. /// </remarks> [EnumMember(Value = "oneshot")] Oneshot } }
glennblock/splunk-sdk-csharp-pcl-hold
src/Splunk/Splunk/Client/ExecutionMode.cs
C#
apache-2.0
2,010
/* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.odk.collect.android.provider; import android.net.Uri; import android.provider.BaseColumns; /** * Convenience definitions for NotePadProvider */ public final class InstanceProviderAPI { public static final String AUTHORITY = "org.odk.collect.android.provider.odk.instances"; // This class cannot be instantiated private InstanceProviderAPI() { } // status for instances public static final String STATUS_INCOMPLETE = "incomplete"; public static final String STATUS_COMPLETE = "complete"; public static final String STATUS_SUBMITTED = "submitted"; public static final String STATUS_SUBMISSION_FAILED = "submissionFailed"; /** * Notes table */ public static final class InstanceColumns implements BaseColumns { // This class cannot be instantiated private InstanceColumns() { } public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/instances"); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.odk.instance"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.odk.instance"; // These are the only things needed for an insert public static final String DISPLAY_NAME = "displayName"; public static final String SUBMISSION_URI = "submissionUri"; public static final String INSTANCE_FILE_PATH = "instanceFilePath"; public static final String JR_FORM_ID = "jrFormId"; public static final String JR_VERSION = "jrVersion"; //public static final String FORM_ID = "formId"; // these are generated for you (but you can insert something else if you want) public static final String STATUS = "status"; public static final String CAN_EDIT_WHEN_COMPLETE = "canEditWhenComplete"; public static final String LAST_STATUS_CHANGE_DATE = "date"; public static final String DISPLAY_SUBTEXT = "displaySubtext"; //public static final String DISPLAY_SUB_SUBTEXT = "displaySubSubtext"; // public static final String DEFAULT_SORT_ORDER = "modified DESC"; // public static final String TITLE = "title"; // public static final String NOTE = "note"; // public static final String CREATED_DATE = "created"; // public static final String MODIFIED_DATE = "modified"; } }
mapkon/collect
collect_app/src/main/java/org/odk/collect/android/provider/InstanceProviderAPI.java
Java
apache-2.0
2,995
CREATE TABLE IF NOT EXISTS `DOWNLOAD_LIST_V2` ( `PRINCIPAL_ID` BIGINT NOT NULL, `UPDATED_ON` TIMESTAMP(3) NULL, `ETAG` char(36) NOT NULL, PRIMARY KEY (`PRINCIPAL_ID`), CONSTRAINT FOREIGN KEY (`PRINCIPAL_ID`) REFERENCES `JDOUSERGROUP` (`ID`) ON DELETE CASCADE )
Sage-Bionetworks/Synapse-Repository-Services
lib/jdomodels/src/main/resources/schema/DownloadList-V2-ddl.sql
SQL
apache-2.0
271
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.regionserver; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.metrics2.MetricsRecordBuilder; import org.apache.hadoop.metrics2.impl.JmxCacheBuster; import org.apache.hadoop.metrics2.lib.DynamicMetricsRegistry; import org.apache.hadoop.metrics2.lib.Interns; import org.apache.hadoop.metrics2.lib.MutableCounterLong; public class MetricsRegionSourceImpl implements MetricsRegionSource { private final MetricsRegionWrapper regionWrapper; private boolean closed = false; private MetricsRegionAggregateSourceImpl agg; private DynamicMetricsRegistry registry; private static final Log LOG = LogFactory.getLog(MetricsRegionSourceImpl.class); private String regionNamePrefix; private String regionPutKey; private String regionDeleteKey; private String regionGetKey; private String regionIncrementKey; private String regionAppendKey; private MutableCounterLong regionPut; private MutableCounterLong regionDelete; private MutableCounterLong regionGet; private MutableCounterLong regionIncrement; private MutableCounterLong regionAppend; public MetricsRegionSourceImpl(MetricsRegionWrapper regionWrapper, MetricsRegionAggregateSourceImpl aggregate) { this.regionWrapper = regionWrapper; agg = aggregate; agg.register(this); LOG.debug("Creating new MetricsRegionSourceImpl for table " + regionWrapper.getTableName() + " " + regionWrapper.getRegionName()); registry = agg.getMetricsRegistry(); regionNamePrefix = "table." + regionWrapper.getTableName() + "." + "region." + regionWrapper.getRegionName() + "."; String suffix = "Count"; regionPutKey = regionNamePrefix + MetricsRegionServerSource.MUTATE_KEY + suffix; regionPut = registry.getLongCounter(regionPutKey, 0l); regionDeleteKey = regionNamePrefix + MetricsRegionServerSource.DELETE_KEY + suffix; regionDelete = registry.getLongCounter(regionDeleteKey, 0l); regionGetKey = regionNamePrefix + MetricsRegionServerSource.GET_KEY + suffix; regionGet = registry.getLongCounter(regionGetKey, 0l); regionIncrementKey = regionNamePrefix + MetricsRegionServerSource.INCREMENT_KEY + suffix; regionIncrement = registry.getLongCounter(regionIncrementKey, 0l); regionAppendKey = regionNamePrefix + MetricsRegionServerSource.APPEND_KEY + suffix; regionAppend = registry.getLongCounter(regionAppendKey, 0l); } @Override public void close() { closed = true; agg.deregister(this); LOG.trace("Removing region Metrics: " + regionWrapper.getRegionName()); registry.removeMetric(regionPutKey); registry.removeMetric(regionDeleteKey); registry.removeMetric(regionGetKey); registry.removeMetric(regionIncrementKey); registry.removeMetric(regionAppendKey); JmxCacheBuster.clearJmxCache(); } @Override public void updatePut() { regionPut.incr(); } @Override public void updateDelete() { regionDelete.incr(); } @Override public void updateGet() { regionGet.incr(); } @Override public void updateIncrement() { regionIncrement.incr(); } @Override public void updateAppend() { regionAppend.incr(); } @Override public MetricsRegionAggregateSource getAggregateSource() { return agg; } @Override public int compareTo(MetricsRegionSource source) { if (!(source instanceof MetricsRegionSourceImpl)) return -1; MetricsRegionSourceImpl impl = (MetricsRegionSourceImpl) source; return this.regionWrapper.getRegionName() .compareTo(impl.regionWrapper.getRegionName()); } void snapshot(MetricsRecordBuilder mrb, boolean ignored) { if (closed) return; mrb.addGauge( Interns.info(regionNamePrefix + MetricsRegionServerSource.STORE_COUNT, MetricsRegionServerSource.STORE_COUNT_DESC), this.regionWrapper.getNumStores()); mrb.addGauge(Interns.info(regionNamePrefix + MetricsRegionServerSource.STOREFILE_COUNT, MetricsRegionServerSource.STOREFILE_COUNT_DESC), this.regionWrapper.getNumStoreFiles()); mrb.addGauge(Interns.info(regionNamePrefix + MetricsRegionServerSource.MEMSTORE_SIZE, MetricsRegionServerSource.MEMSTORE_SIZE_DESC), this.regionWrapper.getMemstoreSize()); mrb.addGauge(Interns.info(regionNamePrefix + MetricsRegionServerSource.STOREFILE_SIZE, MetricsRegionServerSource.STOREFILE_SIZE_DESC), this.regionWrapper.getStoreFileSize()); } }
daidong/DominoHBase
hbase-hadoop2-compat/src/main/java/org/apache/hadoop/hbase/regionserver/MetricsRegionSourceImpl.java
Java
apache-2.0
5,386
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2021 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Dan Larkin-York //////////////////////////////////////////////////////////////////////////////// #pragma once #include <cstdint> #include "Basics/ReadWriteSpinLock.h" namespace arangodb::basics { class SpinUnlocker { public: enum class Mode : std::uint8_t { Read, Write }; public: SpinUnlocker(Mode mode, ReadWriteSpinLock& lock) : _lock(lock), _mode(mode), _locked(true) { if (_mode == Mode::Read) { _lock.unlockRead(); } else { _lock.unlockWrite(); } _locked = false; } ~SpinUnlocker() { acquire(); } // no move SpinUnlocker(SpinUnlocker&&) = delete; SpinUnlocker& operator=(SpinUnlocker&&) = delete; // no copy SpinUnlocker(SpinUnlocker const&) = delete; SpinUnlocker& operator=(SpinUnlocker const&) = delete; bool isLocked() const { return _locked; } void acquire() { if (!_locked) { if (_mode == Mode::Read) { _lock.lockRead(); } else { _lock.lockWrite(); } _locked = true; } } private: ReadWriteSpinLock& _lock; Mode _mode; bool _locked; }; } // namespace arangodb::basics
Simran-B/arangodb
lib/Basics/SpinUnlocker.h
C
apache-2.0
1,969
#pragma once #include <Chip/CM3/Atmel/ATSAM3N1C/SPI.hpp> #include <Chip/CM3/Atmel/ATSAM3N1C/TC0.hpp> #include <Chip/CM3/Atmel/ATSAM3N1C/TC1.hpp> #include <Chip/CM3/Atmel/ATSAM3N1C/TWI0.hpp> #include <Chip/CM3/Atmel/ATSAM3N1C/TWI1.hpp> #include <Chip/CM3/Atmel/ATSAM3N1C/PWM.hpp> #include <Chip/CM3/Atmel/ATSAM3N1C/USART0.hpp> #include <Chip/CM3/Atmel/ATSAM3N1C/USART1.hpp> #include <Chip/CM3/Atmel/ATSAM3N1C/ADC.hpp> #include <Chip/CM3/Atmel/ATSAM3N1C/DACC.hpp> #include <Chip/CM3/Atmel/ATSAM3N1C/MATRIX.hpp> #include <Chip/CM3/Atmel/ATSAM3N1C/PMC.hpp> #include <Chip/CM3/Atmel/ATSAM3N1C/UART0.hpp> #include <Chip/CM3/Atmel/ATSAM3N1C/CHIPID.hpp> #include <Chip/CM3/Atmel/ATSAM3N1C/UART1.hpp> #include <Chip/CM3/Atmel/ATSAM3N1C/EFC.hpp> #include <Chip/CM3/Atmel/ATSAM3N1C/PIOA.hpp> #include <Chip/CM3/Atmel/ATSAM3N1C/PIOB.hpp> #include <Chip/CM3/Atmel/ATSAM3N1C/PIOC.hpp> #include <Chip/CM3/Atmel/ATSAM3N1C/RSTC.hpp> #include <Chip/CM3/Atmel/ATSAM3N1C/SUPC.hpp> #include <Chip/CM3/Atmel/ATSAM3N1C/RTT.hpp> #include <Chip/CM3/Atmel/ATSAM3N1C/WDT.hpp> #include <Chip/CM3/Atmel/ATSAM3N1C/RTC.hpp> #include <Chip/CM3/Atmel/ATSAM3N1C/GPBR.hpp>
porkybrain/Kvasir
Lib/Chip/ATSAM3N1C.hpp
C++
apache-2.0
1,139
Spoon ===== Distributing instrumentation tests to all your Androids. Introduction ------------ Android's ever-expanding ecosystem of devices creates a unique challenge to testing applications. Spoon aims to simplify this task by distributing instrumentation test execution and displaying the results in a meaningful way. Instead of attempting to be a new form of testing, Spoon makes existing instrumentation tests more useful. Using the application APK and instrumentation APK, Spoon runs the tests on multiple devices simultaneously. Once all tests have completed a static HTML summary is generated with detailed information about each device and test. ![High-level output](website/static/example_main.png) Spoon will run on all targets which are visible to `adb devices`. Plug in multiple different phones and tablets, start different configurations of emulators, or use some combination of both! The greater diversity of the targets in use, the more useful the output will be in visualizing your applications. Screenshots ----------- In addition to simply running instrumentation tests, Spoon has the ability to snap screenshots at key points during your tests which are then included in the output. This allows for visual inspection of test executions across different devices. Taking screenshots requires that you include the `spoon-client` JAR in your instrumentation app. For Spoon to save screenshots your app must have the `WRITE_EXTERNAL_STORAGE` permission. In your tests call the `screenshot` method with a human-readable tag. ```java Spoon.screenshot(activity, "initial_state"); /* Normal test code... */ Spoon.screenshot(activity, "after_login"); ``` The tag specified will be used to identify and compare screenshots taken across multiple test runs. ![Results with screenshots](website/static/example_screenshots.png) You can also view each test's screenshots as an animated GIF to gauge the actual sequence of interaction. Files ----- If you have files that will help you in debugging or auditing a test run, for example a log file or a SQLite database you can save these files easily and have them attached to your test report. This will let you easily drill down any issues that occurred in your test run. Attaching files to your report requires that you include the `spoon-client` jar and that you have `WRITE_EXTERNAL_STORAGE` permission. ```java // by absolute path string Spoon.save(context, "/data/data/com.yourapp/your.file"); // or with File Spoon.save(context, new File(context.getCacheDir(), "my-database.db")); ``` ![Device Results with files](website/static/example_files.png) You download the files by clicking on the filename in the device report. Download -------- Download the [latest runner JAR][1] or the [latest client JAR][2], or just add to your dependencies: Maven: ```xml <dependency> <groupId>com.squareup.spoon</groupId> <artifactId>spoon-client</artifactId> <version>1.3.1</version> </dependency> ``` Gradle: We recommend using the [gradle plugin][3] (currently maintained as a separate project). Snapshots of the development version are available in [Sonatype's `snapshots` repository][snap]. Execution --------- Spoon was designed to be run both as a standalone tool or directly as part of your build system. You can run Spoon as a standalone tool with your application and instrumentation APKs. ``` java -jar spoon-runner-1.3.1-jar-with-dependencies.jar \ --apk ExampleApp-debug.apk \ --test-apk ExampleApp-debug-androidTest-unaligned.apk ``` By default the output will be placed in a spoon-output/ folder of the current directory. You can control additional parameters of the execution using other flags. ``` Options: --apk Application APK --output Output path --sdk Path to Android SDK --test-apk Test application APK --title Execution title --class-name Test class name to run (fully-qualified) --method-name Test method name to run (must also use --class-name) --no-animations Disable animated gif generation --size Only run test methods annotated by testSize (small, medium, large) --adb-timeout Set maximum execution time per test in seconds (10min default) --fail-on-failure Non-zero exit code on failure --coverage Code coverage flag. For Spoon to calculate coverage file your app must have the `WRITE_EXTERNAL_STORAGE` permission. (This option pulls the coverage file from all devices and merge them into a single file `merged-coverage.ec`.) --fail-if-no-device-connected Fail if no device is connected --sequential Execute the tests device by device --init-script Path to a script that you want to run before each device --grant-all Grant all runtime permissions during installation on Marshmallow and above devices --e Arguments to pass to the Instrumentation Runner. This can be used multiple times for multiple entries. Usage: --e <NAME>=<VALUE>. The supported arguments varies depending on which test runner you are using, e.g. see the API docs for AndroidJUnitRunner. ``` If you are using Maven for compilation, a plugin is provided for easy execution. Declare the plugin in the `pom.xml` for the instrumentation test module. ```xml <plugin> <groupId>com.squareup.spoon</groupId> <artifactId>spoon-maven-plugin</artifactId> <version>1.3.1</version> </plugin> ``` The plugin will look for an `apk` dependency for the corresponding application. Typically this is specified in parallel with the `jar` dependency on the application. ```xml <dependency> <groupId>com.example</groupId> <artifactId>example-app</artifactId> <version>${project.version}</version> <type>jar</type> <scope>provided</scope> </dependency> <dependency> <groupId>com.example</groupId> <artifactId>example-app</artifactId> <version>${project.version}</version> <type>apk</type> <scope>provided</scope> </dependency> ``` You can invoke the plugin by running `mvn spoon:run`. The execution result will be placed in the `target/spoon-output/` folder. If you want to specify a test class to run, add `-Dspoon.test.class=fully.qualified.ClassName`. If you only want to run a single test in that class, add `-Dspoon.test.method=testAllTheThings`. For a working example see the sample application and instrumentation tests in the `spoon-sample/` folder. Test Sharding ------------- The Android Instrumentation runner supports test sharding using the `numShards` and `shardIndex` arguments ([documentation](https://developer.android.com/tools/testing-support-library/index.html#ajur-sharding)). If you are specifying serials for multiple devices, you may use spoon's built in auto-sharding by specifying --shard: ``` java -jar spoon-runner-1.3.1-jar-with-dependencies.jar \ --apk ExampleApp-debug.apk \ --test-apk ExampleApp-debug-androidTest-unaligned.apk \ -serial emulator-1 \ -serial emulator-2 \ --shard ``` This will automatically shard across all specified serials, and merge the results. When this option is running with `--coverage` flag. It will merge all the coverage files generated from all devices into a single file called `merged-coverage.ec`. If you'd like to use a different sharding strategy, you can use the `--e` option with Spoon to pass those arguments through to the instrumentation runner, e.g. ``` java -jar spoon-runner-1.3.1-jar-with-dependencies.jar \ --apk ExampleApp-debug.apk \ --test-apk ExampleApp-debug-androidTest-unaligned.apk \ --e numShards=4 \ --e shardIndex=0 ``` However, it will be up to you to merge the output from the shards. If you use Jenkins, a good way to set up sharding is inside a "Multi-configuration project". - Add a "User-defined Axis". Choose a name for the shard index variable, and define the index values you want (starting at zero). ![User-defined Axis](website/static/jenkins_matrix_user_axis.png) - In your "Execute shell" step, use the same execution command as above, but inject the shard index for each slave node using the variable you defined above, e.g. `--e shardIndex=${shard_index}`. Make sure you're passing in the correct total number of shards too, e.g. `--e numShards=4`. ![Execute shell](website/static/jenkins_matrix_execute_shell.png) Running Specific Tests ---------------------- There are numerous ways to run a specific test, or set of tests. You can use the Spoon `--size`, `--class-name` or `--method-name` options, or you can use the `--e` option to pass arguments to the instrumentation runner, e.g. ``` --e package=com.mypackage.unit_tests ``` See the documentation for your instrumentation runner to find the full list of supported options (e.g. [AndroidJUnitRunner](http://developer.android.com/reference/android/support/test/runner/AndroidJUnitRunner.html)). License -------- Copyright 2013 Square, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. [1]: https://search.maven.org/remote_content?g=com.squareup.spoon&a=spoon-runner&v=LATEST&c=jar-with-dependencies [2]: https://search.maven.org/remote_content?g=com.squareup.spoon&a=spoon-client&v=LATEST [3]: https://github.com/stanfy/spoon-gradle-plugin [snap]: https://oss.sonatype.org/content/repositories/snapshots/
daj/spoon
README.md
Markdown
apache-2.0
9,977
/** * Get more info at : www.jrebirth.org . * Copyright JRebirth.org © 2011-2013 * Contact : sebastien.bordes@jrebirth.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jrebirth.af.core.ui.fxml; import org.jrebirth.af.api.ui.Model; import org.jrebirth.af.api.wave.Wave; /** * The interface <strong>DefaultFXMLModel</strong>. * * Default implementation of the FXML model. * * @param <M> the class type of the current model * @param <O> the class type of the bindable object * * @author Sébastien Bordes */ public class DefaultFXMLObjectModel<M extends Model, O extends Object> extends AbstractFXMLObjectModel<M, O> { /** * {@inheritDoc} */ @Override protected void initModel() { // Nothing to do yet } /** * {@inheritDoc} */ @Override protected void bind() { // Nothing to do yet } /** * {@inheritDoc} */ @Override protected void unbind() { // Nothing to do yet } /** * {@inheritDoc} */ @Override protected void initInnerComponents() { // Nothing to do yet } /** * {@inheritDoc} */ @Override protected void showView() { // Nothing to do yet } /** * {@inheritDoc} */ @Override protected void hideView() { // Nothing to do yet } /** * {@inheritDoc} */ @Override protected void processWave(final Wave wave) { // Nothing to do yet } }
JRebirth/JRebirth
org.jrebirth.af/core/src/main/java/org/jrebirth/af/core/ui/fxml/DefaultFXMLObjectModel.java
Java
apache-2.0
2,020
# # Author:: Adam Jacob (<adam@opscode.com>) # Author:: Christopher Walters (<cw@opscode.com>) # Author:: Tim Hinderliter (<tim@opscode.com>) # Copyright:: Copyright (c) 2008-2010 Opscode, Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require 'chef/resource_collection' require 'chef/cookbook_version' require 'chef/node' require 'chef/role' require 'chef/log' require 'chef/recipe' require 'chef/run_context/cookbook_compiler' require 'chef/event_dispatch/events_output_stream' class Chef # == Chef::RunContext # Value object that loads and tracks the context of a Chef run class RunContext # Chef::Node object for this run attr_reader :node # Chef::CookbookCollection for this run attr_reader :cookbook_collection # Resource Definitions for this run. Populated when the files in # +definitions/+ are evaluated (this is triggered by #load). attr_reader :definitions ### # These need to be settable so deploy can run a resource_collection # independent of any cookbooks via +recipe_eval+ # The Chef::ResourceCollection for this run. Populated by evaluating # recipes, which is triggered by #load. (See also: CookbookCompiler) attr_accessor :resource_collection # A Hash containing the immediate notifications triggered by resources # during the converge phase of the chef run. attr_accessor :immediate_notification_collection # A Hash containing the delayed (end of run) notifications triggered by # resources during the converge phase of the chef run. attr_accessor :delayed_notification_collection # Event dispatcher for this run. attr_reader :events # Creates a new Chef::RunContext object and populates its fields. This object gets # used by the Chef Server to generate a fully compiled recipe list for a node. # # === Returns # object<Chef::RunContext>:: Duh. :) def initialize(node, cookbook_collection, events) @node = node @cookbook_collection = cookbook_collection @resource_collection = Chef::ResourceCollection.new @immediate_notification_collection = Hash.new {|h,k| h[k] = []} @delayed_notification_collection = Hash.new {|h,k| h[k] = []} @definitions = Hash.new @loaded_recipes = {} @loaded_attributes = {} @events = events @node.run_context = self @cookbook_compiler = nil end # Triggers the compile phase of the chef run. Implemented by # Chef::RunContext::CookbookCompiler def load(run_list_expansion) @cookbook_compiler = CookbookCompiler.new(self, run_list_expansion, events) @cookbook_compiler.compile end # Adds an immediate notification to the # +immediate_notification_collection+. The notification should be a # Chef::Resource::Notification or duck type. def notifies_immediately(notification) nr = notification.notifying_resource if nr.instance_of?(Chef::Resource) @immediate_notification_collection[nr.name] << notification else @immediate_notification_collection[nr.to_s] << notification end end # Adds a delayed notification to the +delayed_notification_collection+. The # notification should be a Chef::Resource::Notification or duck type. def notifies_delayed(notification) nr = notification.notifying_resource if nr.instance_of?(Chef::Resource) @delayed_notification_collection[nr.name] << notification else @delayed_notification_collection[nr.to_s] << notification end end def immediate_notifications(resource) if resource.instance_of?(Chef::Resource) return @immediate_notification_collection[resource.name] else return @immediate_notification_collection[resource.to_s] end end def delayed_notifications(resource) if resource.instance_of?(Chef::Resource) return @delayed_notification_collection[resource.name] else return @delayed_notification_collection[resource.to_s] end end # Evaluates the recipes +recipe_names+. Used by DSL::IncludeRecipe def include_recipe(*recipe_names) result_recipes = Array.new recipe_names.flatten.each do |recipe_name| if result = load_recipe(recipe_name) result_recipes << result end end result_recipes end # Evaluates the recipe +recipe_name+. Used by DSL::IncludeRecipe def load_recipe(recipe_name) Chef::Log.debug("Loading Recipe #{recipe_name} via include_recipe") cookbook_name, recipe_short_name = Chef::Recipe.parse_recipe_name(recipe_name) if unreachable_cookbook?(cookbook_name) # CHEF-4367 Chef::Log.warn(<<-ERROR_MESSAGE) MissingCookbookDependency: Recipe `#{recipe_name}` is not in the run_list, and cookbook '#{cookbook_name}' is not a dependency of any cookbook in the run_list. To load this recipe, first add a dependency on cookbook '#{cookbook_name}' in the cookbook you're including it from in that cookbook's metadata. ERROR_MESSAGE end if loaded_fully_qualified_recipe?(cookbook_name, recipe_short_name) Chef::Log.debug("I am not loading #{recipe_name}, because I have already seen it.") false else loaded_recipe(cookbook_name, recipe_short_name) node.loaded_recipe(cookbook_name, recipe_short_name) cookbook = cookbook_collection[cookbook_name] cookbook.load_recipe(recipe_short_name, self) end end def load_recipe_file(recipe_file) if !File.exist?(recipe_file) raise Chef::Exceptions::RecipeNotFound, "could not find recipe file #{recipe_file}" end Chef::Log.debug("Loading Recipe File #{recipe_file}") recipe = Chef::Recipe.new('@recipe_files', recipe_file, self) recipe.from_file(recipe_file) recipe end # Looks up an attribute file given the +cookbook_name+ and # +attr_file_name+. Used by DSL::IncludeAttribute def resolve_attribute(cookbook_name, attr_file_name) cookbook = cookbook_collection[cookbook_name] raise Chef::Exceptions::CookbookNotFound, "could not find cookbook #{cookbook_name} while loading attribute #{name}" unless cookbook attribute_filename = cookbook.attribute_filenames_by_short_filename[attr_file_name] raise Chef::Exceptions::AttributeNotFound, "could not find filename for attribute #{attr_file_name} in cookbook #{cookbook_name}" unless attribute_filename attribute_filename end # An Array of all recipes that have been loaded. This is stored internally # as a Hash, so ordering is not preserved when using ruby 1.8. # # Recipe names are given in fully qualified form, e.g., the recipe "nginx" # will be given as "nginx::default" # # To determine if a particular recipe has been loaded, use #loaded_recipe? def loaded_recipes @loaded_recipes.keys end # An Array of all attributes files that have been loaded. Stored internally # using a Hash, so order is not preserved on ruby 1.8. # # Attribute file names are given in fully qualified form, e.g., # "nginx::default" instead of "nginx". def loaded_attributes @loaded_attributes.keys end def loaded_fully_qualified_recipe?(cookbook, recipe) @loaded_recipes.has_key?("#{cookbook}::#{recipe}") end # Returns true if +recipe+ has been loaded, false otherwise. Default recipe # names are expanded, so `loaded_recipe?("nginx")` and # `loaded_recipe?("nginx::default")` are valid and give identical results. def loaded_recipe?(recipe) cookbook, recipe_name = Chef::Recipe.parse_recipe_name(recipe) loaded_fully_qualified_recipe?(cookbook, recipe_name) end def loaded_fully_qualified_attribute?(cookbook, attribute_file) @loaded_attributes.has_key?("#{cookbook}::#{attribute_file}") end def loaded_attribute(cookbook, attribute_file) @loaded_attributes["#{cookbook}::#{attribute_file}"] = true end ## # Cookbook File Introspection def has_template_in_cookbook?(cookbook, template_name) cookbook = cookbook_collection[cookbook] cookbook.has_template_for_node?(node, template_name) end def has_cookbook_file_in_cookbook?(cookbook, cb_file_name) cookbook = cookbook_collection[cookbook] cookbook.has_cookbook_file_for_node?(node, cb_file_name) end # Delegates to CookbookCompiler#unreachable_cookbook? # Used to raise an error when attempting to load a recipe belonging to a # cookbook that is not in the dependency graph. See also: CHEF-4367 def unreachable_cookbook?(cookbook_name) @cookbook_compiler.unreachable_cookbook?(cookbook_name) end # Open a stream object that can be printed into and will dispatch to events # # == Arguments # options is a hash with these possible options: # - name: a string that identifies the stream to the user. Preferably short. # # Pass a block and the stream will be yielded to it, and close on its own # at the end of the block. def open_stream(options = {}) stream = EventDispatch::EventsOutputStream.new(events, options) if block_given? begin yield stream ensure stream.close end else stream end end private def loaded_recipe(cookbook, recipe) @loaded_recipes["#{cookbook}::#{recipe}"] = true end end end
evertrue/chef
lib/chef/run_context.rb
Ruby
apache-2.0
10,032
/* * $Id$ * * Copyright 2001-2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.struts.action; import java.io.Serializable; /** * <p>An encapsulation of an individual message returned by the * <code>validate</code> method of an <code>ActionForm</code>, consisting * of a message key (to be used to look up message text in an appropriate * message resources database) plus up to four placeholder objects that can * be used for parametric replacement in the message text.</p> * * @version $Rev$ $Date$ * @since Struts 1.1 */ public class ActionMessage implements Serializable { // ----------------------------------------------------------- Constructors /** * <p>Construct an action message with no replacement values.</p> * * @param key Message key for this message */ public ActionMessage(String key) { this(key, null); } /** * <p>Construct an action message with the specified replacement values.</p> * * @param key Message key for this message * @param value0 First replacement value */ public ActionMessage(String key, Object value0) { this(key, new Object[] { value0 }); } /** * <p>Construct an action message with the specified replacement values.</p> * * @param key Message key for this message * @param value0 First replacement value * @param value1 Second replacement value */ public ActionMessage(String key, Object value0, Object value1) { this(key, new Object[] { value0, value1 }); } /** * <p>Construct an action message with the specified replacement values.</p> * * @param key Message key for this message * @param value0 First replacement value * @param value1 Second replacement value * @param value2 Third replacement value */ public ActionMessage(String key, Object value0, Object value1, Object value2) { this(key, new Object[] { value0, value1, value2 }); } /** * <p>Construct an action message with the specified replacement values.</p> * * @param key Message key for this message * @param value0 First replacement value * @param value1 Second replacement value * @param value2 Third replacement value * @param value3 Fourth replacement value */ public ActionMessage(String key, Object value0, Object value1, Object value2, Object value3) { this(key, new Object[] { value0, value1, value2, value3 }); } /** * <p>Construct an action message with the specified replacement values.</p> * * @param key Message key for this message * @param values Array of replacement values */ public ActionMessage(String key, Object[] values) { this.key = key; this.values = values; this.resource = true; } /** * <p>Construct an action message with the specified replacement values.</p> * * @param key Message key for this message * @param resource Indicates whether the key is a bundle key or literal value */ public ActionMessage(String key, boolean resource) { this.key = key; this.resource = resource; } // ----------------------------------------------------- Instance Variables /** * <p>The message key for this message.</p> */ protected String key = null; /** * <p>The replacement values for this mesasge.</p> */ protected Object values[] = null; /** * <p>Indicates whether the key is taken to be as a bundle key [true] or literal value [false].</p> */ protected boolean resource = true; // --------------------------------------------------------- Public Methods /** * <p>Get the message key for this message.</p> */ public String getKey() { return (this.key); } /** * <p>Get the replacement values for this message.</p> */ public Object[] getValues() { return (this.values); } /** * <p>Indicate whether the key is taken to be as a bundle key [true] or literal value [false].</p> */ public boolean isResource() { return (this.resource); } /** * <p>Returns a String in the format: key[value1, value2, etc].</p> * * @see java.lang.Object#toString() */ public String toString() { StringBuffer buff = new StringBuffer(); buff.append(this.key); buff.append("["); if (this.values != null) { for (int i = 0; i < this.values.length; i++) { buff.append(this.values[i]); // don't append comma to last entry if (i < this.values.length - 1) { buff.append(", "); } } } buff.append("]"); return buff.toString(); } }
kawasima/struts-taglib-compatible
src/share/org/apache/struts/action/ActionMessage.java
Java
apache-2.0
5,427
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights * Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.ecr.model.transform; import java.io.ByteArrayInputStream; import java.util.Collections; import java.util.Map; import java.util.List; import java.util.regex.Pattern; import com.amazonaws.AmazonClientException; import com.amazonaws.Request; import com.amazonaws.DefaultRequest; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.ecr.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.util.BinaryUtils; import com.amazonaws.util.StringUtils; import com.amazonaws.util.IdempotentUtils; import com.amazonaws.util.StringInputStream; import com.amazonaws.protocol.json.*; /** * ListImagesRequest Marshaller */ public class ListImagesRequestMarshaller implements Marshaller<Request<ListImagesRequest>, ListImagesRequest> { private final SdkJsonProtocolFactory protocolFactory; public ListImagesRequestMarshaller(SdkJsonProtocolFactory protocolFactory) { this.protocolFactory = protocolFactory; } public Request<ListImagesRequest> marshall( ListImagesRequest listImagesRequest) { if (listImagesRequest == null) { throw new AmazonClientException( "Invalid argument passed to marshall(...)"); } Request<ListImagesRequest> request = new DefaultRequest<ListImagesRequest>( listImagesRequest, "AmazonECR"); request.addHeader("X-Amz-Target", "AmazonEC2ContainerRegistry_V20150921.ListImages"); request.setHttpMethod(HttpMethodName.POST); request.setResourcePath(""); try { final StructuredJsonGenerator jsonGenerator = protocolFactory .createGenerator(); jsonGenerator.writeStartObject(); if (listImagesRequest.getRegistryId() != null) { jsonGenerator.writeFieldName("registryId").writeValue( listImagesRequest.getRegistryId()); } if (listImagesRequest.getRepositoryName() != null) { jsonGenerator.writeFieldName("repositoryName").writeValue( listImagesRequest.getRepositoryName()); } if (listImagesRequest.getNextToken() != null) { jsonGenerator.writeFieldName("nextToken").writeValue( listImagesRequest.getNextToken()); } if (listImagesRequest.getMaxResults() != null) { jsonGenerator.writeFieldName("maxResults").writeValue( listImagesRequest.getMaxResults()); } jsonGenerator.writeEndObject(); byte[] content = jsonGenerator.getBytes(); request.setContent(new ByteArrayInputStream(content)); request.addHeader("Content-Length", Integer.toString(content.length)); request.addHeader("Content-Type", jsonGenerator.getContentType()); } catch (Throwable t) { throw new AmazonClientException( "Unable to marshall request to JSON: " + t.getMessage(), t); } return request; } }
flofreud/aws-sdk-java
aws-java-sdk-ecr/src/main/java/com/amazonaws/services/ecr/model/transform/ListImagesRequestMarshaller.java
Java
apache-2.0
3,745
/** * 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. */ var App = require('app'); // This logic is substituted by MainAdminView for now. App.MainAdminMenuView = Em.CollectionView.extend({ //contentBinding: 'controller', /*content: [ { route:'user', label:'Users' }, { route:'security', label:'Security' }, { route:'cluster', label:'Cluster' } /*, { route:'authentication', label:'Authentication' }, { route: 'user', label: 'Users' }, { route: 'security', label: 'Security' }/*, { route:'authentication', label:'Authentication' }, { route:'audit', label:'Audit' }*/ /*, { route:'advanced', label:'Advanced' } ], tagName: "ul", classNames: ["nav", "nav-list"], init: function () { this._super(); this.activateView(); // default selected menu }, activateView: function () { var route = App.get('router.mainAdminController.category'); $.each(this._childViews, function () { this.set('active', (this.get('content.route') == route ? "active" : "")); }); }.observes('App.router.mainAdminController.category'), itemViewClass:Em.View.extend({ classNameBindings:["active"], active:"", template:Ember.Handlebars.compile('<a class="text-center" {{action adminNavigate view.content.route }} href="#"> {{unbound view.content.label}}</a>') }) */ });
telefonicaid/fiware-cosmos-ambari
ambari-web/app/views/main/admin/menu.js
JavaScript
apache-2.0
2,238
package uk.co.blackpepper.bowman; import java.io.IOException; import java.lang.reflect.Modifier; import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.Links; import org.springframework.hateoas.RepresentationModel; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.BeanProperty; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.deser.ContextualDeserializer; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import com.fasterxml.jackson.databind.node.ObjectNode; import javassist.util.proxy.ProxyFactory; class ResourceDeserializer extends StdDeserializer<EntityModel<?>> implements ContextualDeserializer { private static final long serialVersionUID = -7290132544264448620L; private TypeResolver typeResolver; private Configuration configuration; ResourceDeserializer(Class<?> type, TypeResolver typeResolver, Configuration configuration) { super(type); this.typeResolver = typeResolver; this.configuration = configuration; } @Override public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) { Class<?> resourceContentType = ctxt.getContextualType().getBindings().getTypeParameters().get(0).getRawClass(); return new ResourceDeserializer(resourceContentType, typeResolver, configuration); } @Override public EntityModel<?> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { ObjectNode node = p.readValueAs(ObjectNode.class); ObjectMapper mapper = (ObjectMapper) p.getCodec(); RepresentationModel resource = mapper.convertValue(node, RepresentationModel.class); Links links = Links.of(resource.getLinks()); Object content = mapper.convertValue(node, getResourceDeserializationType(links)); return new EntityModel<>(content, links); } TypeResolver getTypeResolver() { return typeResolver; } Configuration getConfiguration() { return configuration; } private Class<?> getResourceDeserializationType(Links links) { Class<?> resourceContentType = typeResolver.resolveType(handledType(), links, configuration); if (resourceContentType.isInterface()) { ProxyFactory factory = new ProxyFactory(); factory.setInterfaces(new Class[] {resourceContentType}); resourceContentType = factory.createClass(); } else if (Modifier.isAbstract(resourceContentType.getModifiers())) { ProxyFactory factory = new ProxyFactory(); factory.setSuperclass(resourceContentType); resourceContentType = factory.createClass(); } return resourceContentType; } }
BlackPepperSoftware/hal-client
client/src/main/java/uk/co/blackpepper/bowman/ResourceDeserializer.java
Java
apache-2.0
2,736
/// <reference path="fourslash.ts" /> //// /*1*/15 / /*2*/Math.min(61 / /*3*/42, 32 / 15) / /*4*/15; goTo.marker("1"); verify.not.quickInfoIs("RegExp"); goTo.marker("2"); verify.not.quickInfoIs("RegExp"); goTo.marker("3"); verify.not.quickInfoIs("RegExp"); goTo.marker("4"); verify.not.quickInfoIs("RegExp");
jonathanmarvens/typescript
tests/cases/fourslash/regexDetection.ts
TypeScript
apache-2.0
311
/* * Copyright (C) 2015, 程序亦非猿 * * 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 app.logic.live.view; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.annotation.TargetApi; import android.content.Context; import android.graphics.PointF; import android.graphics.drawable.Drawable; import android.os.Build; import android.util.AttributeSet; import android.view.View; import android.view.animation.AccelerateDecelerateInterpolator; import android.view.animation.AccelerateInterpolator; import android.view.animation.DecelerateInterpolator; import android.view.animation.Interpolator; import android.view.animation.LinearInterpolator; import android.widget.ImageView; import android.widget.RelativeLayout; import java.util.Random; import app.yy.geju.R; public class PeriscopeLayout extends RelativeLayout { //插值器(view 动画时使用的) private Interpolator line = new LinearInterpolator();//线性 private Interpolator acc = new AccelerateInterpolator();//加速 private Interpolator dce = new DecelerateInterpolator();//减速 private Interpolator accdec = new AccelerateDecelerateInterpolator();//先加速后减速 private Interpolator[] interpolators; private int mHeight; private int mWidth; private LayoutParams lp; private Drawable[] drawables; private Random random = new Random(); //随机数类 private int dHeight; private int dWidth; public PeriscopeLayout(Context context) { super(context); init(); } public PeriscopeLayout(Context context, AttributeSet attrs) { super(context, attrs); init(); } public PeriscopeLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public PeriscopeLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(); } private void init() { //初始化显示的图片 drawables = new Drawable[3]; Drawable red = getResources().getDrawable(R.drawable.pl_red); Drawable yellow = getResources().getDrawable(R.drawable.pl_yellow); Drawable blue = getResources().getDrawable(R.drawable.pl_blue); drawables[0] = red; drawables[1] = yellow; drawables[2] = blue; //获取图的宽高 用于后面的计算 //注意 我这里3张图片的大小都是一样的,所以我只取了一个 dHeight = red.getIntrinsicHeight(); dWidth = red.getIntrinsicWidth(); //底部 并且 水平居中 lp = new LayoutParams(dWidth, dHeight); lp.addRule(CENTER_HORIZONTAL, TRUE);//这里的TRUE 要注意 不是true (水平居中) lp.addRule(ALIGN_PARENT_BOTTOM, TRUE); // (底部) // 初始化插补器 interpolators = new Interpolator[4]; interpolators[0] = line; //线性的 interpolators[1] = acc; //加速 interpolators[2] = dce; //减速 interpolators[3] = accdec; //先加后减 } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); mWidth = getMeasuredWidth(); mHeight = getMeasuredHeight(); } /** * 外部调用 */ public void addHeart() { ImageView imageView = new ImageView(getContext()); //随机选一个 imageView.setImageDrawable(drawables[random.nextInt(3)]); imageView.setLayoutParams(lp); addView(imageView); Animator set = getAnimator(imageView); set.addListener(new AnimEndListener(imageView)); set.start(); } /** * 获取一个动画 * @param target * @return */ private Animator getAnimator(View target) { AnimatorSet set = getEnterAnimtor(target); ValueAnimator bezierValueAnimator = getBezierValueAnimator(target); AnimatorSet finalSet = new AnimatorSet(); finalSet.playSequentially(set); finalSet.playSequentially(set, bezierValueAnimator); finalSet.setInterpolator(interpolators[random.nextInt(4)]); finalSet.setTarget(target); return finalSet; } private AnimatorSet getEnterAnimtor(final View target) { ObjectAnimator alpha = ObjectAnimator.ofFloat(target, View.ALPHA, 0.2f, 1f); ObjectAnimator scaleX = ObjectAnimator.ofFloat(target, View.SCALE_X, 0.2f, 1f); ObjectAnimator scaleY = ObjectAnimator.ofFloat(target, View.SCALE_Y, 0.2f, 1f); AnimatorSet enter = new AnimatorSet(); enter.setDuration(500); enter.setInterpolator(new LinearInterpolator()); enter.playTogether(alpha, scaleX, scaleY); enter.setTarget(target); return enter; } private ValueAnimator getBezierValueAnimator(View target) { //初始化一个贝塞尔计算器- - 传入 BezierEvaluator evaluator = new BezierEvaluator(getPointF(2), getPointF(1)); //这里最好画个图 理解一下 传入了起点 和 终点 ValueAnimator animator = ValueAnimator.ofObject(evaluator, new PointF((mWidth - dWidth) / 2, mHeight - dHeight), new PointF(random.nextInt(getWidth()), 0)); animator.addUpdateListener(new BezierListener(target)); animator.setTarget(target); animator.setDuration(3000); return animator; } /** * 获取中间的两个 点 * * @param scale */ private PointF getPointF(int scale) { PointF pointF = new PointF(); pointF.x = random.nextInt((mWidth - 100));//减去100 是为了控制 x轴活动范围,看效果 随意~~ //再Y轴上 为了确保第二个点 在第一个点之上,我把Y分成了上下两半 这样动画效果好一些 也可以用其他方法 pointF.y = random.nextInt((mHeight - 100)) / scale; return pointF; } /** * 爱心的路线 */ private class BezierListener implements ValueAnimator.AnimatorUpdateListener { private View target; public BezierListener(View target) { this.target = target; } @Override public void onAnimationUpdate(ValueAnimator animation) { //这里获取到贝塞尔曲线计算出来的的x y值 赋值给view 这样就能让爱心随着曲线走啦 PointF pointF = (PointF) animation.getAnimatedValue(); target.setX(pointF.x); target.setY(pointF.y); // 这里顺便做一个alpha动画 target.setAlpha(1 - animation.getAnimatedFraction()); } } /** * 爱心动画监听 */ private class AnimEndListener extends AnimatorListenerAdapter { private View target; public AnimEndListener(View target) { this.target = target; } @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); //因为不停的add 导致子view数量只增不减,所以在view动画结束后remove掉 removeView((target)); } } }
Zhangsongsong/GraduationPro
毕业设计/code/android/YYFramework/src/app/logic/live/view/PeriscopeLayout.java
Java
apache-2.0
7,978
/* * Copyright 2016-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <folly/experimental/JemallocNodumpAllocator.h> #include <folly/io/IOBuf.h> #include <folly/memory/Malloc.h> #include <folly/portability/GTest.h> TEST(JemallocNodumpAllocatorTest, Basic) { folly::JemallocNodumpAllocator jna; #ifdef FOLLY_JEMALLOC_NODUMP_ALLOCATOR_SUPPORTED if (folly::usingJEMalloc()) { EXPECT_NE(0, jna.getArenaIndex()); } #endif // FOLLY_JEMALLOC_NODUMP_ALLOCATOR_SUPPORTED auto ptr = jna.allocate(1024); EXPECT_NE(nullptr, ptr); jna.deallocate(ptr); } TEST(JemallocNodumpAllocatorTest, IOBuf) { folly::JemallocNodumpAllocator jna; #ifdef FOLLY_JEMALLOC_NODUMP_ALLOCATOR_SUPPORTED if (folly::usingJEMalloc()) { EXPECT_NE(0, jna.getArenaIndex()); } #endif // FOLLY_JEMALLOC_NODUMP_ALLOCATOR_SUPPORTED const size_t size{1024}; void* ptr = jna.allocate(size); EXPECT_NE(nullptr, ptr); folly::IOBuf ioBuf(folly::IOBuf::TAKE_OWNERSHIP, ptr, size); EXPECT_EQ(size, ioBuf.capacity()); EXPECT_EQ(ptr, ioBuf.data()); uint8_t* data = ioBuf.writableData(); EXPECT_EQ(ptr, data); for (auto i = 0u; i < ioBuf.capacity(); ++i) { data[i] = 'A'; } uint8_t* p = static_cast<uint8_t*> (ptr); for (auto i = 0u; i < size; ++i) { EXPECT_EQ('A', p[i]); } }
rklabs/folly
folly/experimental/test/JemallocNodumpAllocatorTest.cpp
C++
apache-2.0
1,834
/* Copyright (c) 2007 Cyrus Daboo. 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. */ // Header for CEditIdentitySecurity class #ifndef __CEDITIDENTITYSECURITY__MULBERRY__ #define __CEDITIDENTITYSECURITY__MULBERRY__ #include "CPrefsTabSubPanel.h" #include "cdstring.h" #include <LListener.h> // Constants // Panes const PaneIDT paneid_EditIdentitySecurity = 5111; const PaneIDT paneid_EditIdentitySecurityActive = 'ACTI'; const PaneIDT paneid_EditIdentitySecurityGroup1 = 'GRP1'; const PaneIDT paneid_EditIdentitySign = 'SIGN'; const PaneIDT paneid_EditIdentityEncrypt = 'ENCR'; const PaneIDT paneid_EditIdentitySignWith = 'WITH'; const PaneIDT paneid_EditIdentitySignOther = 'OTHE'; // Mesages const MessageT msg_EditIdentitySecurityActive = 'ACTI'; const MessageT msg_EditIdentitySignWith = 'WITH'; // Resources const ResIDT RidL_CEditIdentitySecurityBtns = 5111; // Classes class LCheckBox; class LCheckBoxGroupBox; class LPopupButton; class CTextFieldX; class CEditIdentitySecurity : public CPrefsTabSubPanel, public LListener { private: LCheckBoxGroupBox* mActive; LCheckBox* mSign; LCheckBox* mEncrypt; LPopupButton* mSignWithPopup; CTextFieldX* mSignOther; public: enum { class_ID = 'Iese' }; CEditIdentitySecurity(); CEditIdentitySecurity(LStream *inStream); virtual ~CEditIdentitySecurity(); protected: virtual void FinishCreateSelf(void); // Do odds & ends public: virtual void ListenToMessage(MessageT inMessage, void *ioParam); // Respond to clicks in the buttons virtual void SetData(void* data); // Set data virtual void UpdateData(void* data); // Force update of data }; #endif
mbert/mulberry-main
MacOS/Sources/Application/Preferences_Dialog/Edit_Identities/CEditIdentitySecurity.h
C
apache-2.0
2,227
/* dlapack.f -- translated by f2c (version of 20 August 1993 13:15:44). You must link the resulting object file with the libraries: -lf2c -lm (in that order) */ #include "f2c.h" /* Table of constant values */ static integer c__1 = 1; static doublereal c_b21 = 0.; static doublereal c_b22 = 1.; static integer c__2 = 2; static integer c_n1 = -1; static integer c__3 = 3; static doublereal c_b211 = -1.; /* Subroutine */ int dsyev_(jobz, uplo, n, a, lda, w, work, lwork, info, jobz_len, uplo_len) char *jobz, *uplo; integer *n; doublereal *a; integer *lda; doublereal *w, *work; integer *lwork, *info; ftnlen jobz_len; ftnlen uplo_len; { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2; doublereal d__1; /* Builtin functions */ double sqrt(); /* Local variables */ static integer inde; static doublereal anrm; static integer imax; static doublereal rmin, rmax; static integer lopt, j; extern /* Subroutine */ int dscal_(); static doublereal sigma; extern logical lsame_(); static integer iinfo; static logical lower, wantz; extern doublereal dlamch_(); static integer iscale; static doublereal safmin; extern /* Subroutine */ int xerbla_(); static doublereal bignum; static integer indtau; extern /* Subroutine */ int dsterf_(); extern doublereal dlansy_(); static integer indwrk; extern /* Subroutine */ int dorgtr_(), dsteqr_(), dsytrd_(); static integer llwork; static doublereal smlnum, eps; /* -- LAPACK driver routine (version 1.1) -- */ /* Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., */ /* Courant Institute, Argonne National Lab, and Rice University */ /* March 31, 1993 */ /* .. Scalar Arguments .. */ /* .. */ /* .. Array Arguments .. */ /* .. */ /* Purpose */ /* ======= */ /* DSYEV computes all eigenvalues and, optionally, eigenvectors of a */ /* real symmetric matrix A. */ /* Arguments */ /* ========= */ /* JOBZ (input) CHARACTER*1 */ /* = 'N': Compute eigenvalues only; */ /* = 'V': Compute eigenvalues and eigenvectors. */ /* UPLO (input) CHARACTER*1 */ /* = 'U': Upper triangle of A is stored; */ /* = 'L': Lower triangle of A is stored. */ /* N (input) INTEGER */ /* The order of the matrix A. N >= 0. */ /* A (input/output) DOUBLE PRECISION array, dimension (LDA, N) */ /* On entry, the symmetric matrix A. If UPLO = 'U', the */ /* leading N-by-N upper triangular part of A contains the */ /* upper triangular part of the matrix A. If UPLO = 'L', */ /* the leading N-by-N lower triangular part of A contains */ /* the lower triangular part of the matrix A. */ /* On exit, if JOBZ = 'V', then if INFO = 0, A contains the */ /* orthonormal eigenvectors of the matrix A. */ /* If JOBZ = 'N', then on exit the lower triangle (if UPLO='L') */ /* or the upper triangle (if UPLO='U') of A, including the */ /* diagonal, is destroyed. */ /* LDA (input) INTEGER */ /* The leading dimension of the array A. LDA >= max(1,N). */ /* W (output) DOUBLE PRECISION array, dimension (N) */ /* If INFO = 0, the eigenvalues in ascending order. */ /* WORK (workspace) DOUBLE PRECISION array, dimension (LWORK) */ /* On exit, if INFO = 0, WORK(1) returns the optimal LWORK. */ /* LWORK (input) INTEGER */ /* The length of the array WORK. LWORK >= max(1,3*N-1). */ /* For optimal efficiency, LWORK >= (NB+2)*N, */ /* where NB is the blocksize for DSYTRD returned by ILAENV. */ /* INFO (output) INTEGER */ /* = 0: successful exit */ /* < 0: if INFO = -i, the i-th argument had an illegal value */ /* > 0: if INFO = i, the algorithm failed to converge; i */ /* off-diagonal elements of an intermediate tridiagonal */ /* form did not converge to zero. */ /* ===================================================================== */ /* .. Parameters .. */ /* .. */ /* .. Local Scalars .. */ /* .. */ /* .. External Functions .. */ /* .. */ /* .. External Subroutines .. */ /* .. */ /* .. Intrinsic Functions .. */ /* .. */ /* .. Executable Statements .. */ /* Test the input parameters. */ /* Parameter adjustments */ --work; --w; a_dim1 = *lda; a_offset = a_dim1 + 1; a -= a_offset; /* Function Body */ wantz = lsame_(jobz, "V", 1L, 1L); lower = lsame_(uplo, "L", 1L, 1L); *info = 0; if(!(wantz || lsame_(jobz, "N", 1L, 1L))) { *info = -1; } else if(!(lower || lsame_(uplo, "U", 1L, 1L))) { *info = -2; } else if(*n < 0) { *info = -3; } else if(*lda < max(1, *n)) { *info = -5; } else /* if(complicated condition) */ { /* Computing MAX */ i__1 = 1, i__2 = *n * 3 - 1; if(*lwork < max(i__1, i__2)) { *info = -8; } } if(*info != 0) { i__1 = -(*info); xerbla_("DSYEV ", &i__1, 6L); return 0; } /* Quick return if possible */ if(*n == 0) { work[1] = 1.; return 0; } if(*n == 1) { w[1] = a[a_dim1 + 1]; work[1] = 3.; if(wantz) { a[a_dim1 + 1] = 1.; } return 0; } /* Get machine constants. */ safmin = dlamch_("Safe minimum", 12L); eps = dlamch_("Precision", 9L); smlnum = safmin / eps; bignum = 1. / smlnum; rmin = sqrt(smlnum); rmax = sqrt(bignum); /* Scale matrix to allowable range, if necessary. */ anrm = dlansy_("M", uplo, n, &a[a_offset], lda, &work[1], 1L, 1L); iscale = 0; if(anrm > 0. && anrm < rmin) { iscale = 1; sigma = rmin / anrm; } else if(anrm > rmax) { iscale = 1; sigma = rmax / anrm; } if(iscale == 1) { if(lower) { i__1 = *n; for(j = 1; j <= i__1; ++j) { i__2 = *n - j + 1; dscal_(&i__2, &sigma, &a[j + j * a_dim1], &c__1); /* L10: */ } } else { i__1 = *n; for(j = 1; j <= i__1; ++j) { dscal_(&j, &sigma, &a[j * a_dim1 + 1], &c__1); /* L20: */ } } } /* Call DSYTRD to reduce symmetric matrix to tridiagonal form. */ inde = 1; indtau = inde + *n; indwrk = indtau + *n; llwork = *lwork - indwrk + 1; dsytrd_(uplo, n, &a[a_offset], lda, &w[1], &work[inde], &work[indtau], & work[indwrk], &llwork, &iinfo, 1L); lopt = (integer)((*n << 1) + work[indwrk]); /* For eigenvalues only, call DSTERF. For eigenvectors, first call */ /* DORGTR to generate the orthogonal matrix, then call DSTEQR. */ if(! wantz) { dsterf_(n, &w[1], &work[inde], info); } else { dorgtr_(uplo, n, &a[a_offset], lda, &work[indtau], &work[indwrk], & llwork, &iinfo, 1L); dsteqr_(jobz, n, &w[1], &work[inde], &a[a_offset], lda, &work[indtau], info, 1L); } /* If matrix was scaled, then rescale eigenvalues appropriately. */ if(iscale == 1) { if(*info == 0) { imax = *n; } else { imax = *info - 1; } d__1 = 1. / sigma; dscal_(&imax, &d__1, &w[1], &c__1); } /* Set WORK(1) to optimal workspace size. */ /* Computing MAX */ i__1 = *n * 3 - 1; work[1] = (doublereal) max(i__1, lopt); return 0; /* End of DSYEV */ } /* dsyev_ */ /* Subroutine */ int dsteqr_(compz, n, d, e, z, ldz, work, info, compz_len) char *compz; integer *n; doublereal *d, *e, *z; integer *ldz; doublereal *work; integer *info; ftnlen compz_len; { /* System generated locals */ integer z_dim1, z_offset, i__1, i__2; doublereal d__1, d__2; /* Builtin functions */ double d_sign(); /* Local variables */ static integer lend, jtot; extern /* Subroutine */ int dlae2_(); static doublereal b, c, f, g; static integer i, j, k, l, m; static doublereal p, r, s; extern logical lsame_(); extern /* Subroutine */ int dlasr_(), dswap_(); static integer l1; extern /* Subroutine */ int dlaev2_(); static integer lendm1, lendp1; extern doublereal dlapy2_(); static integer ii; extern doublereal dlamch_(); static integer mm; extern /* Subroutine */ int dlartg_(), xerbla_(), dlazro_(); static integer nmaxit, icompz, lm1, mm1, nm1; static doublereal rt1, rt2, eps, tst; /* -- LAPACK routine (version 1.1) -- */ /* Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., */ /* Courant Institute, Argonne National Lab, and Rice University */ /* March 31, 1993 */ /* .. Scalar Arguments .. */ /* .. */ /* .. Array Arguments .. */ /* .. */ /* Purpose */ /* ======= */ /* DSTEQR computes all eigenvalues and, optionally, eigenvectors of a */ /* symmetric tridiagonal matrix using the implicit QL or QR method. */ /* The eigenvectors of a full or band symmetric matrix can also be found */ /* if DSYTRD or DSPTRD or DSBTRD has been used to reduce this matrix to */ /* tridiagonal form. */ /* Arguments */ /* ========= */ /* COMPZ (input) CHARACTER*1 */ /* = 'N': Compute eigenvalues only. */ /* = 'V': Compute eigenvalues and eigenvectors of the original */ /* symmetric matrix. On entry, Z must contain the */ /* orthogonal matrix used to reduce the original matrix */ /* to tridiagonal form. */ /* = 'I': Compute eigenvalues and eigenvectors of the */ /* tridiagonal matrix. Z is initialized to the identity */ /* matrix. */ /* N (input) INTEGER */ /* The order of the matrix. N >= 0. */ /* D (input/output) DOUBLE PRECISION array, dimension (N) */ /* On entry, the diagonal elements of the tridiagonal matrix. */ /* On exit, if INFO = 0, the eigenvalues in ascending order. */ /* E (input/output) DOUBLE PRECISION array, dimension (N-1) */ /* On entry, the (n-1) subdiagonal elements of the tridiagonal */ /* matrix. */ /* On exit, E has been destroyed. */ /* Z (input/output) DOUBLE PRECISION array, dimension (LDZ, N) */ /* On entry, if COMPZ = 'V', then Z contains the orthogonal */ /* matrix used in the reduction to tridiagonal form. */ /* On exit, if COMPZ = 'V', Z contains the orthonormal */ /* eigenvectors of the original symmetric matrix, and if */ /* COMPZ = 'I', Z contains the orthonormal eigenvectors of */ /* the symmetric tridiagonal matrix. If an error exit is */ /* made, Z contains the eigenvectors associated with the */ /* stored eigenvalues. */ /* If COMPZ = 'N', then Z is not referenced. */ /* LDZ (input) INTEGER */ /* The leading dimension of the array Z. LDZ >= 1, and if */ /* eigenvectors are desired, then LDZ >= max(1,N). */ /* WORK (workspace) DOUBLE PRECISION array, dimension (max(1,2*N-2)) */ /* If COMPZ = 'N', then WORK is not referenced. */ /* INFO (output) INTEGER */ /* = 0: successful exit */ /* < 0: if INFO = -i, the i-th argument had an illegal value */ /* > 0: the algorithm has failed to find all the eigenvalues in */ /* a total of 30*N iterations; if INFO = i, then i */ /* elements of E have not converged to zero; on exit, D */ /* and E contain the elements of a symmetric tridiagonal */ /* matrix which is orthogonally similar to the original */ /* matrix. */ /* ===================================================================== */ /* .. Parameters .. */ /* .. */ /* .. Local Scalars .. */ /* .. */ /* .. External Functions .. */ /* .. */ /* .. External Subroutines .. */ /* .. */ /* .. Intrinsic Functions .. */ /* .. */ /* .. Executable Statements .. */ /* Test the input parameters. */ /* Parameter adjustments */ --work; z_dim1 = *ldz; z_offset = z_dim1 + 1; z -= z_offset; --e; --d; /* Function Body */ *info = 0; if(lsame_(compz, "N", 1L, 1L)) { icompz = 0; } else if(lsame_(compz, "V", 1L, 1L)) { icompz = 1; } else if(lsame_(compz, "I", 1L, 1L)) { icompz = 2; } else { icompz = -1; } if(icompz < 0) { *info = -1; } else if(*n < 0) { *info = -2; } else if(*ldz < 1 || icompz > 0 && *ldz < max(1, *n)) { *info = -6; } if(*info != 0) { i__1 = -(*info); xerbla_("DSTEQR", &i__1, 6L); return 0; } /* Quick return if possible */ if(*n == 0) { return 0; } if(*n == 1) { if(icompz > 0) { z[z_dim1 + 1] = 1.; } return 0; } /* Determine the unit roundoff for this environment. */ eps = dlamch_("E", 1L); /* Compute the eigenvalues and eigenvectors of the tridiagonal */ /* matrix. */ if(icompz == 2) { dlazro_(n, n, &c_b21, &c_b22, &z[z_offset], ldz); } nmaxit = *n * 30; jtot = 0; /* Determine where the matrix splits and choose QL or QR iteration */ /* for each block, according to whether top or bottom diagonal */ /* element is smaller. */ l1 = 1; nm1 = *n - 1; L10: if(l1 > *n) { goto L160; } if(l1 > 1) { e[l1 - 1] = 0.; } if(l1 <= nm1) { i__1 = nm1; for(m = l1; m <= i__1; ++m) { tst = (d__1 = e[m], abs(d__1)); if(tst <= eps * ((d__1 = d[m], abs(d__1)) + (d__2 = d[m + 1], abs(d__2)))) { goto L30; } /* L20: */ } } m = *n; L30: l = l1; lend = m; if((d__1 = d[lend], abs(d__1)) < (d__2 = d[l], abs(d__2))) { l = lend; lend = l1; } l1 = m + 1; if(lend >= l) { /* QL Iteration */ /* Look for small subdiagonal element. */ L40: if(l != lend) { lendm1 = lend - 1; i__1 = lendm1; for(m = l; m <= i__1; ++m) { tst = (d__1 = e[m], abs(d__1)); if(tst <= eps * ((d__1 = d[m], abs(d__1)) + (d__2 = d[m + 1], abs(d__2)))) { goto L60; } /* L50: */ } } m = lend; L60: if(m < lend) { e[m] = 0.; } p = d[l]; if(m == l) { goto L80; } /* If remaining matrix is 2-by-2, use DLAE2 or DLAEV2 */ /* to compute its eigensystem. */ if(m == l + 1) { if(icompz > 0) { dlaev2_(&d[l], &e[l], &d[l + 1], &rt1, &rt2, &c, &s); work[l] = c; work[*n - 1 + l] = s; dlasr_("R", "V", "B", n, &c__2, &work[l], &work[*n - 1 + l], & z[l * z_dim1 + 1], ldz, 1L, 1L, 1L); } else { dlae2_(&d[l], &e[l], &d[l + 1], &rt1, &rt2); } d[l] = rt1; d[l + 1] = rt2; e[l] = 0.; l += 2; if(l <= lend) { goto L40; } goto L10; } if(jtot == nmaxit) { goto L140; } ++jtot; /* Form shift. */ g = (d[l + 1] - p) / (e[l] * 2.); r = dlapy2_(&g, &c_b22); g = d[m] - p + e[l] / (g + d_sign(&r, &g)); s = 1.; c = 1.; p = 0.; /* Inner loop */ mm1 = m - 1; i__1 = l; for(i = mm1; i >= i__1; --i) { f = s * e[i]; b = c * e[i]; dlartg_(&g, &f, &c, &s, &r); if(i != m - 1) { e[i + 1] = r; } g = d[i + 1] - p; r = (d[i] - g) * s + c * 2. * b; p = s * r; d[i + 1] = g + p; g = c * r - b; /* If eigenvectors are desired, then save rotations. */ if(icompz > 0) { work[i] = c; work[*n - 1 + i] = -s; } /* L70: */ } /* If eigenvectors are desired, then apply saved rotations. */ if(icompz > 0) { mm = m - l + 1; dlasr_("R", "V", "B", n, &mm, &work[l], &work[*n - 1 + l], &z[l * z_dim1 + 1], ldz, 1L, 1L, 1L); } d[l] -= p; e[l] = g; goto L40; /* Eigenvalue found. */ L80: d[l] = p; ++l; if(l <= lend) { goto L40; } goto L10; } else { /* QR Iteration */ /* Look for small superdiagonal element. */ L90: if(l != lend) { lendp1 = lend + 1; i__1 = lendp1; for(m = l; m >= i__1; --m) { tst = (d__1 = e[m - 1], abs(d__1)); if(tst <= eps * ((d__1 = d[m], abs(d__1)) + (d__2 = d[m - 1], abs(d__2)))) { goto L110; } /* L100: */ } } m = lend; L110: if(m > lend) { e[m - 1] = 0.; } p = d[l]; if(m == l) { goto L130; } /* If remaining matrix is 2-by-2, use DLAE2 or DLAEV2 */ /* to compute its eigensystem. */ if(m == l - 1) { if(icompz > 0) { dlaev2_(&d[l - 1], &e[l - 1], &d[l], &rt1, &rt2, &c, &s); work[m] = c; work[*n - 1 + m] = s; dlasr_("R", "V", "F", n, &c__2, &work[m], &work[*n - 1 + m], & z[(l - 1) * z_dim1 + 1], ldz, 1L, 1L, 1L); } else { dlae2_(&d[l - 1], &e[l - 1], &d[l], &rt1, &rt2); } d[l - 1] = rt1; d[l] = rt2; e[l - 1] = 0.; l += -2; if(l >= lend) { goto L90; } goto L10; } if(jtot == nmaxit) { goto L140; } ++jtot; /* Form shift. */ g = (d[l - 1] - p) / (e[l - 1] * 2.); r = dlapy2_(&g, &c_b22); g = d[m] - p + e[l - 1] / (g + d_sign(&r, &g)); s = 1.; c = 1.; p = 0.; /* Inner loop */ lm1 = l - 1; i__1 = lm1; for(i = m; i <= i__1; ++i) { f = s * e[i]; b = c * e[i]; dlartg_(&g, &f, &c, &s, &r); if(i != m) { e[i - 1] = r; } g = d[i] - p; r = (d[i + 1] - g) * s + c * 2. * b; p = s * r; d[i] = g + p; g = c * r - b; /* If eigenvectors are desired, then save rotations. */ if(icompz > 0) { work[i] = c; work[*n - 1 + i] = s; } /* L120: */ } /* If eigenvectors are desired, then apply saved rotations. */ if(icompz > 0) { mm = l - m + 1; dlasr_("R", "V", "F", n, &mm, &work[m], &work[*n - 1 + m], &z[m * z_dim1 + 1], ldz, 1L, 1L, 1L); } d[l] -= p; e[lm1] = g; goto L90; /* Eigenvalue found. */ L130: d[l] = p; --l; if(l >= lend) { goto L90; } goto L10; } /* Set error -- no convergence to an eigenvalue after a total */ /* of N*MAXIT iterations. */ L140: i__1 = *n - 1; for(i = 1; i <= i__1; ++i) { if(e[i] != 0.) { ++(*info); } /* L150: */ } return 0; /* Order eigenvalues and eigenvectors. */ L160: i__1 = *n; for(ii = 2; ii <= i__1; ++ii) { i = ii - 1; k = i; p = d[i]; i__2 = *n; for(j = ii; j <= i__2; ++j) { if(d[j] < p) { k = j; p = d[j]; } /* L170: */ } if(k != i) { d[k] = d[i]; d[i] = p; if(icompz > 0) { dswap_(n, &z[i * z_dim1 + 1], &c__1, &z[k * z_dim1 + 1], & c__1); } } /* L180: */ } return 0; /* End of DSTEQR */ } /* dsteqr_ */ /* Subroutine */ int dlartg_(f, g, cs, sn, r) doublereal *f, *g, *cs, *sn, *r; { /* Builtin functions */ double sqrt(); /* Local variables */ static doublereal t, tt; /* -- LAPACK auxiliary routine (version 1.1) -- */ /* Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., */ /* Courant Institute, Argonne National Lab, and Rice University */ /* October 31, 1992 */ /* .. Scalar Arguments .. */ /* .. */ /* Purpose */ /* ======= */ /* DLARTG generate a plane rotation so that */ /* [ CS SN ] . [ F ] = [ R ] where CS**2 + SN**2 = 1. */ /* [ -SN CS ] [ G ] [ 0 ] */ /* This is a faster version of the BLAS1 routine DROTG, except for */ /* the following differences: */ /* F and G are unchanged on return. */ /* If G=0, then CS=1 and SN=0. */ /* If F=0 and (G .ne. 0), then CS=0 and SN=1 without doing any */ /* floating point operations (saves work in DBDSQR when */ /* there are zeros on the diagonal). */ /* Arguments */ /* ========= */ /* F (input) DOUBLE PRECISION */ /* The first component of vector to be rotated. */ /* G (input) DOUBLE PRECISION */ /* The second component of vector to be rotated. */ /* CS (output) DOUBLE PRECISION */ /* The cosine of the rotation. */ /* SN (output) DOUBLE PRECISION */ /* The sine of the rotation. */ /* R (output) DOUBLE PRECISION */ /* The nonzero component of the rotated vector. */ /* ===================================================================== */ /* .. Parameters .. */ /* .. */ /* .. Local Scalars .. */ /* .. */ /* .. Intrinsic Functions .. */ /* .. */ /* .. Executable Statements .. */ if(*g == 0.) { *cs = 1.; *sn = 0.; *r = *f; } else if(*f == 0.) { *cs = 0.; *sn = 1.; *r = *g; } else { if(abs(*f) > abs(*g)) { t = *g / *f; tt = sqrt(t * t + 1.); *cs = 1. / tt; *sn = t * *cs; *r = *f * tt; } else { t = *f / *g; tt = sqrt(t * t + 1.); *sn = 1. / tt; *cs = t * *sn; *r = *g * tt; } } return 0; /* End of DLARTG */ } /* dlartg_ */ /* Subroutine */ int dlasr_(side, pivot, direct, m, n, c, s, a, lda, side_len, pivot_len, direct_len) char *side, *pivot, *direct; integer *m, *n; doublereal *c, *s, *a; integer *lda; ftnlen side_len; ftnlen pivot_len; ftnlen direct_len; { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2; /* Local variables */ static integer info; static doublereal temp; static integer i, j; extern logical lsame_(); static doublereal ctemp, stemp; extern /* Subroutine */ int xerbla_(); /* -- LAPACK auxiliary routine (version 1.1) -- */ /* Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., */ /* Courant Institute, Argonne National Lab, and Rice University */ /* October 31, 1992 */ /* .. Scalar Arguments .. */ /* .. */ /* .. Array Arguments .. */ /* .. */ /* Purpose */ /* ======= */ /* DLASR performs the transformation */ /* A := P*A, when SIDE = 'L' or 'l' ( Left-hand side ) */ /* A := A*P', when SIDE = 'R' or 'r' ( Right-hand side ) */ /* where A is an m by n real matrix and P is an orthogonal matrix, */ /* consisting of a sequence of plane rotations determined by the */ /* parameters PIVOT and DIRECT as follows ( z = m when SIDE = 'L' or 'l' */ /* and z = n when SIDE = 'R' or 'r' ): */ /* When DIRECT = 'F' or 'f' ( Forward sequence ) then */ /* P = P( z - 1 )*...*P( 2 )*P( 1 ), */ /* and when DIRECT = 'B' or 'b' ( Backward sequence ) then */ /* P = P( 1 )*P( 2 )*...*P( z - 1 ), */ /* where P( k ) is a plane rotation matrix for the following planes: */ /* when PIVOT = 'V' or 'v' ( Variable pivot ), */ /* the plane ( k, k + 1 ) */ /* when PIVOT = 'T' or 't' ( Top pivot ), */ /* the plane ( 1, k + 1 ) */ /* when PIVOT = 'B' or 'b' ( Bottom pivot ), */ /* the plane ( k, z ) */ /* c( k ) and s( k ) must contain the cosine and sine that define the */ /* matrix P( k ). The two by two plane rotation part of the matrix */ /* P( k ), R( k ), is assumed to be of the form */ /* R( k ) = ( c( k ) s( k ) ). */ /* ( -s( k ) c( k ) ) */ /* This version vectorises across rows of the array A when SIDE = 'L'. */ /* Arguments */ /* ========= */ /* SIDE (input) CHARACTER*1 */ /* Specifies whether the plane rotation matrix P is applied to */ /* A on the left or the right. */ /* = 'L': Left, compute A := P*A */ /* = 'R': Right, compute A:= A*P' */ /* DIRECT (input) CHARACTER*1 */ /* Specifies whether P is a forward or backward sequence of */ /* plane rotations. */ /* = 'F': Forward, P = P( z - 1 )*...*P( 2 )*P( 1 ) */ /* = 'B': Backward, P = P( 1 )*P( 2 )*...*P( z - 1 ) */ /* PIVOT (input) CHARACTER*1 */ /* Specifies the plane for which P(k) is a plane rotation */ /* matrix. */ /* = 'V': Variable pivot, the plane (k,k+1) */ /* = 'T': Top pivot, the plane (1,k+1) */ /* = 'B': Bottom pivot, the plane (k,z) */ /* M (input) INTEGER */ /* The number of rows of the matrix A. If m <= 1, an immediate */ /* return is effected. */ /* N (input) INTEGER */ /* The number of columns of the matrix A. If n <= 1, an */ /* immediate return is effected. */ /* C, S (input) DOUBLE PRECISION arrays, dimension */ /* (M-1) if SIDE = 'L' */ /* (N-1) if SIDE = 'R' */ /* c(k) and s(k) contain the cosine and sine that define the */ /* matrix P(k). The two by two plane rotation part of the */ /* matrix P(k), R(k), is assumed to be of the form */ /* R( k ) = ( c( k ) s( k ) ). */ /* ( -s( k ) c( k ) ) */ /* A (input/output) DOUBLE PRECISION array, dimension (LDA,N) */ /* The m by n matrix A. On exit, A is overwritten by P*A if */ /* SIDE = 'R' or by A*P' if SIDE = 'L'. */ /* LDA (input) INTEGER */ /* The leading dimension of the array A. LDA >= max(1,M). */ /* ===================================================================== */ /* .. Parameters .. */ /* .. */ /* .. Local Scalars .. */ /* .. */ /* .. External Functions .. */ /* .. */ /* .. External Subroutines .. */ /* .. */ /* .. Intrinsic Functions .. */ /* .. */ /* .. Executable Statements .. */ /* Test the input parameters */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = a_dim1 + 1; a -= a_offset; --s; --c; /* Function Body */ info = 0; if(!(lsame_(side, "L", 1L, 1L) || lsame_(side, "R", 1L, 1L))) { info = 1; } else if(!(lsame_(pivot, "V", 1L, 1L) || lsame_(pivot, "T", 1L, 1L) || lsame_(pivot, "B", 1L, 1L))) { info = 2; } else if(!(lsame_(direct, "F", 1L, 1L) || lsame_(direct, "B", 1L, 1L))) { info = 3; } else if(*m < 0) { info = 4; } else if(*n < 0) { info = 5; } else if(*lda < max(1, *m)) { info = 9; } if(info != 0) { xerbla_("DLASR ", &info, 6L); return 0; } /* Quick return if possible */ if(*m == 0 || *n == 0) { return 0; } if(lsame_(side, "L", 1L, 1L)) { /* Form P * A */ if(lsame_(pivot, "V", 1L, 1L)) { if(lsame_(direct, "F", 1L, 1L)) { i__1 = *m - 1; for(j = 1; j <= i__1; ++j) { ctemp = c[j]; stemp = s[j]; if(ctemp != 1. || stemp != 0.) { i__2 = *n; for(i = 1; i <= i__2; ++i) { temp = a[j + 1 + i * a_dim1]; a[j + 1 + i * a_dim1] = ctemp * temp - stemp * a[ j + i * a_dim1]; a[j + i * a_dim1] = stemp * temp + ctemp * a[j + i * a_dim1]; /* L10: */ } } /* L20: */ } } else if(lsame_(direct, "B", 1L, 1L)) { for(j = *m - 1; j >= 1; --j) { ctemp = c[j]; stemp = s[j]; if(ctemp != 1. || stemp != 0.) { i__1 = *n; for(i = 1; i <= i__1; ++i) { temp = a[j + 1 + i * a_dim1]; a[j + 1 + i * a_dim1] = ctemp * temp - stemp * a[ j + i * a_dim1]; a[j + i * a_dim1] = stemp * temp + ctemp * a[j + i * a_dim1]; /* L30: */ } } /* L40: */ } } } else if(lsame_(pivot, "T", 1L, 1L)) { if(lsame_(direct, "F", 1L, 1L)) { i__1 = *m; for(j = 2; j <= i__1; ++j) { ctemp = c[j - 1]; stemp = s[j - 1]; if(ctemp != 1. || stemp != 0.) { i__2 = *n; for(i = 1; i <= i__2; ++i) { temp = a[j + i * a_dim1]; a[j + i * a_dim1] = ctemp * temp - stemp * a[i * a_dim1 + 1]; a[i * a_dim1 + 1] = stemp * temp + ctemp * a[i * a_dim1 + 1]; /* L50: */ } } /* L60: */ } } else if(lsame_(direct, "B", 1L, 1L)) { for(j = *m; j >= 2; --j) { ctemp = c[j - 1]; stemp = s[j - 1]; if(ctemp != 1. || stemp != 0.) { i__1 = *n; for(i = 1; i <= i__1; ++i) { temp = a[j + i * a_dim1]; a[j + i * a_dim1] = ctemp * temp - stemp * a[i * a_dim1 + 1]; a[i * a_dim1 + 1] = stemp * temp + ctemp * a[i * a_dim1 + 1]; /* L70: */ } } /* L80: */ } } } else if(lsame_(pivot, "B", 1L, 1L)) { if(lsame_(direct, "F", 1L, 1L)) { i__1 = *m - 1; for(j = 1; j <= i__1; ++j) { ctemp = c[j]; stemp = s[j]; if(ctemp != 1. || stemp != 0.) { i__2 = *n; for(i = 1; i <= i__2; ++i) { temp = a[j + i * a_dim1]; a[j + i * a_dim1] = stemp * a[*m + i * a_dim1] + ctemp * temp; a[*m + i * a_dim1] = ctemp * a[*m + i * a_dim1] - stemp * temp; /* L90: */ } } /* L100: */ } } else if(lsame_(direct, "B", 1L, 1L)) { for(j = *m - 1; j >= 1; --j) { ctemp = c[j]; stemp = s[j]; if(ctemp != 1. || stemp != 0.) { i__1 = *n; for(i = 1; i <= i__1; ++i) { temp = a[j + i * a_dim1]; a[j + i * a_dim1] = stemp * a[*m + i * a_dim1] + ctemp * temp; a[*m + i * a_dim1] = ctemp * a[*m + i * a_dim1] - stemp * temp; /* L110: */ } } /* L120: */ } } } } else if(lsame_(side, "R", 1L, 1L)) { /* Form A * P' */ if(lsame_(pivot, "V", 1L, 1L)) { if(lsame_(direct, "F", 1L, 1L)) { i__1 = *n - 1; for(j = 1; j <= i__1; ++j) { ctemp = c[j]; stemp = s[j]; if(ctemp != 1. || stemp != 0.) { i__2 = *m; for(i = 1; i <= i__2; ++i) { temp = a[i + (j + 1) * a_dim1]; a[i + (j + 1) * a_dim1] = ctemp * temp - stemp * a[i + j * a_dim1]; a[i + j * a_dim1] = stemp * temp + ctemp * a[i + j * a_dim1]; /* L130: */ } } /* L140: */ } } else if(lsame_(direct, "B", 1L, 1L)) { for(j = *n - 1; j >= 1; --j) { ctemp = c[j]; stemp = s[j]; if(ctemp != 1. || stemp != 0.) { i__1 = *m; for(i = 1; i <= i__1; ++i) { temp = a[i + (j + 1) * a_dim1]; a[i + (j + 1) * a_dim1] = ctemp * temp - stemp * a[i + j * a_dim1]; a[i + j * a_dim1] = stemp * temp + ctemp * a[i + j * a_dim1]; /* L150: */ } } /* L160: */ } } } else if(lsame_(pivot, "T", 1L, 1L)) { if(lsame_(direct, "F", 1L, 1L)) { i__1 = *n; for(j = 2; j <= i__1; ++j) { ctemp = c[j - 1]; stemp = s[j - 1]; if(ctemp != 1. || stemp != 0.) { i__2 = *m; for(i = 1; i <= i__2; ++i) { temp = a[i + j * a_dim1]; a[i + j * a_dim1] = ctemp * temp - stemp * a[i + a_dim1]; a[i + a_dim1] = stemp * temp + ctemp * a[i + a_dim1]; /* L170: */ } } /* L180: */ } } else if(lsame_(direct, "B", 1L, 1L)) { for(j = *n; j >= 2; --j) { ctemp = c[j - 1]; stemp = s[j - 1]; if(ctemp != 1. || stemp != 0.) { i__1 = *m; for(i = 1; i <= i__1; ++i) { temp = a[i + j * a_dim1]; a[i + j * a_dim1] = ctemp * temp - stemp * a[i + a_dim1]; a[i + a_dim1] = stemp * temp + ctemp * a[i + a_dim1]; /* L190: */ } } /* L200: */ } } } else if(lsame_(pivot, "B", 1L, 1L)) { if(lsame_(direct, "F", 1L, 1L)) { i__1 = *n - 1; for(j = 1; j <= i__1; ++j) { ctemp = c[j]; stemp = s[j]; if(ctemp != 1. || stemp != 0.) { i__2 = *m; for(i = 1; i <= i__2; ++i) { temp = a[i + j * a_dim1]; a[i + j * a_dim1] = stemp * a[i + *n * a_dim1] + ctemp * temp; a[i + *n * a_dim1] = ctemp * a[i + *n * a_dim1] - stemp * temp; /* L210: */ } } /* L220: */ } } else if(lsame_(direct, "B", 1L, 1L)) { for(j = *n - 1; j >= 1; --j) { ctemp = c[j]; stemp = s[j]; if(ctemp != 1. || stemp != 0.) { i__1 = *m; for(i = 1; i <= i__1; ++i) { temp = a[i + j * a_dim1]; a[i + j * a_dim1] = stemp * a[i + *n * a_dim1] + ctemp * temp; a[i + *n * a_dim1] = ctemp * a[i + *n * a_dim1] - stemp * temp; /* L230: */ } } /* L240: */ } } } } return 0; /* End of DLASR */ } /* dlasr_ */ /* Subroutine */ int dlaev2_(a, b, c, rt1, rt2, cs1, sn1) doublereal *a, *b, *c, *rt1, *rt2, *cs1, *sn1; { /* System generated locals */ doublereal d__1; /* Builtin functions */ double sqrt(); /* Local variables */ static doublereal acmn, acmx, ab, df, cs, ct, tb, sm, tn, rt, adf, acs; static integer sgn1, sgn2; /* -- LAPACK auxiliary routine (version 1.1) -- */ /* Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., */ /* Courant Institute, Argonne National Lab, and Rice University */ /* October 31, 1992 */ /* .. Scalar Arguments .. */ /* .. */ /* Purpose */ /* ======= */ /* DLAEV2 computes the eigendecomposition of a 2-by-2 symmetric matrix */ /* [ A B ] */ /* [ B C ]. */ /* On return, RT1 is the eigenvalue of larger absolute value, RT2 is the */ /* eigenvalue of smaller absolute value, and (CS1,SN1) is the unit right */ /* eigenvector for RT1, giving the decomposition */ /* [ CS1 SN1 ] [ A B ] [ CS1 -SN1 ] = [ RT1 0 ] */ /* [-SN1 CS1 ] [ B C ] [ SN1 CS1 ] [ 0 RT2 ]. */ /* Arguments */ /* ========= */ /* A (input) DOUBLE PRECISION */ /* The (1,1) entry of the 2-by-2 matrix. */ /* B (input) DOUBLE PRECISION */ /* The (1,2) entry and the conjugate of the (2,1) entry of the */ /* 2-by-2 matrix. */ /* C (input) DOUBLE PRECISION */ /* The (2,2) entry of the 2-by-2 matrix. */ /* RT1 (output) DOUBLE PRECISION */ /* The eigenvalue of larger absolute value. */ /* RT2 (output) DOUBLE PRECISION */ /* The eigenvalue of smaller absolute value. */ /* CS1 (output) DOUBLE PRECISION */ /* SN1 (output) DOUBLE PRECISION */ /* The vector (CS1, SN1) is a unit right eigenvector for RT1. */ /* Further Details */ /* =============== */ /* RT1 is accurate to a few ulps barring over/underflow. */ /* RT2 may be inaccurate if there is massive cancellation in the */ /* determinant A*C-B*B; higher precision or correctly rounded or */ /* correctly truncated arithmetic would be needed to compute RT2 */ /* accurately in all cases. */ /* CS1 and SN1 are accurate to a few ulps barring over/underflow. */ /* Overflow is possible only if RT1 is within a factor of 5 of overflow. */ /* Underflow is harmless if the input data is 0 or exceeds */ /* underflow_threshold / macheps. */ /* ===================================================================== */ /* .. Parameters .. */ /* .. */ /* .. Local Scalars .. */ /* .. */ /* .. Intrinsic Functions .. */ /* .. */ /* .. Executable Statements .. */ /* Compute the eigenvalues */ sm = *a + *c; df = *a - *c; adf = abs(df); tb = *b + *b; ab = abs(tb); if(abs(*a) > abs(*c)) { acmx = *a; acmn = *c; } else { acmx = *c; acmn = *a; } if(adf > ab) { /* Computing 2nd power */ d__1 = ab / adf; rt = adf * sqrt(d__1 * d__1 + 1.); } else if(adf < ab) { /* Computing 2nd power */ d__1 = adf / ab; rt = ab * sqrt(d__1 * d__1 + 1.); } else { /* Includes case AB=ADF=0 */ rt = ab * sqrt(2.); } if(sm < 0.) { *rt1 = (sm - rt) * .5; sgn1 = -1; /* Order of execution important. */ /* To get fully accurate smaller eigenvalue, */ /* next line needs to be executed in higher precision. */ *rt2 = acmx / *rt1 * acmn - *b / *rt1 * *b; } else if(sm > 0.) { *rt1 = (sm + rt) * .5; sgn1 = 1; /* Order of execution important. */ /* To get fully accurate smaller eigenvalue, */ /* next line needs to be executed in higher precision. */ *rt2 = acmx / *rt1 * acmn - *b / *rt1 * *b; } else { /* Includes case RT1 = RT2 = 0 */ *rt1 = rt * .5; *rt2 = rt * -.5; sgn1 = 1; } /* Compute the eigenvector */ if(df >= 0.) { cs = df + rt; sgn2 = 1; } else { cs = df - rt; sgn2 = -1; } acs = abs(cs); if(acs > ab) { ct = -tb / cs; *sn1 = 1. / sqrt(ct * ct + 1.); *cs1 = ct * *sn1; } else { if(ab == 0.) { *cs1 = 1.; *sn1 = 0.; } else { tn = -cs / tb; *cs1 = 1. / sqrt(tn * tn + 1.); *sn1 = tn * *cs1; } } if(sgn1 == sgn2) { tn = *cs1; *cs1 = -(*sn1); *sn1 = tn; } return 0; /* End of DLAEV2 */ } /* dlaev2_ */ /* Subroutine */ int dlazro_(m, n, alpha, beta, a, lda) integer *m, *n; doublereal *alpha, *beta, *a; integer *lda; { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2; /* Local variables */ static integer i, j; /* -- LAPACK auxiliary routine (version 1.1) -- */ /* Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., */ /* Courant Institute, Argonne National Lab, and Rice University */ /* October 31, 1992 */ /* .. Scalar Arguments .. */ /* .. */ /* .. Array Arguments .. */ /* .. */ /* Purpose */ /* ======= */ /* DLAZRO initializes a 2-D array A to BETA on the diagonal and */ /* ALPHA on the offdiagonals. */ /* Arguments */ /* ========= */ /* M (input) INTEGER */ /* The number of rows of the matrix A. M >= 0. */ /* N (input) INTEGER */ /* The number of columns of the matrix A. N >= 0. */ /* ALPHA (input) DOUBLE PRECISION */ /* The constant to which the offdiagonal elements are to be set. */ /* BETA (input) DOUBLE PRECISION */ /* The constant to which the diagonal elements are to be set. */ /* A (output) DOUBLE PRECISION array, dimension (LDA,N) */ /* On exit, the leading m by n submatrix of A is set such that */ /* A(i,j) = ALPHA, 1 <= i <= m, 1 <= j <= n, i <> j */ /* A(i,i) = BETA, 1 <= i <= min(m,n). */ /* LDA (input) INTEGER */ /* The leading dimension of the array A. LDA >= max(1,M). */ /* ===================================================================== */ /* .. Local Scalars .. */ /* .. */ /* .. Intrinsic Functions .. */ /* .. */ /* .. Executable Statements .. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = a_dim1 + 1; a -= a_offset; /* Function Body */ i__1 = *n; for(j = 1; j <= i__1; ++j) { i__2 = *m; for(i = 1; i <= i__2; ++i) { a[i + j * a_dim1] = *alpha; /* L10: */ } /* L20: */ } i__1 = min(*m, *n); for(i = 1; i <= i__1; ++i) { a[i + i * a_dim1] = *beta; /* L30: */ } return 0; /* End of DLAZRO */ } /* dlazro_ */ /* Subroutine */ int dorgtr_(uplo, n, a, lda, tau, work, lwork, info, uplo_len) char *uplo; integer *n; doublereal *a; integer *lda; doublereal *tau, *work; integer *lwork, *info; ftnlen uplo_len; { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; /* Local variables */ static integer i, j; extern logical lsame_(); static integer iinfo; static logical upper; extern /* Subroutine */ int xerbla_(), dorgql_(), dorgqr_(); /* -- LAPACK routine (version 1.1) -- */ /* Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., */ /* Courant Institute, Argonne National Lab, and Rice University */ /* March 31, 1993 */ /* .. Scalar Arguments .. */ /* .. */ /* .. Array Arguments .. */ /* .. */ /* Purpose */ /* ======= */ /* DORGTR generates a real orthogonal matrix Q which is defined as the */ /* product of n-1 elementary reflectors of order N, as returned by */ /* DSYTRD: */ /* if UPLO = 'U', Q = H(n-1) . . . H(2) H(1), */ /* if UPLO = 'L', Q = H(1) H(2) . . . H(n-1). */ /* Arguments */ /* ========= */ /* UPLO (input) CHARACTER*1 */ /* = 'U': Upper triangle of A contains elementary reflectors */ /* from DSYTRD; */ /* = 'L': Lower triangle of A contains elementary reflectors */ /* from DSYTRD. */ /* N (input) INTEGER */ /* The order of the matrix Q. N >= 0. */ /* A (input/output) DOUBLE PRECISION array, dimension (LDA,N) */ /* On entry, the vectors which define the elementary reflectors, */ /* as returned by DSYTRD. */ /* On exit, the N-by-N orthogonal matrix Q. */ /* LDA (input) INTEGER */ /* The leading dimension of the array A. LDA >= max(1,N). */ /* TAU (input) DOUBLE PRECISION array, dimension (N-1) */ /* TAU(i) must contain the scalar factor of the elementary */ /* reflector H(i), as returned by DSYTRD. */ /* WORK (workspace) DOUBLE PRECISION array, dimension (LWORK) */ /* On exit, if INFO = 0, WORK(1) returns the optimal LWORK. */ /* LWORK (input) INTEGER */ /* The dimension of the array WORK. LWORK >= max(1,N-1). */ /* For optimum performance LWORK >= (N-1)*NB, where NB is */ /* the optimal blocksize. */ /* INFO (output) INTEGER */ /* = 0: successful exit */ /* < 0: if INFO = -i, the i-th argument had an illegal value */ /* ===================================================================== */ /* .. Parameters .. */ /* .. */ /* .. Local Scalars .. */ /* .. */ /* .. External Functions .. */ /* .. */ /* .. External Subroutines .. */ /* .. */ /* .. Intrinsic Functions .. */ /* .. */ /* .. Executable Statements .. */ /* Test the input arguments */ /* Parameter adjustments */ --work; --tau; a_dim1 = *lda; a_offset = a_dim1 + 1; a -= a_offset; /* Function Body */ *info = 0; upper = lsame_(uplo, "U", 1L, 1L); if(! upper && ! lsame_(uplo, "L", 1L, 1L)) { *info = -1; } else if(*n < 0) { *info = -2; } else if(*lda < max(1, *n)) { *info = -4; } else /* if(complicated condition) */ { /* Computing MAX */ i__1 = 1, i__2 = *n - 1; if(*lwork < max(i__1, i__2)) { *info = -7; } } if(*info != 0) { i__1 = -(*info); xerbla_("DORGTR", &i__1, 6L); return 0; } /* Quick return if possible */ if(*n == 0) { work[1] = 1.; return 0; } if(upper) { /* Q was determined by a call to DSYTRD with UPLO = 'U' */ /* Shift the vectors which define the elementary reflectors one */ /* column to the left, and set the last row and column of Q to */ /* those of the unit matrix */ i__1 = *n - 1; for(j = 1; j <= i__1; ++j) { i__2 = j - 1; for(i = 1; i <= i__2; ++i) { a[i + j * a_dim1] = a[i + (j + 1) * a_dim1]; /* L10: */ } a[*n + j * a_dim1] = 0.; /* L20: */ } i__1 = *n - 1; for(i = 1; i <= i__1; ++i) { a[i + *n * a_dim1] = 0.; /* L30: */ } a[*n + *n * a_dim1] = 1.; /* Generate Q(1:n-1,1:n-1) */ i__1 = *n - 1; i__2 = *n - 1; i__3 = *n - 1; dorgql_(&i__1, &i__2, &i__3, &a[a_offset], lda, &tau[1], &work[1], lwork, &iinfo); } else { /* Q was determined by a call to DSYTRD with UPLO = 'L'. */ /* Shift the vectors which define the elementary reflectors one */ /* column to the right, and set the first row and column of Q t o */ /* those of the unit matrix */ for(j = *n; j >= 2; --j) { a[j * a_dim1 + 1] = 0.; i__1 = *n; for(i = j + 1; i <= i__1; ++i) { a[i + j * a_dim1] = a[i + (j - 1) * a_dim1]; /* L40: */ } /* L50: */ } a[a_dim1 + 1] = 1.; i__1 = *n; for(i = 2; i <= i__1; ++i) { a[i + a_dim1] = 0.; /* L60: */ } if(*n > 1) { /* Generate Q(2:n,2:n) */ i__1 = *n - 1; i__2 = *n - 1; i__3 = *n - 1; dorgqr_(&i__1, &i__2, &i__3, &a[(a_dim1 << 1) + 2], lda, &tau[1], &work[1], lwork, &iinfo); } } return 0; /* End of DORGTR */ } /* dorgtr_ */ /* Subroutine */ int dorgqr_(m, n, k, a, lda, tau, work, lwork, info) integer *m, *n, *k; doublereal *a; integer *lda; doublereal *tau, *work; integer *lwork, *info; { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; /* Local variables */ static integer i, j, l, nbmin, iinfo; extern /* Subroutine */ int dorg2r_(); static integer ib, nb, ki, kk; extern /* Subroutine */ int dlarfb_(); static integer nx; extern /* Subroutine */ int dlarft_(), xerbla_(); extern integer ilaenv_(); static integer ldwork, iws; /* -- LAPACK routine (version 1.1) -- */ /* Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., */ /* Courant Institute, Argonne National Lab, and Rice University */ /* March 31, 1993 */ /* .. Scalar Arguments .. */ /* .. */ /* .. Array Arguments .. */ /* .. */ /* Purpose */ /* ======= */ /* DORGQR generates an M-by-N real matrix Q with orthonormal columns, */ /* which is defined as the first N columns of a product of K elementary */ /* reflectors of order M */ /* Q = H(1) H(2) . . . H(k) */ /* as returned by DGEQRF. */ /* Arguments */ /* ========= */ /* M (input) INTEGER */ /* The number of rows of the matrix Q. M >= 0. */ /* N (input) INTEGER */ /* The number of columns of the matrix Q. M >= N >= 0. */ /* K (input) INTEGER */ /* The number of elementary reflectors whose product defines the */ /* matrix Q. N >= K >= 0. */ /* A (input/output) DOUBLE PRECISION array, dimension (LDA,N) */ /* On entry, the i-th column must contain the vector which */ /* defines the elementary reflector H(i), for i = 1,2,...,k, as */ /* returned by DGEQRF in the first k columns of its array */ /* argument A. */ /* On exit, the M-by-N matrix Q. */ /* LDA (input) INTEGER */ /* The first dimension of the array A. LDA >= max(1,M). */ /* TAU (input) DOUBLE PRECISION array, dimension (K) */ /* TAU(i) must contain the scalar factor of the elementary */ /* reflector H(i), as returned by DGEQRF. */ /* WORK (workspace) DOUBLE PRECISION array, dimension (LWORK) */ /* On exit, if INFO = 0, WORK(1) returns the optimal LWORK. */ /* LWORK (input) INTEGER */ /* The dimension of the array WORK. LWORK >= max(1,N). */ /* For optimum performance LWORK >= N*NB, where NB is the */ /* optimal blocksize. */ /* INFO (output) INTEGER */ /* = 0: successful exit */ /* < 0: if INFO = -i, the i-th argument has an illegal value */ /* ===================================================================== */ /* .. Parameters .. */ /* .. */ /* .. Local Scalars .. */ /* .. */ /* .. External Subroutines .. */ /* .. */ /* .. Intrinsic Functions .. */ /* .. */ /* .. External Functions .. */ /* .. */ /* .. Executable Statements .. */ /* Test the input arguments */ /* Parameter adjustments */ --work; --tau; a_dim1 = *lda; a_offset = a_dim1 + 1; a -= a_offset; /* Function Body */ *info = 0; if(*m < 0) { *info = -1; } else if(*n < 0 || *n > *m) { *info = -2; } else if(*k < 0 || *k > *n) { *info = -3; } else if(*lda < max(1, *m)) { *info = -5; } else if(*lwork < max(1, *n)) { *info = -8; } if(*info != 0) { i__1 = -(*info); xerbla_("DORGQR", &i__1, 6L); return 0; } /* Quick return if possible */ if(*n <= 0) { work[1] = 1.; return 0; } /* Determine the block size. */ nb = ilaenv_(&c__1, "DORGQR", " ", m, n, k, &c_n1, 6L, 1L); nbmin = 2; nx = 0; iws = *n; if(nb > 1 && nb < *k) { /* Determine when to cross over from blocked to unblocked code. */ /* Computing MAX */ i__1 = 0, i__2 = ilaenv_(&c__3, "DORGQR", " ", m, n, k, &c_n1, 6L, 1L) ; nx = max(i__1, i__2); if(nx < *k) { /* Determine if workspace is large enough for blocked co de. */ ldwork = *n; iws = ldwork * nb; if(*lwork < iws) { /* Not enough workspace to use optimal NB: reduc e NB and */ /* determine the minimum value of NB. */ nb = *lwork / ldwork; /* Computing MAX */ i__1 = 2, i__2 = ilaenv_(&c__2, "DORGQR", " ", m, n, k, &c_n1, 6L, 1L); nbmin = max(i__1, i__2); } } } if(nb >= nbmin && nb < *k && nx < *k) { /* Use blocked code after the last block. */ /* The first kk columns are handled by the block method. */ ki = (*k - nx - 1) / nb * nb; /* Computing MIN */ i__1 = *k, i__2 = ki + nb; kk = min(i__1, i__2); /* Set A(1:kk,kk+1:n) to zero. */ i__1 = *n; for(j = kk + 1; j <= i__1; ++j) { i__2 = kk; for(i = 1; i <= i__2; ++i) { a[i + j * a_dim1] = 0.; /* L10: */ } /* L20: */ } } else { kk = 0; } /* Use unblocked code for the last or only block. */ if(kk < *n) { i__1 = *m - kk; i__2 = *n - kk; i__3 = *k - kk; dorg2r_(&i__1, &i__2, &i__3, &a[kk + 1 + (kk + 1) * a_dim1], lda, & tau[kk + 1], &work[1], &iinfo); } if(kk > 0) { /* Use blocked code */ i__1 = -nb; for(i = ki + 1; i__1 < 0 ? i >= 1 : i <= 1; i += i__1) { /* Computing MIN */ i__2 = nb, i__3 = *k - i + 1; ib = min(i__2, i__3); if(i + ib <= *n) { /* Form the triangular factor of the block reflec tor */ /* H = H(i) H(i+1) . . . H(i+ib-1) */ i__2 = *m - i + 1; dlarft_("Forward", "Columnwise", &i__2, &ib, &a[i + i * a_dim1], lda, &tau[i], &work[1], &ldwork, 7L, 10L); /* Apply H to A(i:m,i+ib:n) from the left */ i__2 = *m - i + 1; i__3 = *n - i - ib + 1; dlarfb_("Left", "No transpose", "Forward", "Columnwise", & i__2, &i__3, &ib, &a[i + i * a_dim1], lda, &work[1], & ldwork, &a[i + (i + ib) * a_dim1], lda, &work[ib + 1], &ldwork, 4L, 12L, 7L, 10L); } /* Apply H to rows i:m of current block */ i__2 = *m - i + 1; dorg2r_(&i__2, &ib, &ib, &a[i + i * a_dim1], lda, &tau[i], &work[ 1], &iinfo); /* Set rows 1:i-1 of current block to zero */ i__2 = i + ib - 1; for(j = i; j <= i__2; ++j) { i__3 = i - 1; for(l = 1; l <= i__3; ++l) { a[l + j * a_dim1] = 0.; /* L30: */ } /* L40: */ } /* L50: */ } } work[1] = (doublereal) iws; return 0; /* End of DORGQR */ } /* dorgqr_ */ /* Subroutine */ int dorg2r_(m, n, k, a, lda, tau, work, info) integer *m, *n, *k; doublereal *a; integer *lda; doublereal *tau, *work; integer *info; { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2; doublereal d__1; /* Local variables */ static integer i, j, l; extern /* Subroutine */ int dscal_(), dlarf_(), xerbla_(); /* -- LAPACK routine (version 1.1) -- */ /* Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., */ /* Courant Institute, Argonne National Lab, and Rice University */ /* February 29, 1992 */ /* .. Scalar Arguments .. */ /* .. */ /* .. Array Arguments .. */ /* .. */ /* Purpose */ /* ======= */ /* DORG2R generates an m by n real matrix Q with orthonormal columns, */ /* which is defined as the first n columns of a product of k elementary */ /* reflectors of order m */ /* Q = H(1) H(2) . . . H(k) */ /* as returned by DGEQRF. */ /* Arguments */ /* ========= */ /* M (input) INTEGER */ /* The number of rows of the matrix Q. M >= 0. */ /* N (input) INTEGER */ /* The number of columns of the matrix Q. M >= N >= 0. */ /* K (input) INTEGER */ /* The number of elementary reflectors whose product defines the */ /* matrix Q. N >= K >= 0. */ /* A (input/output) DOUBLE PRECISION array, dimension (LDA,N) */ /* On entry, the i-th column must contain the vector which */ /* defines the elementary reflector H(i), for i = 1,2,...,k, as */ /* returned by DGEQRF in the first k columns of its array */ /* argument A. */ /* On exit, the m-by-n matrix Q. */ /* LDA (input) INTEGER */ /* The first dimension of the array A. LDA >= max(1,M). */ /* TAU (input) DOUBLE PRECISION array, dimension (K) */ /* TAU(i) must contain the scalar factor of the elementary */ /* reflector H(i), as returned by DGEQRF. */ /* WORK (workspace) DOUBLE PRECISION array, dimension (N) */ /* INFO (output) INTEGER */ /* = 0: successful exit */ /* < 0: if INFO = -i, the i-th argument has an illegal value */ /* ===================================================================== */ /* .. Parameters .. */ /* .. */ /* .. Local Scalars .. */ /* .. */ /* .. External Subroutines .. */ /* .. */ /* .. Intrinsic Functions .. */ /* .. */ /* .. Executable Statements .. */ /* Test the input arguments */ /* Parameter adjustments */ --work; --tau; a_dim1 = *lda; a_offset = a_dim1 + 1; a -= a_offset; /* Function Body */ *info = 0; if(*m < 0) { *info = -1; } else if(*n < 0 || *n > *m) { *info = -2; } else if(*k < 0 || *k > *n) { *info = -3; } else if(*lda < max(1, *m)) { *info = -5; } if(*info != 0) { i__1 = -(*info); xerbla_("DORG2R", &i__1, 6L); return 0; } /* Quick return if possible */ if(*n <= 0) { return 0; } /* Initialise columns k+1:n to columns of the unit matrix */ i__1 = *n; for(j = *k + 1; j <= i__1; ++j) { i__2 = *m; for(l = 1; l <= i__2; ++l) { a[l + j * a_dim1] = 0.; /* L10: */ } a[j + j * a_dim1] = 1.; /* L20: */ } for(i = *k; i >= 1; --i) { /* Apply H(i) to A(i:m,i:n) from the left */ if(i < *n) { a[i + i * a_dim1] = 1.; i__1 = *m - i + 1; i__2 = *n - i; dlarf_("Left", &i__1, &i__2, &a[i + i * a_dim1], &c__1, &tau[i], & a[i + (i + 1) * a_dim1], lda, &work[1], 4L); } if(i < *m) { i__1 = *m - i; d__1 = -tau[i]; dscal_(&i__1, &d__1, &a[i + 1 + i * a_dim1], &c__1); } a[i + i * a_dim1] = 1. - tau[i]; /* Set A(1:i-1,i) to zero */ i__1 = i - 1; for(l = 1; l <= i__1; ++l) { a[l + i * a_dim1] = 0.; /* L30: */ } /* L40: */ } return 0; /* End of DORG2R */ } /* dorg2r_ */ /* Subroutine */ int dorgql_(m, n, k, a, lda, tau, work, lwork, info) integer *m, *n, *k; doublereal *a; integer *lda; doublereal *tau, *work; integer *lwork, *info; { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4; /* Local variables */ static integer i, j, l, nbmin, iinfo; extern /* Subroutine */ int dorg2l_(); static integer ib, nb, kk; extern /* Subroutine */ int dlarfb_(); static integer nx; extern /* Subroutine */ int dlarft_(), xerbla_(); extern integer ilaenv_(); static integer ldwork, iws; /* -- LAPACK routine (version 1.1) -- */ /* Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., */ /* Courant Institute, Argonne National Lab, and Rice University */ /* March 31, 1993 */ /* .. Scalar Arguments .. */ /* .. */ /* .. Array Arguments .. */ /* .. */ /* Purpose */ /* ======= */ /* DORGQL generates an M-by-N real matrix Q with orthonormal columns, */ /* which is defined as the last N columns of a product of K elementary */ /* reflectors of order M */ /* Q = H(k) . . . H(2) H(1) */ /* as returned by DGEQLF. */ /* Arguments */ /* ========= */ /* M (input) INTEGER */ /* The number of rows of the matrix Q. M >= 0. */ /* N (input) INTEGER */ /* The number of columns of the matrix Q. M >= N >= 0. */ /* K (input) INTEGER */ /* The number of elementary reflectors whose product defines the */ /* matrix Q. N >= K >= 0. */ /* A (input/output) DOUBLE PRECISION array, dimension (LDA,N) */ /* On entry, the (n-k+i)-th column must contain the vector which */ /* defines the elementary reflector H(i), for i = 1,2,...,k, as */ /* returned by DGEQLF in the last k columns of its array */ /* argument A. */ /* On exit, the M-by-N matrix Q. */ /* LDA (input) INTEGER */ /* The first dimension of the array A. LDA >= max(1,M). */ /* TAU (input) DOUBLE PRECISION array, dimension (K) */ /* TAU(i) must contain the scalar factor of the elementary */ /* reflector H(i), as returned by DGEQLF. */ /* WORK (workspace) DOUBLE PRECISION array, dimension (LWORK) */ /* On exit, if INFO = 0, WORK(1) returns the optimal LWORK. */ /* LWORK (input) INTEGER */ /* The dimension of the array WORK. LWORK >= max(1,N). */ /* For optimum performance LWORK >= N*NB, where NB is the */ /* optimal blocksize. */ /* INFO (output) INTEGER */ /* = 0: successful exit */ /* < 0: if INFO = -i, the i-th argument has an illegal value */ /* ===================================================================== */ /* .. Parameters .. */ /* .. */ /* .. Local Scalars .. */ /* .. */ /* .. External Subroutines .. */ /* .. */ /* .. Intrinsic Functions .. */ /* .. */ /* .. External Functions .. */ /* .. */ /* .. Executable Statements .. */ /* Test the input arguments */ /* Parameter adjustments */ --work; --tau; a_dim1 = *lda; a_offset = a_dim1 + 1; a -= a_offset; /* Function Body */ *info = 0; if(*m < 0) { *info = -1; } else if(*n < 0 || *n > *m) { *info = -2; } else if(*k < 0 || *k > *n) { *info = -3; } else if(*lda < max(1, *m)) { *info = -5; } else if(*lwork < max(1, *n)) { *info = -8; } if(*info != 0) { i__1 = -(*info); xerbla_("DORGQL", &i__1, 6L); return 0; } /* Quick return if possible */ if(*n <= 0) { work[1] = 1.; return 0; } /* Determine the block size. */ nb = ilaenv_(&c__1, "DORGQL", " ", m, n, k, &c_n1, 6L, 1L); nbmin = 2; nx = 0; iws = *n; if(nb > 1 && nb < *k) { /* Determine when to cross over from blocked to unblocked code. */ /* Computing MAX */ i__1 = 0, i__2 = ilaenv_(&c__3, "DORGQL", " ", m, n, k, &c_n1, 6L, 1L) ; nx = max(i__1, i__2); if(nx < *k) { /* Determine if workspace is large enough for blocked co de. */ ldwork = *n; iws = ldwork * nb; if(*lwork < iws) { /* Not enough workspace to use optimal NB: reduc e NB and */ /* determine the minimum value of NB. */ nb = *lwork / ldwork; /* Computing MAX */ i__1 = 2, i__2 = ilaenv_(&c__2, "DORGQL", " ", m, n, k, &c_n1, 6L, 1L); nbmin = max(i__1, i__2); } } } if(nb >= nbmin && nb < *k && nx < *k) { /* Use blocked code after the first block. */ /* The last kk columns are handled by the block method. */ /* Computing MIN */ i__1 = *k, i__2 = (*k - nx + nb - 1) / nb * nb; kk = min(i__1, i__2); /* Set A(m-kk+1:m,1:n-kk) to zero. */ i__1 = *n - kk; for(j = 1; j <= i__1; ++j) { i__2 = *m; for(i = *m - kk + 1; i <= i__2; ++i) { a[i + j * a_dim1] = 0.; /* L10: */ } /* L20: */ } } else { kk = 0; } /* Use unblocked code for the first or only block. */ i__1 = *m - kk; i__2 = *n - kk; i__3 = *k - kk; dorg2l_(&i__1, &i__2, &i__3, &a[a_offset], lda, &tau[1], &work[1], &iinfo) ; if(kk > 0) { /* Use blocked code */ i__1 = *k; i__2 = nb; for(i = *k - kk + 1; i__2 < 0 ? i >= i__1 : i <= i__1; i += i__2) { /* Computing MIN */ i__3 = nb, i__4 = *k - i + 1; ib = min(i__3, i__4); if(*n - *k + i > 1) { /* Form the triangular factor of the block reflec tor */ /* H = H(i+ib-1) . . . H(i+1) H(i) */ i__3 = *m - *k + i + ib - 1; dlarft_("Backward", "Columnwise", &i__3, &ib, &a[(*n - *k + i) * a_dim1 + 1], lda, &tau[i], &work[1], &ldwork, 8L, 10L); /* Apply H to A(1:m-k+i+ib-1,1:n-k+i-1) from the left */ i__3 = *m - *k + i + ib - 1; i__4 = *n - *k + i - 1; dlarfb_("Left", "No transpose", "Backward", "Columnwise", & i__3, &i__4, &ib, &a[(*n - *k + i) * a_dim1 + 1], lda, &work[1], &ldwork, &a[a_offset], lda, &work[ib + 1], &ldwork, 4L, 12L, 8L, 10L); } /* Apply H to rows 1:m-k+i+ib-1 of current block */ i__3 = *m - *k + i + ib - 1; dorg2l_(&i__3, &ib, &ib, &a[(*n - *k + i) * a_dim1 + 1], lda, & tau[i], &work[1], &iinfo); /* Set rows m-k+i+ib:m of current block to zero */ i__3 = *n - *k + i + ib - 1; for(j = *n - *k + i; j <= i__3; ++j) { i__4 = *m; for(l = *m - *k + i + ib; l <= i__4; ++l) { a[l + j * a_dim1] = 0.; /* L30: */ } /* L40: */ } /* L50: */ } } work[1] = (doublereal) iws; return 0; /* End of DORGQL */ } /* dorgql_ */ /* Subroutine */ int dlarfb_(side, trans, direct, storev, m, n, k, v, ldv, t, ldt, c, ldc, work, ldwork, side_len, trans_len, direct_len, storev_len) char *side, *trans, *direct, *storev; integer *m, *n, *k; doublereal *v; integer *ldv; doublereal *t; integer *ldt; doublereal *c; integer *ldc; doublereal *work; integer *ldwork; ftnlen side_len; ftnlen trans_len; ftnlen direct_len; ftnlen storev_len; { /* System generated locals */ integer c_dim1, c_offset, t_dim1, t_offset, v_dim1, v_offset, work_dim1, work_offset, i__1, i__2; /* Local variables */ static integer i, j; extern /* Subroutine */ int dgemm_(); extern logical lsame_(); extern /* Subroutine */ int dcopy_(), dtrmm_(); static char transt[1]; /* -- LAPACK auxiliary routine (version 1.1) -- */ /* Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., */ /* Courant Institute, Argonne National Lab, and Rice University */ /* February 29, 1992 */ /* .. Scalar Arguments .. */ /* .. */ /* .. Array Arguments .. */ /* .. */ /* Purpose */ /* ======= */ /* DLARFB applies a real block reflector H or its transpose H' to a */ /* real m by n matrix C, from either the left or the right. */ /* Arguments */ /* ========= */ /* SIDE (input) CHARACTER*1 */ /* = 'L': apply H or H' from the Left */ /* = 'R': apply H or H' from the Right */ /* TRANS (input) CHARACTER*1 */ /* = 'N': apply H (No transpose) */ /* = 'T': apply H' (Transpose) */ /* DIRECT (input) CHARACTER*1 */ /* Indicates how H is formed from a product of elementary */ /* reflectors */ /* = 'F': H = H(1) H(2) . . . H(k) (Forward) */ /* = 'B': H = H(k) . . . H(2) H(1) (Backward) */ /* STOREV (input) CHARACTER*1 */ /* Indicates how the vectors which define the elementary */ /* reflectors are stored: */ /* = 'C': Columnwise */ /* = 'R': Rowwise */ /* M (input) INTEGER */ /* The number of rows of the matrix C. */ /* N (input) INTEGER */ /* The number of columns of the matrix C. */ /* K (input) INTEGER */ /* The order of the matrix T (= the number of elementary */ /* reflectors whose product defines the block reflector). */ /* V (input) DOUBLE PRECISION array, dimension */ /* (LDV,K) if STOREV = 'C' */ /* (LDV,M) if STOREV = 'R' and SIDE = 'L' */ /* (LDV,N) if STOREV = 'R' and SIDE = 'R' */ /* The matrix V. See further details. */ /* LDV (input) INTEGER */ /* The leading dimension of the array V. */ /* If STOREV = 'C' and SIDE = 'L', LDV >= max(1,M); */ /* if STOREV = 'C' and SIDE = 'R', LDV >= max(1,N); */ /* if STOREV = 'R', LDV >= K. */ /* T (input) DOUBLE PRECISION array, dimension (LDT,K) */ /* The triangular k by k matrix T in the representation of the */ /* block reflector. */ /* LDT (input) INTEGER */ /* The leading dimension of the array T. LDT >= K. */ /* C (input/output) DOUBLE PRECISION array, dimension (LDC,N) */ /* On entry, the m by n matrix C. */ /* On exit, C is overwritten by H*C or H'*C or C*H or C*H'. */ /* LDC (input) INTEGER */ /* The leading dimension of the array C. LDA >= max(1,M). */ /* WORK (workspace) DOUBLE PRECISION array, dimension (LDWORK,K) */ /* LDWORK (input) INTEGER */ /* The leading dimension of the array WORK. */ /* If SIDE = 'L', LDWORK >= max(1,N); */ /* if SIDE = 'R', LDWORK >= max(1,M). */ /* ===================================================================== */ /* .. Parameters .. */ /* .. */ /* .. Local Scalars .. */ /* .. */ /* .. External Functions .. */ /* .. */ /* .. External Subroutines .. */ /* .. */ /* .. Executable Statements .. */ /* Quick return if possible */ /* Parameter adjustments */ work_dim1 = *ldwork; work_offset = work_dim1 + 1; work -= work_offset; c_dim1 = *ldc; c_offset = c_dim1 + 1; c -= c_offset; t_dim1 = *ldt; t_offset = t_dim1 + 1; t -= t_offset; v_dim1 = *ldv; v_offset = v_dim1 + 1; v -= v_offset; /* Function Body */ if(*m <= 0 || *n <= 0) { return 0; } if(lsame_(trans, "N", 1L, 1L)) { *transt = 'T'; } else { *transt = 'N'; } if(lsame_(storev, "C", 1L, 1L)) { if(lsame_(direct, "F", 1L, 1L)) { /* Let V = ( V1 ) (first K rows) */ /* ( V2 ) */ /* where V1 is unit lower triangular. */ if(lsame_(side, "L", 1L, 1L)) { /* Form H * C or H' * C where C = ( C1 ) */ /* ( C2 ) */ /* W := C' * V = (C1'*V1 + C2'*V2) (stored in WORK) */ /* W := C1' */ i__1 = *k; for(j = 1; j <= i__1; ++j) { dcopy_(n, &c[j + c_dim1], ldc, &work[j * work_dim1 + 1], & c__1); /* L10: */ } /* W := W * V1 */ dtrmm_("Right", "Lower", "No transpose", "Unit", n, k, &c_b22, &v[v_offset], ldv, &work[work_offset], ldwork, 5L, 5L, 12L, 4L); if(*m > *k) { /* W := W + C2'*V2 */ i__1 = *m - *k; dgemm_("Transpose", "No transpose", n, k, &i__1, &c_b22, & c[*k + 1 + c_dim1], ldc, &v[*k + 1 + v_dim1], ldv, &c_b22, &work[work_offset], ldwork, 9L, 12L); } /* W := W * T' or W * T */ dtrmm_("Right", "Upper", transt, "Non-unit", n, k, &c_b22, &t[ t_offset], ldt, &work[work_offset], ldwork, 5L, 5L, 1L, 8L); /* C := C - V * W' */ if(*m > *k) { /* C2 := C2 - V2 * W' */ i__1 = *m - *k; dgemm_("No transpose", "Transpose", &i__1, n, k, &c_b211, &v[*k + 1 + v_dim1], ldv, &work[work_offset], ldwork, &c_b22, &c[*k + 1 + c_dim1], ldc, 12L, 9L) ; } /* W := W * V1' */ dtrmm_("Right", "Lower", "Transpose", "Unit", n, k, &c_b22, & v[v_offset], ldv, &work[work_offset], ldwork, 5L, 5L, 9L, 4L); /* C1 := C1 - W' */ i__1 = *k; for(j = 1; j <= i__1; ++j) { i__2 = *n; for(i = 1; i <= i__2; ++i) { c[j + i * c_dim1] -= work[i + j * work_dim1]; /* L20: */ } /* L30: */ } } else if(lsame_(side, "R", 1L, 1L)) { /* Form C * H or C * H' where C = ( C1 C2 ) */ /* W := C * V = (C1*V1 + C2*V2) (stored in WOR K) */ /* W := C1 */ i__1 = *k; for(j = 1; j <= i__1; ++j) { dcopy_(m, &c[j * c_dim1 + 1], &c__1, &work[j * work_dim1 + 1], &c__1); /* L40: */ } /* W := W * V1 */ dtrmm_("Right", "Lower", "No transpose", "Unit", m, k, &c_b22, &v[v_offset], ldv, &work[work_offset], ldwork, 5L, 5L, 12L, 4L); if(*n > *k) { /* W := W + C2 * V2 */ i__1 = *n - *k; dgemm_("No transpose", "No transpose", m, k, &i__1, & c_b22, &c[(*k + 1) * c_dim1 + 1], ldc, &v[*k + 1 + v_dim1], ldv, &c_b22, &work[work_offset], ldwork, 12L, 12L); } /* W := W * T or W * T' */ dtrmm_("Right", "Upper", trans, "Non-unit", m, k, &c_b22, &t[ t_offset], ldt, &work[work_offset], ldwork, 5L, 5L, 1L, 8L); /* C := C - W * V' */ if(*n > *k) { /* C2 := C2 - W * V2' */ i__1 = *n - *k; dgemm_("No transpose", "Transpose", m, &i__1, k, &c_b211, &work[work_offset], ldwork, &v[*k + 1 + v_dim1], ldv, &c_b22, &c[(*k + 1) * c_dim1 + 1], ldc, 12L, 9L); } /* W := W * V1' */ dtrmm_("Right", "Lower", "Transpose", "Unit", m, k, &c_b22, & v[v_offset], ldv, &work[work_offset], ldwork, 5L, 5L, 9L, 4L); /* C1 := C1 - W */ i__1 = *k; for(j = 1; j <= i__1; ++j) { i__2 = *m; for(i = 1; i <= i__2; ++i) { c[i + j * c_dim1] -= work[i + j * work_dim1]; /* L50: */ } /* L60: */ } } } else { /* Let V = ( V1 ) */ /* ( V2 ) (last K rows) */ /* where V2 is unit upper triangular. */ if(lsame_(side, "L", 1L, 1L)) { /* Form H * C or H' * C where C = ( C1 ) */ /* ( C2 ) */ /* W := C' * V = (C1'*V1 + C2'*V2) (stored in WORK) */ /* W := C2' */ i__1 = *k; for(j = 1; j <= i__1; ++j) { dcopy_(n, &c[*m - *k + j + c_dim1], ldc, &work[j * work_dim1 + 1], &c__1); /* L70: */ } /* W := W * V2 */ dtrmm_("Right", "Upper", "No transpose", "Unit", n, k, &c_b22, &v[*m - *k + 1 + v_dim1], ldv, &work[work_offset], ldwork, 5L, 5L, 12L, 4L); if(*m > *k) { /* W := W + C1'*V1 */ i__1 = *m - *k; dgemm_("Transpose", "No transpose", n, k, &i__1, &c_b22, & c[c_offset], ldc, &v[v_offset], ldv, &c_b22, & work[work_offset], ldwork, 9L, 12L); } /* W := W * T' or W * T */ dtrmm_("Right", "Lower", transt, "Non-unit", n, k, &c_b22, &t[ t_offset], ldt, &work[work_offset], ldwork, 5L, 5L, 1L, 8L); /* C := C - V * W' */ if(*m > *k) { /* C1 := C1 - V1 * W' */ i__1 = *m - *k; dgemm_("No transpose", "Transpose", &i__1, n, k, &c_b211, &v[v_offset], ldv, &work[work_offset], ldwork, & c_b22, &c[c_offset], ldc, 12L, 9L); } /* W := W * V2' */ dtrmm_("Right", "Upper", "Transpose", "Unit", n, k, &c_b22, & v[*m - *k + 1 + v_dim1], ldv, &work[work_offset], ldwork, 5L, 5L, 9L, 4L); /* C2 := C2 - W' */ i__1 = *k; for(j = 1; j <= i__1; ++j) { i__2 = *n; for(i = 1; i <= i__2; ++i) { c[*m - *k + j + i * c_dim1] -= work[i + j * work_dim1] ; /* L80: */ } /* L90: */ } } else if(lsame_(side, "R", 1L, 1L)) { /* Form C * H or C * H' where C = ( C1 C2 ) */ /* W := C * V = (C1*V1 + C2*V2) (stored in WOR K) */ /* W := C2 */ i__1 = *k; for(j = 1; j <= i__1; ++j) { dcopy_(m, &c[(*n - *k + j) * c_dim1 + 1], &c__1, &work[j * work_dim1 + 1], &c__1); /* L100: */ } /* W := W * V2 */ dtrmm_("Right", "Upper", "No transpose", "Unit", m, k, &c_b22, &v[*n - *k + 1 + v_dim1], ldv, &work[work_offset], ldwork, 5L, 5L, 12L, 4L); if(*n > *k) { /* W := W + C1 * V1 */ i__1 = *n - *k; dgemm_("No transpose", "No transpose", m, k, &i__1, & c_b22, &c[c_offset], ldc, &v[v_offset], ldv, & c_b22, &work[work_offset], ldwork, 12L, 12L); } /* W := W * T or W * T' */ dtrmm_("Right", "Lower", trans, "Non-unit", m, k, &c_b22, &t[ t_offset], ldt, &work[work_offset], ldwork, 5L, 5L, 1L, 8L); /* C := C - W * V' */ if(*n > *k) { /* C1 := C1 - W * V1' */ i__1 = *n - *k; dgemm_("No transpose", "Transpose", m, &i__1, k, &c_b211, &work[work_offset], ldwork, &v[v_offset], ldv, & c_b22, &c[c_offset], ldc, 12L, 9L); } /* W := W * V2' */ dtrmm_("Right", "Upper", "Transpose", "Unit", m, k, &c_b22, & v[*n - *k + 1 + v_dim1], ldv, &work[work_offset], ldwork, 5L, 5L, 9L, 4L); /* C2 := C2 - W */ i__1 = *k; for(j = 1; j <= i__1; ++j) { i__2 = *m; for(i = 1; i <= i__2; ++i) { c[i + (*n - *k + j) * c_dim1] -= work[i + j * work_dim1]; /* L110: */ } /* L120: */ } } } } else if(lsame_(storev, "R", 1L, 1L)) { if(lsame_(direct, "F", 1L, 1L)) { /* Let V = ( V1 V2 ) (V1: first K columns) */ /* where V1 is unit upper triangular. */ if(lsame_(side, "L", 1L, 1L)) { /* Form H * C or H' * C where C = ( C1 ) */ /* ( C2 ) */ /* W := C' * V' = (C1'*V1' + C2'*V2') (stored i n WORK) */ /* W := C1' */ i__1 = *k; for(j = 1; j <= i__1; ++j) { dcopy_(n, &c[j + c_dim1], ldc, &work[j * work_dim1 + 1], & c__1); /* L130: */ } /* W := W * V1' */ dtrmm_("Right", "Upper", "Transpose", "Unit", n, k, &c_b22, & v[v_offset], ldv, &work[work_offset], ldwork, 5L, 5L, 9L, 4L); if(*m > *k) { /* W := W + C2'*V2' */ i__1 = *m - *k; dgemm_("Transpose", "Transpose", n, k, &i__1, &c_b22, &c[* k + 1 + c_dim1], ldc, &v[(*k + 1) * v_dim1 + 1], ldv, &c_b22, &work[work_offset], ldwork, 9L, 9L); } /* W := W * T' or W * T */ dtrmm_("Right", "Upper", transt, "Non-unit", n, k, &c_b22, &t[ t_offset], ldt, &work[work_offset], ldwork, 5L, 5L, 1L, 8L); /* C := C - V' * W' */ if(*m > *k) { /* C2 := C2 - V2' * W' */ i__1 = *m - *k; dgemm_("Transpose", "Transpose", &i__1, n, k, &c_b211, &v[ (*k + 1) * v_dim1 + 1], ldv, &work[work_offset], ldwork, &c_b22, &c[*k + 1 + c_dim1], ldc, 9L, 9L); } /* W := W * V1 */ dtrmm_("Right", "Upper", "No transpose", "Unit", n, k, &c_b22, &v[v_offset], ldv, &work[work_offset], ldwork, 5L, 5L, 12L, 4L); /* C1 := C1 - W' */ i__1 = *k; for(j = 1; j <= i__1; ++j) { i__2 = *n; for(i = 1; i <= i__2; ++i) { c[j + i * c_dim1] -= work[i + j * work_dim1]; /* L140: */ } /* L150: */ } } else if(lsame_(side, "R", 1L, 1L)) { /* Form C * H or C * H' where C = ( C1 C2 ) */ /* W := C * V' = (C1*V1' + C2*V2') (stored in WORK) */ /* W := C1 */ i__1 = *k; for(j = 1; j <= i__1; ++j) { dcopy_(m, &c[j * c_dim1 + 1], &c__1, &work[j * work_dim1 + 1], &c__1); /* L160: */ } /* W := W * V1' */ dtrmm_("Right", "Upper", "Transpose", "Unit", m, k, &c_b22, & v[v_offset], ldv, &work[work_offset], ldwork, 5L, 5L, 9L, 4L); if(*n > *k) { /* W := W + C2 * V2' */ i__1 = *n - *k; dgemm_("No transpose", "Transpose", m, k, &i__1, &c_b22, & c[(*k + 1) * c_dim1 + 1], ldc, &v[(*k + 1) * v_dim1 + 1], ldv, &c_b22, &work[work_offset], ldwork, 12L, 9L); } /* W := W * T or W * T' */ dtrmm_("Right", "Upper", trans, "Non-unit", m, k, &c_b22, &t[ t_offset], ldt, &work[work_offset], ldwork, 5L, 5L, 1L, 8L); /* C := C - W * V */ if(*n > *k) { /* C2 := C2 - W * V2 */ i__1 = *n - *k; dgemm_("No transpose", "No transpose", m, &i__1, k, & c_b211, &work[work_offset], ldwork, &v[(*k + 1) * v_dim1 + 1], ldv, &c_b22, &c[(*k + 1) * c_dim1 + 1], ldc, 12L, 12L); } /* W := W * V1 */ dtrmm_("Right", "Upper", "No transpose", "Unit", m, k, &c_b22, &v[v_offset], ldv, &work[work_offset], ldwork, 5L, 5L, 12L, 4L); /* C1 := C1 - W */ i__1 = *k; for(j = 1; j <= i__1; ++j) { i__2 = *m; for(i = 1; i <= i__2; ++i) { c[i + j * c_dim1] -= work[i + j * work_dim1]; /* L170: */ } /* L180: */ } } } else { /* Let V = ( V1 V2 ) (V2: last K columns) */ /* where V2 is unit lower triangular. */ if(lsame_(side, "L", 1L, 1L)) { /* Form H * C or H' * C where C = ( C1 ) */ /* ( C2 ) */ /* W := C' * V' = (C1'*V1' + C2'*V2') (stored i n WORK) */ /* W := C2' */ i__1 = *k; for(j = 1; j <= i__1; ++j) { dcopy_(n, &c[*m - *k + j + c_dim1], ldc, &work[j * work_dim1 + 1], &c__1); /* L190: */ } /* W := W * V2' */ dtrmm_("Right", "Lower", "Transpose", "Unit", n, k, &c_b22, & v[(*m - *k + 1) * v_dim1 + 1], ldv, &work[work_offset] , ldwork, 5L, 5L, 9L, 4L); if(*m > *k) { /* W := W + C1'*V1' */ i__1 = *m - *k; dgemm_("Transpose", "Transpose", n, k, &i__1, &c_b22, &c[ c_offset], ldc, &v[v_offset], ldv, &c_b22, &work[ work_offset], ldwork, 9L, 9L); } /* W := W * T' or W * T */ dtrmm_("Right", "Lower", transt, "Non-unit", n, k, &c_b22, &t[ t_offset], ldt, &work[work_offset], ldwork, 5L, 5L, 1L, 8L); /* C := C - V' * W' */ if(*m > *k) { /* C1 := C1 - V1' * W' */ i__1 = *m - *k; dgemm_("Transpose", "Transpose", &i__1, n, k, &c_b211, &v[ v_offset], ldv, &work[work_offset], ldwork, & c_b22, &c[c_offset], ldc, 9L, 9L); } /* W := W * V2 */ dtrmm_("Right", "Lower", "No transpose", "Unit", n, k, &c_b22, &v[(*m - *k + 1) * v_dim1 + 1], ldv, &work[ work_offset], ldwork, 5L, 5L, 12L, 4L); /* C2 := C2 - W' */ i__1 = *k; for(j = 1; j <= i__1; ++j) { i__2 = *n; for(i = 1; i <= i__2; ++i) { c[*m - *k + j + i * c_dim1] -= work[i + j * work_dim1] ; /* L200: */ } /* L210: */ } } else if(lsame_(side, "R", 1L, 1L)) { /* Form C * H or C * H' where C = ( C1 C2 ) */ /* W := C * V' = (C1*V1' + C2*V2') (stored in WORK) */ /* W := C2 */ i__1 = *k; for(j = 1; j <= i__1; ++j) { dcopy_(m, &c[(*n - *k + j) * c_dim1 + 1], &c__1, &work[j * work_dim1 + 1], &c__1); /* L220: */ } /* W := W * V2' */ dtrmm_("Right", "Lower", "Transpose", "Unit", m, k, &c_b22, & v[(*n - *k + 1) * v_dim1 + 1], ldv, &work[work_offset] , ldwork, 5L, 5L, 9L, 4L); if(*n > *k) { /* W := W + C1 * V1' */ i__1 = *n - *k; dgemm_("No transpose", "Transpose", m, k, &i__1, &c_b22, & c[c_offset], ldc, &v[v_offset], ldv, &c_b22, & work[work_offset], ldwork, 12L, 9L); } /* W := W * T or W * T' */ dtrmm_("Right", "Lower", trans, "Non-unit", m, k, &c_b22, &t[ t_offset], ldt, &work[work_offset], ldwork, 5L, 5L, 1L, 8L); /* C := C - W * V */ if(*n > *k) { /* C1 := C1 - W * V1 */ i__1 = *n - *k; dgemm_("No transpose", "No transpose", m, &i__1, k, & c_b211, &work[work_offset], ldwork, &v[v_offset], ldv, &c_b22, &c[c_offset], ldc, 12L, 12L); } /* W := W * V2 */ dtrmm_("Right", "Lower", "No transpose", "Unit", m, k, &c_b22, &v[(*n - *k + 1) * v_dim1 + 1], ldv, &work[ work_offset], ldwork, 5L, 5L, 12L, 4L); /* C1 := C1 - W */ i__1 = *k; for(j = 1; j <= i__1; ++j) { i__2 = *m; for(i = 1; i <= i__2; ++i) { c[i + (*n - *k + j) * c_dim1] -= work[i + j * work_dim1]; /* L230: */ } /* L240: */ } } } } return 0; /* End of DLARFB */ } /* dlarfb_ */ /* Subroutine */ int dlarft_(direct, storev, n, k, v, ldv, tau, t, ldt, direct_len, storev_len) char *direct, *storev; integer *n, *k; doublereal *v; integer *ldv; doublereal *tau, *t; integer *ldt; ftnlen direct_len; ftnlen storev_len; { /* System generated locals */ integer t_dim1, t_offset, v_dim1, v_offset, i__1, i__2, i__3; doublereal d__1; /* Local variables */ static integer i, j; extern logical lsame_(); extern /* Subroutine */ int dgemv_(), dtrmv_(); static doublereal vii; /* -- LAPACK auxiliary routine (version 1.1) -- */ /* Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., */ /* Courant Institute, Argonne National Lab, and Rice University */ /* February 29, 1992 */ /* .. Scalar Arguments .. */ /* .. */ /* .. Array Arguments .. */ /* .. */ /* Purpose */ /* ======= */ /* DLARFT forms the triangular factor T of a real block reflector H */ /* of order n, which is defined as a product of k elementary reflectors. */ /* If DIRECT = 'F', H = H(1) H(2) . . . H(k) and T is upper triangular; */ /* If DIRECT = 'B', H = H(k) . . . H(2) H(1) and T is lower triangular. */ /* If STOREV = 'C', the vector which defines the elementary reflector */ /* H(i) is stored in the i-th column of the array V, and */ /* H = I - V * T * V' */ /* If STOREV = 'R', the vector which defines the elementary reflector */ /* H(i) is stored in the i-th row of the array V, and */ /* H = I - V' * T * V */ /* Arguments */ /* ========= */ /* DIRECT (input) CHARACTER*1 */ /* Specifies the order in which the elementary reflectors are */ /* multiplied to form the block reflector: */ /* = 'F': H = H(1) H(2) . . . H(k) (Forward) */ /* = 'B': H = H(k) . . . H(2) H(1) (Backward) */ /* STOREV (input) CHARACTER*1 */ /* Specifies how the vectors which define the elementary */ /* reflectors are stored (see also Further Details): */ /* = 'C': columnwise */ /* = 'R': rowwise */ /* N (input) INTEGER */ /* The order of the block reflector H. N >= 0. */ /* K (input) INTEGER */ /* The order of the triangular factor T (= the number of */ /* elementary reflectors). K >= 1. */ /* V (input/output) DOUBLE PRECISION array, dimension */ /* (LDV,K) if STOREV = 'C' */ /* (LDV,N) if STOREV = 'R' */ /* The matrix V. See further details. */ /* LDV (input) INTEGER */ /* The leading dimension of the array V. */ /* If STOREV = 'C', LDV >= max(1,N); if STOREV = 'R', LDV >= K. */ /* TAU (input) DOUBLE PRECISION array, dimension (K) */ /* TAU(i) must contain the scalar factor of the elementary */ /* reflector H(i). */ /* T (output) DOUBLE PRECISION array, dimension (LDT,K) */ /* The k by k triangular factor T of the block reflector. */ /* If DIRECT = 'F', T is upper triangular; if DIRECT = 'B', T is */ /* lower triangular. The rest of the array is not used. */ /* LDT (input) INTEGER */ /* The leading dimension of the array T. LDT >= K. */ /* Further Details */ /* =============== */ /* The shape of the matrix V and the storage of the vectors which define */ /* the H(i) is best illustrated by the following example with n = 5 and */ /* k = 3. The elements equal to 1 are not stored; the corresponding */ /* array elements are modified but restored on exit. The rest of the */ /* array is not used. */ /* DIRECT = 'F' and STOREV = 'C': DIRECT = 'F' and STOREV = 'R': */ /* V = ( 1 ) V = ( 1 v1 v1 v1 v1 ) */ /* ( v1 1 ) ( 1 v2 v2 v2 ) */ /* ( v1 v2 1 ) ( 1 v3 v3 ) */ /* ( v1 v2 v3 ) */ /* ( v1 v2 v3 ) */ /* DIRECT = 'B' and STOREV = 'C': DIRECT = 'B' and STOREV = 'R': */ /* V = ( v1 v2 v3 ) V = ( v1 v1 1 ) */ /* ( v1 v2 v3 ) ( v2 v2 v2 1 ) */ /* ( 1 v2 v3 ) ( v3 v3 v3 v3 1 ) */ /* ( 1 v3 ) */ /* ( 1 ) */ /* ===================================================================== */ /* .. Parameters .. */ /* .. */ /* .. Local Scalars .. */ /* .. */ /* .. External Subroutines .. */ /* .. */ /* .. External Functions .. */ /* .. */ /* .. Executable Statements .. */ /* Quick return if possible */ /* Parameter adjustments */ t_dim1 = *ldt; t_offset = t_dim1 + 1; t -= t_offset; --tau; v_dim1 = *ldv; v_offset = v_dim1 + 1; v -= v_offset; /* Function Body */ if(*n == 0) { return 0; } if(lsame_(direct, "F", 1L, 1L)) { i__1 = *k; for(i = 1; i <= i__1; ++i) { if(tau[i] == 0.) { /* H(i) = I */ i__2 = i; for(j = 1; j <= i__2; ++j) { t[j + i * t_dim1] = 0.; /* L10: */ } } else { /* general case */ vii = v[i + i * v_dim1]; v[i + i * v_dim1] = 1.; if(lsame_(storev, "C", 1L, 1L)) { /* T(1:i-1,i) := - tau(i) * V(i:n,1:i-1)' * V(i:n,i) */ i__2 = *n - i + 1; i__3 = i - 1; d__1 = -tau[i]; dgemv_("Transpose", &i__2, &i__3, &d__1, &v[i + v_dim1], ldv, &v[i + i * v_dim1], &c__1, &c_b21, &t[i * t_dim1 + 1], &c__1, 9L); } else { /* T(1:i-1,i) := - tau(i) * V(1:i-1,i:n) * V(i,i:n)' */ i__2 = i - 1; i__3 = *n - i + 1; d__1 = -tau[i]; dgemv_("No transpose", &i__2, &i__3, &d__1, &v[i * v_dim1 + 1], ldv, &v[i + i * v_dim1], ldv, &c_b21, &t[i * t_dim1 + 1], &c__1, 12L); } v[i + i * v_dim1] = vii; /* T(1:i-1,i) := T(1:i-1,1:i-1) * T(1:i-1,i) */ i__2 = i - 1; dtrmv_("Upper", "No transpose", "Non-unit", &i__2, &t[ t_offset], ldt, &t[i * t_dim1 + 1], &c__1, 5L, 12L, 8L); t[i + i * t_dim1] = tau[i]; } /* L20: */ } } else { for(i = *k; i >= 1; --i) { if(tau[i] == 0.) { /* H(i) = I */ i__1 = *k; for(j = i; j <= i__1; ++j) { t[j + i * t_dim1] = 0.; /* L30: */ } } else { /* general case */ if(i < *k) { if(lsame_(storev, "C", 1L, 1L)) { vii = v[*n - *k + i + i * v_dim1]; v[*n - *k + i + i * v_dim1] = 1.; /* T(i+1:k,i) := */ /* - tau(i) * V(1:n-k+i,i+1 :k)' * V(1:n-k+i,i) */ i__1 = *n - *k + i; i__2 = *k - i; d__1 = -tau[i]; dgemv_("Transpose", &i__1, &i__2, &d__1, &v[(i + 1) * v_dim1 + 1], ldv, &v[i * v_dim1 + 1], &c__1, & c_b21, &t[i + 1 + i * t_dim1], &c__1, 9L); v[*n - *k + i + i * v_dim1] = vii; } else { vii = v[i + (*n - *k + i) * v_dim1]; v[i + (*n - *k + i) * v_dim1] = 1.; /* T(i+1:k,i) := */ /* - tau(i) * V(i+1:k,1:n-k +i) * V(i,1:n-k+i)' */ i__1 = *k - i; i__2 = *n - *k + i; d__1 = -tau[i]; dgemv_("No transpose", &i__1, &i__2, &d__1, &v[i + 1 + v_dim1], ldv, &v[i + v_dim1], ldv, &c_b21, & t[i + 1 + i * t_dim1], &c__1, 12L); v[i + (*n - *k + i) * v_dim1] = vii; } /* T(i+1:k,i) := T(i+1:k,i+1:k) * T(i+1:k, i) */ i__1 = *k - i; dtrmv_("Lower", "No transpose", "Non-unit", &i__1, &t[i + 1 + (i + 1) * t_dim1], ldt, &t[i + 1 + i * t_dim1] , &c__1, 5L, 12L, 8L); } t[i + i * t_dim1] = tau[i]; } /* L40: */ } } return 0; /* End of DLARFT */ } /* dlarft_ */ /* Subroutine */ int dorg2l_(m, n, k, a, lda, tau, work, info) integer *m, *n, *k; doublereal *a; integer *lda; doublereal *tau, *work; integer *info; { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; doublereal d__1; /* Local variables */ static integer i, j, l; extern /* Subroutine */ int dscal_(), dlarf_(); static integer ii; extern /* Subroutine */ int xerbla_(); /* -- LAPACK routine (version 1.1) -- */ /* Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., */ /* Courant Institute, Argonne National Lab, and Rice University */ /* February 29, 1992 */ /* .. Scalar Arguments .. */ /* .. */ /* .. Array Arguments .. */ /* .. */ /* Purpose */ /* ======= */ /* DORG2L generates an m by n real matrix Q with orthonormal columns, */ /* which is defined as the last n columns of a product of k elementary */ /* reflectors of order m */ /* Q = H(k) . . . H(2) H(1) */ /* as returned by DGEQLF. */ /* Arguments */ /* ========= */ /* M (input) INTEGER */ /* The number of rows of the matrix Q. M >= 0. */ /* N (input) INTEGER */ /* The number of columns of the matrix Q. M >= N >= 0. */ /* K (input) INTEGER */ /* The number of elementary reflectors whose product defines the */ /* matrix Q. N >= K >= 0. */ /* A (input/output) DOUBLE PRECISION array, dimension (LDA,N) */ /* On entry, the (n-k+i)-th column must contain the vector which */ /* defines the elementary reflector H(i), for i = 1,2,...,k, as */ /* returned by DGEQLF in the last k columns of its array */ /* argument A. */ /* On exit, the m by n matrix Q. */ /* LDA (input) INTEGER */ /* The first dimension of the array A. LDA >= max(1,M). */ /* TAU (input) DOUBLE PRECISION array, dimension (K) */ /* TAU(i) must contain the scalar factor of the elementary */ /* reflector H(i), as returned by DGEQLF. */ /* WORK (workspace) DOUBLE PRECISION array, dimension (N) */ /* INFO (output) INTEGER */ /* = 0: successful exit */ /* < 0: if INFO = -i, the i-th argument has an illegal value */ /* ===================================================================== */ /* .. Parameters .. */ /* .. */ /* .. Local Scalars .. */ /* .. */ /* .. External Subroutines .. */ /* .. */ /* .. Intrinsic Functions .. */ /* .. */ /* .. Executable Statements .. */ /* Test the input arguments */ /* Parameter adjustments */ --work; --tau; a_dim1 = *lda; a_offset = a_dim1 + 1; a -= a_offset; /* Function Body */ *info = 0; if(*m < 0) { *info = -1; } else if(*n < 0 || *n > *m) { *info = -2; } else if(*k < 0 || *k > *n) { *info = -3; } else if(*lda < max(1, *m)) { *info = -5; } if(*info != 0) { i__1 = -(*info); xerbla_("DORG2L", &i__1, 6L); return 0; } /* Quick return if possible */ if(*n <= 0) { return 0; } /* Initialise columns 1:n-k to columns of the unit matrix */ i__1 = *n - *k; for(j = 1; j <= i__1; ++j) { i__2 = *m; for(l = 1; l <= i__2; ++l) { a[l + j * a_dim1] = 0.; /* L10: */ } a[*m - *n + j + j * a_dim1] = 1.; /* L20: */ } i__1 = *k; for(i = 1; i <= i__1; ++i) { ii = *n - *k + i; /* Apply H(i) to A(1:m-k+i,1:n-k+i) from the left */ a[*m - *n + ii + ii * a_dim1] = 1.; i__2 = *m - *n + ii; i__3 = ii - 1; dlarf_("Left", &i__2, &i__3, &a[ii * a_dim1 + 1], &c__1, &tau[i], &a[ a_offset], lda, &work[1], 4L); i__2 = *m - *n + ii - 1; d__1 = -tau[i]; dscal_(&i__2, &d__1, &a[ii * a_dim1 + 1], &c__1); a[*m - *n + ii + ii * a_dim1] = 1. - tau[i]; /* Set A(m-k+i+1:m,n-k+i) to zero */ i__2 = *m; for(l = *m - *n + ii + 1; l <= i__2; ++l) { a[l + ii * a_dim1] = 0.; /* L30: */ } /* L40: */ } return 0; /* End of DORG2L */ } /* dorg2l_ */ /* Subroutine */ int dlarf_(side, m, n, v, incv, tau, c, ldc, work, side_len) char *side; integer *m, *n; doublereal *v; integer *incv; doublereal *tau, *c; integer *ldc; doublereal *work; ftnlen side_len; { /* System generated locals */ integer c_dim1, c_offset; doublereal d__1; /* Local variables */ extern /* Subroutine */ int dger_(); extern logical lsame_(); extern /* Subroutine */ int dgemv_(); /* -- LAPACK auxiliary routine (version 1.1) -- */ /* Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., */ /* Courant Institute, Argonne National Lab, and Rice University */ /* February 29, 1992 */ /* .. Scalar Arguments .. */ /* .. */ /* .. Array Arguments .. */ /* .. */ /* Purpose */ /* ======= */ /* DLARF applies a real elementary reflector H to a real m by n matrix */ /* C, from either the left or the right. H is represented in the form */ /* H = I - tau * v * v' */ /* where tau is a real scalar and v is a real vector. */ /* If tau = 0, then H is taken to be the unit matrix. */ /* Arguments */ /* ========= */ /* SIDE (input) CHARACTER*1 */ /* = 'L': form H * C */ /* = 'R': form C * H */ /* M (input) INTEGER */ /* The number of rows of the matrix C. */ /* N (input) INTEGER */ /* The number of columns of the matrix C. */ /* V (input) DOUBLE PRECISION array, dimension */ /* (1 + (M-1)*abs(INCV)) if SIDE = 'L' */ /* or (1 + (N-1)*abs(INCV)) if SIDE = 'R' */ /* The vector v in the representation of H. V is not used if */ /* TAU = 0. */ /* INCV (input) INTEGER */ /* The increment between elements of v. INCV <> 0. */ /* TAU (input) DOUBLE PRECISION */ /* The value tau in the representation of H. */ /* C (input/output) DOUBLE PRECISION array, dimension (LDC,N) */ /* On entry, the m by n matrix C. */ /* On exit, C is overwritten by the matrix H * C if SIDE = 'L', */ /* or C * H if SIDE = 'R'. */ /* LDC (input) INTEGER */ /* The leading dimension of the array C. LDC >= max(1,M). */ /* WORK (workspace) DOUBLE PRECISION array, dimension */ /* (N) if SIDE = 'L' */ /* or (M) if SIDE = 'R' */ /* ===================================================================== */ /* .. Parameters .. */ /* .. */ /* .. External Subroutines .. */ /* .. */ /* .. External Functions .. */ /* .. */ /* .. Executable Statements .. */ /* Parameter adjustments */ --work; c_dim1 = *ldc; c_offset = c_dim1 + 1; c -= c_offset; --v; /* Function Body */ if(lsame_(side, "L", 1L, 1L)) { /* Form H * C */ if(*tau != 0.) { /* w := C' * v */ dgemv_("Transpose", m, n, &c_b22, &c[c_offset], ldc, &v[1], incv, &c_b21, &work[1], &c__1, 9L); /* C := C - v * w' */ d__1 = -(*tau); dger_(m, n, &d__1, &v[1], incv, &work[1], &c__1, &c[c_offset], ldc); } } else { /* Form C * H */ if(*tau != 0.) { /* w := C * v */ dgemv_("No transpose", m, n, &c_b22, &c[c_offset], ldc, &v[1], incv, &c_b21, &work[1], &c__1, 12L); /* C := C - w * v' */ d__1 = -(*tau); dger_(m, n, &d__1, &work[1], &c__1, &v[1], incv, &c[c_offset], ldc); } } return 0; /* End of DLARF */ } /* dlarf_ */ /* Subroutine */ int dsterf_(n, d, e, info) integer *n; doublereal *d, *e; integer *info; { /* System generated locals */ integer i__1, i__2; doublereal d__1, d__2; /* Builtin functions */ double sqrt(), d_sign(); /* Local variables */ static doublereal oldc; static integer lend, jtot; extern /* Subroutine */ int dlae2_(); static doublereal c; static integer i, j, k, l, m; static doublereal p, gamma, r, s, alpha, sigma; static integer l1, lendm1, lendp1; extern doublereal dlapy2_(); static doublereal bb; static integer ii; extern doublereal dlamch_(); static doublereal oldgam; extern /* Subroutine */ int xerbla_(); static integer nmaxit, lm1, mm1, nm1; static doublereal rt1, rt2, eps, rte, tst; /* -- LAPACK routine (version 1.1) -- */ /* Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., */ /* Courant Institute, Argonne National Lab, and Rice University */ /* March 31, 1993 */ /* .. Scalar Arguments .. */ /* .. */ /* .. Array Arguments .. */ /* .. */ /* Purpose */ /* ======= */ /* DSTERF computes all eigenvalues of a symmetric tridiagonal matrix */ /* using the Pal-Walker-Kahan variant of the QL or QR algorithm. */ /* Arguments */ /* ========= */ /* N (input) INTEGER */ /* The order of the matrix. N >= 0. */ /* D (input/output) DOUBLE PRECISION array, dimension (N) */ /* On entry, the n diagonal elements of the tridiagonal matrix. */ /* On exit, if INFO = 0, the eigenvalues in ascending order. */ /* E (input/output) DOUBLE PRECISION array, dimension (N-1) */ /* On entry, the (n-1) subdiagonal elements of the tridiagonal */ /* matrix. */ /* On exit, E has been destroyed. */ /* INFO (output) INTEGER */ /* = 0: successful exit */ /* < 0: if INFO = -i, the i-th argument had an illegal value */ /* > 0: the algorithm failed to find all of the eigenvalues in */ /* a total of 30*N iterations; if INFO = i, then i */ /* elements of E have not converged to zero. */ /* ===================================================================== */ /* .. Parameters .. */ /* .. */ /* .. Local Scalars .. */ /* .. */ /* .. External Functions .. */ /* .. */ /* .. External Subroutines .. */ /* .. */ /* .. Intrinsic Functions .. */ /* .. */ /* .. Executable Statements .. */ /* Test the input parameters. */ /* Parameter adjustments */ --e; --d; /* Function Body */ *info = 0; /* Quick return if possible */ if(*n < 0) { *info = -1; i__1 = -(*info); xerbla_("DSTERF", &i__1, 6L); return 0; } if(*n <= 1) { return 0; } /* Determine the unit roundoff for this environment. */ eps = dlamch_("E", 1L); /* Compute the eigenvalues of the tridiagonal matrix. */ i__1 = *n - 1; for(i = 1; i <= i__1; ++i) { /* Computing 2nd power */ d__1 = e[i]; e[i] = d__1 * d__1; /* L10: */ } nmaxit = *n * 30; sigma = 0.; jtot = 0; /* Determine where the matrix splits and choose QL or QR iteration */ /* for each block, according to whether top or bottom diagonal */ /* element is smaller. */ l1 = 1; nm1 = *n - 1; L20: if(l1 > *n) { goto L170; } if(l1 > 1) { e[l1 - 1] = 0.; } if(l1 <= nm1) { i__1 = nm1; for(m = l1; m <= i__1; ++m) { tst = sqrt((d__1 = e[m], abs(d__1))); if(tst <= eps * ((d__1 = d[m], abs(d__1)) + (d__2 = d[m + 1], abs(d__2)))) { goto L40; } /* L30: */ } } m = *n; L40: l = l1; lend = m; if((d__1 = d[lend], abs(d__1)) < (d__2 = d[l], abs(d__2))) { l = lend; lend = l1; } l1 = m + 1; if(lend >= l) { /* QL Iteration */ /* Look for small subdiagonal element. */ L50: if(l != lend) { lendm1 = lend - 1; i__1 = lendm1; for(m = l; m <= i__1; ++m) { tst = sqrt((d__1 = e[m], abs(d__1))); if(tst <= eps * ((d__1 = d[m], abs(d__1)) + (d__2 = d[m + 1], abs(d__2)))) { goto L70; } /* L60: */ } } m = lend; L70: if(m < lend) { e[m] = 0.; } p = d[l]; if(m == l) { goto L90; } /* If remaining matrix is 2 by 2, use DLAE2 to compute its */ /* eigenvalues. */ if(m == l + 1) { rte = sqrt(e[l]); dlae2_(&d[l], &rte, &d[l + 1], &rt1, &rt2); d[l] = rt1; d[l + 1] = rt2; e[l] = 0.; l += 2; if(l <= lend) { goto L50; } goto L20; } if(jtot == nmaxit) { goto L150; } ++jtot; /* Form shift. */ rte = sqrt(e[l]); sigma = (d[l + 1] - p) / (rte * 2.); r = dlapy2_(&sigma, &c_b22); sigma = p - rte / (sigma + d_sign(&r, &sigma)); c = 1.; s = 0.; gamma = d[m] - sigma; p = gamma * gamma; /* Inner loop */ mm1 = m - 1; i__1 = l; for(i = mm1; i >= i__1; --i) { bb = e[i]; r = p + bb; if(i != m - 1) { e[i + 1] = s * r; } oldc = c; c = p / r; s = bb / r; oldgam = gamma; alpha = d[i]; gamma = c * (alpha - sigma) - s * oldgam; d[i + 1] = oldgam + (alpha - gamma); if(c != 0.) { p = gamma * gamma / c; } else { p = oldc * bb; } /* L80: */ } e[l] = s * p; d[l] = sigma + gamma; goto L50; /* Eigenvalue found. */ L90: d[l] = p; ++l; if(l <= lend) { goto L50; } goto L20; } else { /* QR Iteration */ /* Look for small superdiagonal element. */ L100: if(l != lend) { lendp1 = lend + 1; i__1 = lendp1; for(m = l; m >= i__1; --m) { tst = sqrt((d__1 = e[m - 1], abs(d__1))); if(tst <= eps * ((d__1 = d[m], abs(d__1)) + (d__2 = d[m - 1], abs(d__2)))) { goto L120; } /* L110: */ } } m = lend; L120: if(m > lend) { e[m - 1] = 0.; } p = d[l]; if(m == l) { goto L140; } /* If remaining matrix is 2 by 2, use DLAE2 to compute its */ /* eigenvalues. */ if(m == l - 1) { rte = sqrt(e[l - 1]); dlae2_(&d[l], &rte, &d[l - 1], &rt1, &rt2); d[l] = rt1; d[l - 1] = rt2; e[l - 1] = 0.; l += -2; if(l >= lend) { goto L100; } goto L20; } if(jtot == nmaxit) { goto L150; } ++jtot; /* Form shift. */ rte = sqrt(e[l - 1]); sigma = (d[l - 1] - p) / (rte * 2.); r = dlapy2_(&sigma, &c_b22); sigma = p - rte / (sigma + d_sign(&r, &sigma)); c = 1.; s = 0.; gamma = d[m] - sigma; p = gamma * gamma; /* Inner loop */ lm1 = l - 1; i__1 = lm1; for(i = m; i <= i__1; ++i) { bb = e[i]; r = p + bb; if(i != m) { e[i - 1] = s * r; } oldc = c; c = p / r; s = bb / r; oldgam = gamma; alpha = d[i + 1]; gamma = c * (alpha - sigma) - s * oldgam; d[i] = oldgam + (alpha - gamma); if(c != 0.) { p = gamma * gamma / c; } else { p = oldc * bb; } /* L130: */ } e[lm1] = s * p; d[l] = sigma + gamma; goto L100; /* Eigenvalue found. */ L140: d[l] = p; --l; if(l >= lend) { goto L100; } goto L20; } /* Set error -- no convergence to an eigenvalue after a total */ /* of N*MAXIT iterations. */ L150: i__1 = *n - 1; for(i = 1; i <= i__1; ++i) { if(e[i] != 0.) { ++(*info); } /* L160: */ } return 0; /* Sort eigenvalues in increasing order. */ L170: i__1 = *n; for(ii = 2; ii <= i__1; ++ii) { i = ii - 1; k = i; p = d[i]; i__2 = *n; for(j = ii; j <= i__2; ++j) { if(d[j] < p) { k = j; p = d[j]; } /* L180: */ } if(k != i) { d[k] = d[i]; d[i] = p; } /* L190: */ } return 0; /* End of DSTERF */ } /* dsterf_ */ /* Subroutine */ int dlae2_(a, b, c, rt1, rt2) doublereal *a, *b, *c, *rt1, *rt2; { /* System generated locals */ doublereal d__1; /* Builtin functions */ double sqrt(); /* Local variables */ static doublereal acmn, acmx, ab, df, tb, sm, rt, adf; /* -- LAPACK auxiliary routine (version 1.1) -- */ /* Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., */ /* Courant Institute, Argonne National Lab, and Rice University */ /* October 31, 1992 */ /* .. Scalar Arguments .. */ /* .. */ /* Purpose */ /* ======= */ /* DLAE2 computes the eigenvalues of a 2-by-2 symmetric matrix */ /* [ A B ] */ /* [ B C ]. */ /* On return, RT1 is the eigenvalue of larger absolute value, and RT2 */ /* is the eigenvalue of smaller absolute value. */ /* Arguments */ /* ========= */ /* A (input) DOUBLE PRECISION */ /* The (1,1) entry of the 2-by-2 matrix. */ /* B (input) DOUBLE PRECISION */ /* The (1,2) and (2,1) entries of the 2-by-2 matrix. */ /* C (input) DOUBLE PRECISION */ /* The (2,2) entry of the 2-by-2 matrix. */ /* RT1 (output) DOUBLE PRECISION */ /* The eigenvalue of larger absolute value. */ /* RT2 (output) DOUBLE PRECISION */ /* The eigenvalue of smaller absolute value. */ /* Further Details */ /* =============== */ /* RT1 is accurate to a few ulps barring over/underflow. */ /* RT2 may be inaccurate if there is massive cancellation in the */ /* determinant A*C-B*B; higher precision or correctly rounded or */ /* correctly truncated arithmetic would be needed to compute RT2 */ /* accurately in all cases. */ /* Overflow is possible only if RT1 is within a factor of 5 of overflow. */ /* Underflow is harmless if the input data is 0 or exceeds */ /* underflow_threshold / macheps. */ /* ===================================================================== */ /* .. Parameters .. */ /* .. */ /* .. Local Scalars .. */ /* .. */ /* .. Intrinsic Functions .. */ /* .. */ /* .. Executable Statements .. */ /* Compute the eigenvalues */ sm = *a + *c; df = *a - *c; adf = abs(df); tb = *b + *b; ab = abs(tb); if(abs(*a) > abs(*c)) { acmx = *a; acmn = *c; } else { acmx = *c; acmn = *a; } if(adf > ab) { /* Computing 2nd power */ d__1 = ab / adf; rt = adf * sqrt(d__1 * d__1 + 1.); } else if(adf < ab) { /* Computing 2nd power */ d__1 = adf / ab; rt = ab * sqrt(d__1 * d__1 + 1.); } else { /* Includes case AB=ADF=0 */ rt = ab * sqrt(2.); } if(sm < 0.) { *rt1 = (sm - rt) * .5; /* Order of execution important. */ /* To get fully accurate smaller eigenvalue, */ /* next line needs to be executed in higher precision. */ *rt2 = acmx / *rt1 * acmn - *b / *rt1 * *b; } else if(sm > 0.) { *rt1 = (sm + rt) * .5; /* Order of execution important. */ /* To get fully accurate smaller eigenvalue, */ /* next line needs to be executed in higher precision. */ *rt2 = acmx / *rt1 * acmn - *b / *rt1 * *b; } else { /* Includes case RT1 = RT2 = 0 */ *rt1 = rt * .5; *rt2 = rt * -.5; } return 0; /* End of DLAE2 */ } /* dlae2_ */ /* Subroutine */ int dsytrd_(uplo, n, a, lda, d, e, tau, work, lwork, info, uplo_len) char *uplo; integer *n; doublereal *a; integer *lda; doublereal *d, *e, *tau, *work; integer *lwork, *info; ftnlen uplo_len; { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; /* Local variables */ static integer i, j; extern logical lsame_(); static integer nbmin, iinfo; static logical upper; extern /* Subroutine */ int dsytd2_(), dsyr2k_(); static integer nb, kk, nx; extern /* Subroutine */ int dlatrd_(), xerbla_(); extern integer ilaenv_(); static integer ldwork, iws; /* -- LAPACK routine (version 1.1) -- */ /* Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., */ /* Courant Institute, Argonne National Lab, and Rice University */ /* March 31, 1993 */ /* .. Scalar Arguments .. */ /* .. */ /* .. Array Arguments .. */ /* .. */ /* Purpose */ /* ======= */ /* DSYTRD reduces a real symmetric matrix A to real symmetric */ /* tridiagonal form T by an orthogonal similarity transformation: */ /* Q**T * A * Q = T. */ /* Arguments */ /* ========= */ /* UPLO (input) CHARACTER*1 */ /* = 'U': Upper triangle of A is stored; */ /* = 'L': Lower triangle of A is stored. */ /* N (input) INTEGER */ /* The order of the matrix A. N >= 0. */ /* A (input/output) DOUBLE PRECISION array, dimension (LDA,N) */ /* On entry, the symmetric matrix A. If UPLO = 'U', the leading */ /* N-by-N upper triangular part of A contains the upper */ /* triangular part of the matrix A, and the strictly lower */ /* triangular part of A is not referenced. If UPLO = 'L', the */ /* leading N-by-N lower triangular part of A contains the lower */ /* triangular part of the matrix A, and the strictly upper */ /* triangular part of A is not referenced. */ /* On exit, if UPLO = 'U', the diagonal and first superdiagonal */ /* of A are overwritten by the corresponding elements of the */ /* tridiagonal matrix T, and the elements above the first */ /* superdiagonal, with the array TAU, represent the orthogonal */ /* matrix Q as a product of elementary reflectors; if UPLO */ /* = 'L', the diagonal and first subdiagonal of A are over- */ /* written by the corresponding elements of the tridiagonal */ /* matrix T, and the elements below the first subdiagonal, with */ /* the array TAU, represent the orthogonal matrix Q as a product */ /* of elementary reflectors. See Further Details. */ /* LDA (input) INTEGER */ /* The leading dimension of the array A. LDA >= max(1,N). */ /* D (output) DOUBLE PRECISION array, dimension (N) */ /* The diagonal elements of the tridiagonal matrix T: */ /* D(i) = A(i,i). */ /* E (output) DOUBLE PRECISION array, dimension (N-1) */ /* The off-diagonal elements of the tridiagonal matrix T: */ /* E(i) = A(i,i+1) if UPLO = 'U', E(i) = A(i+1,i) if UPLO = 'L'. */ /* TAU (output) DOUBLE PRECISION array, dimension (N-1) */ /* The scalar factors of the elementary reflectors (see Further */ /* Details). */ /* WORK (workspace) DOUBLE PRECISION array, dimension (LWORK) */ /* On exit, if INFO = 0, WORK(1) returns the optimal LWORK. */ /* LWORK (input) INTEGER */ /* The dimension of the array WORK. LWORK >= 1. */ /* For optimum performance LWORK >= N*NB, where NB is the */ /* optimal blocksize. */ /* INFO (output) INTEGER */ /* = 0: successful exit */ /* < 0: if INFO = -i, the i-th argument had an illegal value */ /* Further Details */ /* =============== */ /* If UPLO = 'U', the matrix Q is represented as a product of elementary */ /* reflectors */ /* Q = H(n-1) . . . H(2) H(1). */ /* Each H(i) has the form */ /* H(i) = I - tau * v * v' */ /* where tau is a real scalar, and v is a real vector with */ /* v(i+1:n) = 0 and v(i) = 1; v(1:i-1) is stored on exit in */ /* A(1:i-1,i+1), and tau in TAU(i). */ /* If UPLO = 'L', the matrix Q is represented as a product of elementary */ /* reflectors */ /* Q = H(1) H(2) . . . H(n-1). */ /* Each H(i) has the form */ /* H(i) = I - tau * v * v' */ /* where tau is a real scalar, and v is a real vector with */ /* v(1:i) = 0 and v(i+1) = 1; v(i+2:n) is stored on exit in A(i+2:n,i), */ /* and tau in TAU(i). */ /* The contents of A on exit are illustrated by the following examples */ /* with n = 5: */ /* if UPLO = 'U': if UPLO = 'L': */ /* ( d e v2 v3 v4 ) ( d ) */ /* ( d e v3 v4 ) ( e d ) */ /* ( d e v4 ) ( v1 e d ) */ /* ( d e ) ( v1 v2 e d ) */ /* ( d ) ( v1 v2 v3 e d ) */ /* where d and e denote diagonal and off-diagonal elements of T, and vi */ /* denotes an element of the vector defining H(i). */ /* ===================================================================== */ /* .. Parameters .. */ /* .. */ /* .. Local Scalars .. */ /* .. */ /* .. External Subroutines .. */ /* .. */ /* .. Intrinsic Functions .. */ /* .. */ /* .. External Functions .. */ /* .. */ /* .. Executable Statements .. */ /* Test the input parameters */ /* Parameter adjustments */ --work; --tau; --e; --d; a_dim1 = *lda; a_offset = a_dim1 + 1; a -= a_offset; /* Function Body */ *info = 0; upper = lsame_(uplo, "U", 1L, 1L); if(! upper && ! lsame_(uplo, "L", 1L, 1L)) { *info = -1; } else if(*n < 0) { *info = -2; } else if(*lda < max(1, *n)) { *info = -4; } else if(*lwork < 1) { *info = -9; } if(*info != 0) { i__1 = -(*info); xerbla_("DSYTRD", &i__1, 6L); return 0; } /* Quick return if possible */ if(*n == 0) { work[1] = 1.; return 0; } /* Determine the block size. */ nb = ilaenv_(&c__1, "DSYTRD", uplo, n, &c_n1, &c_n1, &c_n1, 6L, 1L); nx = *n; iws = 1; if(nb > 1 && nb < *n) { /* Determine when to cross over from blocked to unblocked code */ /* (last block is always handled by unblocked code). */ /* Computing MAX */ i__1 = nb, i__2 = ilaenv_(&c__3, "DSYTRD", uplo, n, &c_n1, &c_n1, & c_n1, 6L, 1L); nx = max(i__1, i__2); if(nx < *n) { /* Determine if workspace is large enough for blocked co de. */ ldwork = *n; iws = ldwork * nb; if(*lwork < iws) { /* Not enough workspace to use optimal NB: deter mine the */ /* minimum value of NB, and reduce NB or force us e of */ /* unblocked code by setting NX = N. */ nb = *lwork / ldwork; nbmin = ilaenv_(&c__2, "DSYTRD", uplo, n, &c_n1, &c_n1, &c_n1, 6L, 1L); if(nb < nbmin) { nx = *n; } } } else { nx = *n; } } else { nb = 1; } if(upper) { /* Reduce the upper triangle of A. */ /* Columns 1:kk are handled by the unblocked method. */ kk = *n - (*n - nx + nb - 1) / nb * nb; i__1 = kk + 1; i__2 = -nb; for(i = *n - nb + 1; i__2 < 0 ? i >= i__1 : i <= i__1; i += i__2) { /* Reduce columns i:i+nb-1 to tridiagonal form and form the */ /* matrix W which is needed to update the unreduced part of */ /* the matrix */ i__3 = i + nb - 1; dlatrd_(uplo, &i__3, &nb, &a[a_offset], lda, &e[1], &tau[1], & work[1], &ldwork, 1L); /* Update the unreduced submatrix A(1:i-1,1:i-1), using an */ /* update of the form: A := A - V*W' - W*V' */ i__3 = i - 1; dsyr2k_(uplo, "No transpose", &i__3, &nb, &c_b211, &a[i * a_dim1 + 1], lda, &work[1], &ldwork, &c_b22, &a[a_offset], lda, 1L, 12L); /* Copy superdiagonal elements back into A, and diagonal */ /* elements into D */ i__3 = i + nb - 1; for(j = i; j <= i__3; ++j) { a[j - 1 + j * a_dim1] = e[j - 1]; d[j] = a[j + j * a_dim1]; /* L10: */ } /* L20: */ } /* Use unblocked code to reduce the last or only block */ dsytd2_(uplo, &kk, &a[a_offset], lda, &d[1], &e[1], &tau[1], &iinfo, 1L); } else { /* Reduce the lower triangle of A */ i__2 = *n - nx; i__1 = nb; for(i = 1; i__1 < 0 ? i >= i__2 : i <= i__2; i += i__1) { /* Reduce columns i:i+nb-1 to tridiagonal form and form the */ /* matrix W which is needed to update the unreduced part of */ /* the matrix */ i__3 = *n - i + 1; dlatrd_(uplo, &i__3, &nb, &a[i + i * a_dim1], lda, &e[i], &tau[i], &work[1], &ldwork, 1L); /* Update the unreduced submatrix A(i+ib:n,i+ib:n), usin g */ /* an update of the form: A := A - V*W' - W*V' */ i__3 = *n - i - nb + 1; dsyr2k_(uplo, "No transpose", &i__3, &nb, &c_b211, &a[i + nb + i * a_dim1], lda, &work[nb + 1], &ldwork, &c_b22, &a[i + nb + (i + nb) * a_dim1], lda, 1L, 12L); /* Copy subdiagonal elements back into A, and diagonal */ /* elements into D */ i__3 = i + nb - 1; for(j = i; j <= i__3; ++j) { a[j + 1 + j * a_dim1] = e[j]; d[j] = a[j + j * a_dim1]; /* L30: */ } /* L40: */ } /* Use unblocked code to reduce the last or only block */ i__1 = *n - i + 1; dsytd2_(uplo, &i__1, &a[i + i * a_dim1], lda, &d[i], &e[i], &tau[i], & iinfo, 1L); } work[1] = (doublereal) iws; return 0; /* End of DSYTRD */ } /* dsytrd_ */ /* Subroutine */ int dsytd2_(uplo, n, a, lda, d, e, tau, info, uplo_len) char *uplo; integer *n; doublereal *a; integer *lda; doublereal *d, *e, *tau; integer *info; ftnlen uplo_len; { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; /* Local variables */ extern doublereal ddot_(); static doublereal taui; extern /* Subroutine */ int dsyr2_(); static integer i; static doublereal alpha; extern logical lsame_(); extern /* Subroutine */ int daxpy_(); static logical upper; extern /* Subroutine */ int dsymv_(), dlarfg_(), xerbla_(); /* -- LAPACK routine (version 1.1) -- */ /* Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., */ /* Courant Institute, Argonne National Lab, and Rice University */ /* October 31, 1992 */ /* .. Scalar Arguments .. */ /* .. */ /* .. Array Arguments .. */ /* .. */ /* Purpose */ /* ======= */ /* DSYTD2 reduces a real symmetric matrix A to symmetric tridiagonal */ /* form T by an orthogonal similarity transformation: Q' * A * Q = T. */ /* Arguments */ /* ========= */ /* UPLO (input) CHARACTER*1 */ /* Specifies whether the upper or lower triangular part of the */ /* symmetric matrix A is stored: */ /* = 'U': Upper triangular */ /* = 'L': Lower triangular */ /* N (input) INTEGER */ /* The order of the matrix A. N >= 0. */ /* A (input/output) DOUBLE PRECISION array, dimension (LDA,N) */ /* On entry, the symmetric matrix A. If UPLO = 'U', the leading */ /* n-by-n upper triangular part of A contains the upper */ /* triangular part of the matrix A, and the strictly lower */ /* triangular part of A is not referenced. If UPLO = 'L', the */ /* leading n-by-n lower triangular part of A contains the lower */ /* triangular part of the matrix A, and the strictly upper */ /* triangular part of A is not referenced. */ /* On exit, if UPLO = 'U', the diagonal and first superdiagonal */ /* of A are overwritten by the corresponding elements of the */ /* tridiagonal matrix T, and the elements above the first */ /* superdiagonal, with the array TAU, represent the orthogonal */ /* matrix Q as a product of elementary reflectors; if UPLO */ /* = 'L', the diagonal and first subdiagonal of A are over- */ /* written by the corresponding elements of the tridiagonal */ /* matrix T, and the elements below the first subdiagonal, with */ /* the array TAU, represent the orthogonal matrix Q as a product */ /* of elementary reflectors. See Further Details. */ /* LDA (input) INTEGER */ /* The leading dimension of the array A. LDA >= max(1,N). */ /* D (output) DOUBLE PRECISION array, dimension (N) */ /* The diagonal elements of the tridiagonal matrix T: */ /* D(i) = A(i,i). */ /* E (output) DOUBLE PRECISION array, dimension (N-1) */ /* The off-diagonal elements of the tridiagonal matrix T: */ /* E(i) = A(i,i+1) if UPLO = 'U', E(i) = A(i+1,i) if UPLO = 'L'. */ /* TAU (output) DOUBLE PRECISION array, dimension (N-1) */ /* The scalar factors of the elementary reflectors (see Further */ /* Details). */ /* INFO (output) INTEGER */ /* = 0: successful exit */ /* < 0: if INFO = -i, the i-th argument had an illegal value. */ /* Further Details */ /* =============== */ /* If UPLO = 'U', the matrix Q is represented as a product of elementary */ /* reflectors */ /* Q = H(n-1) . . . H(2) H(1). */ /* Each H(i) has the form */ /* H(i) = I - tau * v * v' */ /* where tau is a real scalar, and v is a real vector with */ /* v(i+1:n) = 0 and v(i) = 1; v(1:i-1) is stored on exit in */ /* A(1:i-1,i+1), and tau in TAU(i). */ /* If UPLO = 'L', the matrix Q is represented as a product of elementary */ /* reflectors */ /* Q = H(1) H(2) . . . H(n-1). */ /* Each H(i) has the form */ /* H(i) = I - tau * v * v' */ /* where tau is a real scalar, and v is a real vector with */ /* v(1:i) = 0 and v(i+1) = 1; v(i+2:n) is stored on exit in A(i+2:n,i), */ /* and tau in TAU(i). */ /* The contents of A on exit are illustrated by the following examples */ /* with n = 5: */ /* if UPLO = 'U': if UPLO = 'L': */ /* ( d e v2 v3 v4 ) ( d ) */ /* ( d e v3 v4 ) ( e d ) */ /* ( d e v4 ) ( v1 e d ) */ /* ( d e ) ( v1 v2 e d ) */ /* ( d ) ( v1 v2 v3 e d ) */ /* where d and e denote diagonal and off-diagonal elements of T, and vi */ /* denotes an element of the vector defining H(i). */ /* ===================================================================== */ /* .. Parameters .. */ /* .. */ /* .. Local Scalars .. */ /* .. */ /* .. External Subroutines .. */ /* .. */ /* .. External Functions .. */ /* .. */ /* .. Intrinsic Functions .. */ /* .. */ /* .. Executable Statements .. */ /* Test the input parameters */ /* Parameter adjustments */ --tau; --e; --d; a_dim1 = *lda; a_offset = a_dim1 + 1; a -= a_offset; /* Function Body */ *info = 0; upper = lsame_(uplo, "U", 1L, 1L); if(! upper && ! lsame_(uplo, "L", 1L, 1L)) { *info = -1; } else if(*n < 0) { *info = -2; } else if(*lda < max(1, *n)) { *info = -4; } if(*info != 0) { i__1 = -(*info); xerbla_("DSYTD2", &i__1, 6L); return 0; } /* Quick return if possible */ if(*n <= 0) { return 0; } if(upper) { /* Reduce the upper triangle of A */ for(i = *n - 1; i >= 1; --i) { /* Generate elementary reflector H(i) = I - tau * v * v' */ /* to annihilate A(1:i-1,i+1) */ dlarfg_(&i, &a[i + (i + 1) * a_dim1], &a[(i + 1) * a_dim1 + 1], & c__1, &taui); e[i] = a[i + (i + 1) * a_dim1]; if(taui != 0.) { /* Apply H(i) from both sides to A(1:i,1:i) */ a[i + (i + 1) * a_dim1] = 1.; /* Compute x := tau * A * v storing x in TAU(1: i) */ dsymv_(uplo, &i, &taui, &a[a_offset], lda, &a[(i + 1) * a_dim1 + 1], &c__1, &c_b21, &tau[1], &c__1, 1L); /* Compute w := x - 1/2 * tau * (x'*v) * v */ alpha = taui * -.5 * ddot_(&i, &tau[1], &c__1, &a[(i + 1) * a_dim1 + 1], &c__1); daxpy_(&i, &alpha, &a[(i + 1) * a_dim1 + 1], &c__1, &tau[1], & c__1); /* Apply the transformation as a rank-2 update: */ /* A := A - v * w' - w * v' */ dsyr2_(uplo, &i, &c_b211, &a[(i + 1) * a_dim1 + 1], &c__1, & tau[1], &c__1, &a[a_offset], lda, 1L); a[i + (i + 1) * a_dim1] = e[i]; } d[i + 1] = a[i + 1 + (i + 1) * a_dim1]; tau[i] = taui; /* L10: */ } d[1] = a[a_dim1 + 1]; } else { /* Reduce the lower triangle of A */ i__1 = *n - 1; for(i = 1; i <= i__1; ++i) { /* Generate elementary reflector H(i) = I - tau * v * v' */ /* to annihilate A(i+2:n,i) */ i__2 = *n - i; /* Computing MIN */ i__3 = i + 2; dlarfg_(&i__2, &a[i + 1 + i * a_dim1], &a[min(i__3, *n) + i * a_dim1], &c__1, &taui); e[i] = a[i + 1 + i * a_dim1]; if(taui != 0.) { /* Apply H(i) from both sides to A(i+1:n,i+1:n) */ a[i + 1 + i * a_dim1] = 1.; /* Compute x := tau * A * v storing y in TAU(i: n-1) */ i__2 = *n - i; dsymv_(uplo, &i__2, &taui, &a[i + 1 + (i + 1) * a_dim1], lda, &a[i + 1 + i * a_dim1], &c__1, &c_b21, &tau[i], &c__1, 1L); /* Compute w := x - 1/2 * tau * (x'*v) * v */ i__2 = *n - i; alpha = taui * -.5 * ddot_(&i__2, &tau[i], &c__1, &a[i + 1 + i * a_dim1], &c__1); i__2 = *n - i; daxpy_(&i__2, &alpha, &a[i + 1 + i * a_dim1], &c__1, &tau[i], &c__1); /* Apply the transformation as a rank-2 update: */ /* A := A - v * w' - w * v' */ i__2 = *n - i; dsyr2_(uplo, &i__2, &c_b211, &a[i + 1 + i * a_dim1], &c__1, & tau[i], &c__1, &a[i + 1 + (i + 1) * a_dim1], lda, 1L); a[i + 1 + i * a_dim1] = e[i]; } d[i] = a[i + i * a_dim1]; tau[i] = taui; /* L20: */ } d[*n] = a[*n + *n * a_dim1]; } return 0; /* End of DSYTD2 */ } /* dsytd2_ */ /* Subroutine */ int xerbla_(srname, info, srname_len) char *srname; integer *info; ftnlen srname_len; { /* Format strings */ static char fmt_9999[] = "(\002 ** On entry to \002,a6,\002 parameter nu\ mber \002,i2,\002 had \002,\002an illegal value\002)"; /* Builtin functions */ integer s_wsfe(), do_fio(), e_wsfe(); /* Subroutine */ int s_stop(); /* Fortran I/O blocks */ static cilist io___164 = { 0, 6, 0, fmt_9999, 0 }; /* -- LAPACK auxiliary routine (version 1.1) -- */ /* Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., */ /* Courant Institute, Argonne National Lab, and Rice University */ /* February 29, 1992 */ /* .. Scalar Arguments .. */ /* .. */ /* Purpose */ /* ======= */ /* XERBLA is an error handler for the LAPACK routines. */ /* It is called by an LAPACK routine if an input parameter has an */ /* invalid value. A message is printed and execution stops. */ /* Installers may consider modifying the STOP statement in order to */ /* call system-specific exception-handling facilities. */ /* Arguments */ /* ========= */ /* SRNAME (input) CHARACTER*6 */ /* The name of the routine which called XERBLA. */ /* INFO (input) INTEGER */ /* The position of the invalid parameter in the parameter list */ /* of the calling routine. */ /* .. Executable Statements .. */ s_wsfe(&io___164); do_fio(&c__1, srname, 6L); do_fio(&c__1, (char *) & (*info), (ftnlen)sizeof(integer)); e_wsfe(); s_stop("", 0L); /* End of XERBLA */ } /* xerbla_ */ /* Subroutine */ int dlatrd_(uplo, n, nb, a, lda, e, tau, w, ldw, uplo_len) char *uplo; integer *n, *nb; doublereal *a; integer *lda; doublereal *e, *tau, *w; integer *ldw; ftnlen uplo_len; { /* System generated locals */ integer a_dim1, a_offset, w_dim1, w_offset, i__1, i__2, i__3; /* Local variables */ extern doublereal ddot_(); static integer i; static doublereal alpha; extern /* Subroutine */ int dscal_(); extern logical lsame_(); extern /* Subroutine */ int dgemv_(), daxpy_(), dsymv_(), dlarfg_(); static integer iw; /* -- LAPACK auxiliary routine (version 1.1) -- */ /* Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., */ /* Courant Institute, Argonne National Lab, and Rice University */ /* October 31, 1992 */ /* .. Scalar Arguments .. */ /* .. */ /* .. Array Arguments .. */ /* .. */ /* Purpose */ /* ======= */ /* DLATRD reduces NB rows and columns of a real symmetric matrix A to */ /* symmetric tridiagonal form by an orthogonal similarity */ /* transformation Q' * A * Q, and returns the matrices V and W which are */ /* needed to apply the transformation to the unreduced part of A. */ /* If UPLO = 'U', DLATRD reduces the last NB rows and columns of a */ /* matrix, of which the upper triangle is supplied; */ /* if UPLO = 'L', DLATRD reduces the first NB rows and columns of a */ /* matrix, of which the lower triangle is supplied. */ /* This is an auxiliary routine called by DSYTRD. */ /* Arguments */ /* ========= */ /* UPLO (input) CHARACTER */ /* Specifies whether the upper or lower triangular part of the */ /* symmetric matrix A is stored: */ /* = 'U': Upper triangular */ /* = 'L': Lower triangular */ /* N (input) INTEGER */ /* The order of the matrix A. */ /* NB (input) INTEGER */ /* The number of rows and columns to be reduced. */ /* A (input/output) DOUBLE PRECISION array, dimension (LDA,N) */ /* On entry, the symmetric matrix A. If UPLO = 'U', the leading */ /* n-by-n upper triangular part of A contains the upper */ /* triangular part of the matrix A, and the strictly lower */ /* triangular part of A is not referenced. If UPLO = 'L', the */ /* leading n-by-n lower triangular part of A contains the lower */ /* triangular part of the matrix A, and the strictly upper */ /* triangular part of A is not referenced. */ /* On exit: */ /* if UPLO = 'U', the last NB columns have been reduced to */ /* tridiagonal form, with the diagonal elements overwriting */ /* the diagonal elements of A; the elements above the diagonal */ /* with the array TAU, represent the orthogonal matrix Q as a */ /* product of elementary reflectors; */ /* if UPLO = 'L', the first NB columns have been reduced to */ /* tridiagonal form, with the diagonal elements overwriting */ /* the diagonal elements of A; the elements below the diagonal */ /* with the array TAU, represent the orthogonal matrix Q as a */ /* product of elementary reflectors. */ /* See Further Details. */ /* LDA (input) INTEGER */ /* The leading dimension of the array A. LDA >= (1,N). */ /* E (output) DOUBLE PRECISION array, dimension (N-1) */ /* If UPLO = 'U', E(n-nb:n-1) contains the superdiagonal */ /* elements of the last NB columns of the reduced matrix; */ /* if UPLO = 'L', E(1:nb) contains the subdiagonal elements of */ /* the first NB columns of the reduced matrix. */ /* TAU (output) DOUBLE PRECISION array, dimension (N-1) */ /* The scalar factors of the elementary reflectors, stored in */ /* TAU(n-nb:n-1) if UPLO = 'U', and in TAU(1:nb) if UPLO = 'L'. */ /* See Further Details. */ /* W (output) DOUBLE PRECISION array, dimension (LDW,NB) */ /* The n-by-nb matrix W required to update the unreduced part */ /* of A. */ /* LDW (input) INTEGER */ /* The leading dimension of the array W. LDW >= max(1,N). */ /* Further Details */ /* =============== */ /* If UPLO = 'U', the matrix Q is represented as a product of elementary */ /* reflectors */ /* Q = H(n) H(n-1) . . . H(n-nb+1). */ /* Each H(i) has the form */ /* H(i) = I - tau * v * v' */ /* where tau is a real scalar, and v is a real vector with */ /* v(i:n) = 0 and v(i-1) = 1; v(1:i-1) is stored on exit in A(1:i-1,i), */ /* and tau in TAU(i-1). */ /* If UPLO = 'L', the matrix Q is represented as a product of elementary */ /* reflectors */ /* Q = H(1) H(2) . . . H(nb). */ /* Each H(i) has the form */ /* H(i) = I - tau * v * v' */ /* where tau is a real scalar, and v is a real vector with */ /* v(1:i) = 0 and v(i+1) = 1; v(i+1:n) is stored on exit in A(i+1:n,i), */ /* and tau in TAU(i). */ /* The elements of the vectors v together form the n-by-nb matrix V */ /* which is needed, with W, to apply the transformation to the unreduced */ /* part of the matrix, using a symmetric rank-2k update of the form: */ /* A := A - V*W' - W*V'. */ /* The contents of A on exit are illustrated by the following examples */ /* with n = 5 and nb = 2: */ /* if UPLO = 'U': if UPLO = 'L': */ /* ( a a a v4 v5 ) ( d ) */ /* ( a a v4 v5 ) ( 1 d ) */ /* ( a 1 v5 ) ( v1 1 a ) */ /* ( d 1 ) ( v1 v2 a a ) */ /* ( d ) ( v1 v2 a a a ) */ /* where d denotes a diagonal element of the reduced matrix, a denotes */ /* an element of the original matrix that is unchanged, and vi denotes */ /* an element of the vector defining H(i). */ /* ===================================================================== */ /* .. Parameters .. */ /* .. */ /* .. Local Scalars .. */ /* .. */ /* .. External Subroutines .. */ /* .. */ /* .. External Functions .. */ /* .. */ /* .. Intrinsic Functions .. */ /* .. */ /* .. Executable Statements .. */ /* Quick return if possible */ /* Parameter adjustments */ w_dim1 = *ldw; w_offset = w_dim1 + 1; w -= w_offset; --tau; --e; a_dim1 = *lda; a_offset = a_dim1 + 1; a -= a_offset; /* Function Body */ if(*n <= 0) { return 0; } if(lsame_(uplo, "U", 1L, 1L)) { /* Reduce last NB columns of upper triangle */ i__1 = *n - *nb + 1; for(i = *n; i >= i__1; --i) { iw = i - *n + *nb; if(i < *n) { /* Update A(1:i,i) */ i__2 = *n - i; dgemv_("No transpose", &i, &i__2, &c_b211, &a[(i + 1) * a_dim1 + 1], lda, &w[i + (iw + 1) * w_dim1], ldw, & c_b22, &a[i * a_dim1 + 1], &c__1, 12L); i__2 = *n - i; dgemv_("No transpose", &i, &i__2, &c_b211, &w[(iw + 1) * w_dim1 + 1], ldw, &a[i + (i + 1) * a_dim1], lda, & c_b22, &a[i * a_dim1 + 1], &c__1, 12L); } if(i > 1) { /* Generate elementary reflector H(i) to annihila te */ /* A(1:i-2,i) */ i__2 = i - 1; dlarfg_(&i__2, &a[i - 1 + i * a_dim1], &a[i * a_dim1 + 1], & c__1, &tau[i - 1]); e[i - 1] = a[i - 1 + i * a_dim1]; a[i - 1 + i * a_dim1] = 1.; /* Compute W(1:i-1,i) */ i__2 = i - 1; dsymv_("Upper", &i__2, &c_b22, &a[a_offset], lda, &a[i * a_dim1 + 1], &c__1, &c_b21, &w[iw * w_dim1 + 1], & c__1, 5L); if(i < *n) { i__2 = i - 1; i__3 = *n - i; dgemv_("Transpose", &i__2, &i__3, &c_b22, &w[(iw + 1) * w_dim1 + 1], ldw, &a[i * a_dim1 + 1], &c__1, & c_b21, &w[i + 1 + iw * w_dim1], &c__1, 9L); i__2 = i - 1; i__3 = *n - i; dgemv_("No transpose", &i__2, &i__3, &c_b211, &a[(i + 1) * a_dim1 + 1], lda, &w[i + 1 + iw * w_dim1], &c__1, &c_b22, &w[iw * w_dim1 + 1], &c__1, 12L); i__2 = i - 1; i__3 = *n - i; dgemv_("Transpose", &i__2, &i__3, &c_b22, &a[(i + 1) * a_dim1 + 1], lda, &a[i * a_dim1 + 1], &c__1, & c_b21, &w[i + 1 + iw * w_dim1], &c__1, 9L); i__2 = i - 1; i__3 = *n - i; dgemv_("No transpose", &i__2, &i__3, &c_b211, &w[(iw + 1) * w_dim1 + 1], ldw, &w[i + 1 + iw * w_dim1], & c__1, &c_b22, &w[iw * w_dim1 + 1], &c__1, 12L); } i__2 = i - 1; dscal_(&i__2, &tau[i - 1], &w[iw * w_dim1 + 1], &c__1); i__2 = i - 1; alpha = tau[i - 1] * -.5 * ddot_(&i__2, &w[iw * w_dim1 + 1], & c__1, &a[i * a_dim1 + 1], &c__1); i__2 = i - 1; daxpy_(&i__2, &alpha, &a[i * a_dim1 + 1], &c__1, &w[iw * w_dim1 + 1], &c__1); } /* L10: */ } } else { /* Reduce first NB columns of lower triangle */ i__1 = *nb; for(i = 1; i <= i__1; ++i) { /* Update A(i:n,i) */ i__2 = *n - i + 1; i__3 = i - 1; dgemv_("No transpose", &i__2, &i__3, &c_b211, &a[i + a_dim1], lda, &w[i + w_dim1], ldw, &c_b22, &a[i + i * a_dim1], &c__1, 12L); i__2 = *n - i + 1; i__3 = i - 1; dgemv_("No transpose", &i__2, &i__3, &c_b211, &w[i + w_dim1], ldw, &a[i + a_dim1], lda, &c_b22, &a[i + i * a_dim1], &c__1, 12L); if(i < *n) { /* Generate elementary reflector H(i) to annihila te */ /* A(i+2:n,i) */ i__2 = *n - i; /* Computing MIN */ i__3 = i + 2; dlarfg_(&i__2, &a[i + 1 + i * a_dim1], &a[min(i__3, *n) + i * a_dim1], &c__1, &tau[i]); e[i] = a[i + 1 + i * a_dim1]; a[i + 1 + i * a_dim1] = 1.; /* Compute W(i+1:n,i) */ i__2 = *n - i; dsymv_("Lower", &i__2, &c_b22, &a[i + 1 + (i + 1) * a_dim1], lda, &a[i + 1 + i * a_dim1], &c__1, &c_b21, &w[i + 1 + i * w_dim1], &c__1, 5L); i__2 = *n - i; i__3 = i - 1; dgemv_("Transpose", &i__2, &i__3, &c_b22, &w[i + 1 + w_dim1], ldw, &a[i + 1 + i * a_dim1], &c__1, &c_b21, &w[i * w_dim1 + 1], &c__1, 9L); i__2 = *n - i; i__3 = i - 1; dgemv_("No transpose", &i__2, &i__3, &c_b211, &a[i + 1 + a_dim1], lda, &w[i * w_dim1 + 1], &c__1, &c_b22, &w[i + 1 + i * w_dim1], &c__1, 12L); i__2 = *n - i; i__3 = i - 1; dgemv_("Transpose", &i__2, &i__3, &c_b22, &a[i + 1 + a_dim1], lda, &a[i + 1 + i * a_dim1], &c__1, &c_b21, &w[i * w_dim1 + 1], &c__1, 9L); i__2 = *n - i; i__3 = i - 1; dgemv_("No transpose", &i__2, &i__3, &c_b211, &w[i + 1 + w_dim1], ldw, &w[i * w_dim1 + 1], &c__1, &c_b22, &w[i + 1 + i * w_dim1], &c__1, 12L); i__2 = *n - i; dscal_(&i__2, &tau[i], &w[i + 1 + i * w_dim1], &c__1); i__2 = *n - i; alpha = tau[i] * -.5 * ddot_(&i__2, &w[i + 1 + i * w_dim1], & c__1, &a[i + 1 + i * a_dim1], &c__1); i__2 = *n - i; daxpy_(&i__2, &alpha, &a[i + 1 + i * a_dim1], &c__1, &w[i + 1 + i * w_dim1], &c__1); } /* L20: */ } } return 0; /* End of DLATRD */ } /* dlatrd_ */ /* Subroutine */ int dlarfg_(n, alpha, x, incx, tau) integer *n; doublereal *alpha, *x; integer *incx; doublereal *tau; { /* System generated locals */ integer i__1; doublereal d__1; /* Builtin functions */ double d_sign(); /* Local variables */ static doublereal beta; extern doublereal dnrm2_(); static integer j; extern /* Subroutine */ int dscal_(); static doublereal xnorm; extern doublereal dlapy2_(), dlamch_(); static doublereal safmin, rsafmn; static integer knt; /* -- LAPACK auxiliary routine (version 1.1) -- */ /* Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., */ /* Courant Institute, Argonne National Lab, and Rice University */ /* February 29, 1992 */ /* .. Scalar Arguments .. */ /* .. */ /* .. Array Arguments .. */ /* .. */ /* Purpose */ /* ======= */ /* DLARFG generates a real elementary reflector H of order n, such */ /* that */ /* H * ( alpha ) = ( beta ), H' * H = I. */ /* ( x ) ( 0 ) */ /* where alpha and beta are scalars, and x is an (n-1)-element real */ /* vector. H is represented in the form */ /* H = I - tau * ( 1 ) * ( 1 v' ) , */ /* ( v ) */ /* where tau is a real scalar and v is a real (n-1)-element */ /* vector. */ /* If the elements of x are all zero, then tau = 0 and H is taken to be */ /* the unit matrix. */ /* Otherwise 1 <= tau <= 2. */ /* Arguments */ /* ========= */ /* N (input) INTEGER */ /* The order of the elementary reflector. */ /* ALPHA (input/output) DOUBLE PRECISION */ /* On entry, the value alpha. */ /* On exit, it is overwritten with the value beta. */ /* X (input/output) DOUBLE PRECISION array, dimension */ /* (1+(N-2)*abs(INCX)) */ /* On entry, the vector x. */ /* On exit, it is overwritten with the vector v. */ /* INCX (input) INTEGER */ /* The increment between elements of X. INCX <> 0. */ /* TAU (output) DOUBLE PRECISION */ /* The value tau. */ /* ===================================================================== */ /* .. Parameters .. */ /* .. */ /* .. Local Scalars .. */ /* .. */ /* .. External Functions .. */ /* .. */ /* .. Intrinsic Functions .. */ /* .. */ /* .. External Subroutines .. */ /* .. */ /* .. Executable Statements .. */ /* Parameter adjustments */ --x; /* Function Body */ if(*n <= 1) { *tau = 0.; return 0; } i__1 = *n - 1; xnorm = dnrm2_(&i__1, &x[1], incx); if(xnorm == 0.) { /* H = I */ *tau = 0.; } else { /* general case */ d__1 = dlapy2_(alpha, &xnorm); beta = -d_sign(&d__1, alpha); safmin = dlamch_("S", 1L); if(abs(beta) < safmin) { /* XNORM, BETA may be inaccurate; scale X and recompute them */ rsafmn = 1. / safmin; knt = 0; L10: ++knt; i__1 = *n - 1; dscal_(&i__1, &rsafmn, &x[1], incx); beta *= rsafmn; *alpha *= rsafmn; if(abs(beta) < safmin) { goto L10; } /* New BETA is at most 1, at least SAFMIN */ i__1 = *n - 1; xnorm = dnrm2_(&i__1, &x[1], incx); d__1 = dlapy2_(alpha, &xnorm); beta = -d_sign(&d__1, alpha); *tau = (beta - *alpha) / beta; i__1 = *n - 1; d__1 = 1. / (*alpha - beta); dscal_(&i__1, &d__1, &x[1], incx); /* If ALPHA is subnormal, it may lose relative accuracy */ *alpha = beta; i__1 = knt; for(j = 1; j <= i__1; ++j) { *alpha *= safmin; /* L20: */ } } else { *tau = (beta - *alpha) / beta; i__1 = *n - 1; d__1 = 1. / (*alpha - beta); dscal_(&i__1, &d__1, &x[1], incx); *alpha = beta; } } return 0; /* End of DLARFG */ } /* dlarfg_ */ doublereal dlamch_(cmach, cmach_len) char *cmach; ftnlen cmach_len; { /* Initialized data */ static logical first = TRUE_; /* System generated locals */ integer i__1; doublereal ret_val; /* Builtin functions */ double pow_di(); /* Local variables */ static doublereal base; static integer beta; static doublereal emin, prec, emax; static integer imin, imax; static logical lrnd; static doublereal rmin, rmax, t, rmach; extern logical lsame_(); static doublereal small, sfmin; extern /* Subroutine */ int dlamc2_(); static integer it; static doublereal rnd, eps; /* -- LAPACK auxiliary routine (version 1.1) -- */ /* Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., */ /* Courant Institute, Argonne National Lab, and Rice University */ /* October 31, 1992 */ /* .. Scalar Arguments .. */ /* .. */ /* Purpose */ /* ======= */ /* DLAMCH determines double precision machine parameters. */ /* Arguments */ /* ========= */ /* CMACH (input) CHARACTER*1 */ /* Specifies the value to be returned by DLAMCH: */ /* = 'E' or 'e', DLAMCH := eps */ /* = 'S' or 's , DLAMCH := sfmin */ /* = 'B' or 'b', DLAMCH := base */ /* = 'P' or 'p', DLAMCH := eps*base */ /* = 'N' or 'n', DLAMCH := t */ /* = 'R' or 'r', DLAMCH := rnd */ /* = 'M' or 'm', DLAMCH := emin */ /* = 'U' or 'u', DLAMCH := rmin */ /* = 'L' or 'l', DLAMCH := emax */ /* = 'O' or 'o', DLAMCH := rmax */ /* where */ /* eps = relative machine precision */ /* sfmin = safe minimum, such that 1/sfmin does not overflow */ /* base = base of the machine */ /* prec = eps*base */ /* t = number of (base) digits in the mantissa */ /* rnd = 1.0 when rounding occurs in addition, 0.0 otherwise */ /* emin = minimum exponent before (gradual) underflow */ /* rmin = underflow threshold - base**(emin-1) */ /* emax = largest exponent before overflow */ /* rmax = overflow threshold - (base**emax)*(1-eps) */ /* ===================================================================== */ /* .. Parameters .. */ /* .. */ /* .. Local Scalars .. */ /* .. */ /* .. External Functions .. */ /* .. */ /* .. External Subroutines .. */ /* .. */ /* .. Save statement .. */ /* .. */ /* .. Data statements .. */ /* .. */ /* .. Executable Statements .. */ if(first) { first = FALSE_; dlamc2_(&beta, &it, &lrnd, &eps, &imin, &rmin, &imax, &rmax); base = (doublereal) beta; t = (doublereal) it; if(lrnd) { rnd = 1.; i__1 = 1 - it; eps = pow_di(&base, &i__1) / 2; } else { rnd = 0.; i__1 = 1 - it; eps = pow_di(&base, &i__1); } prec = eps * base; emin = (doublereal) imin; emax = (doublereal) imax; sfmin = rmin; small = 1. / rmax; if(small >= sfmin) { /* Use SMALL plus a bit, to avoid the possibility of rou nding */ /* causing overflow when computing 1/sfmin. */ sfmin = small * (eps + 1.); } } if(lsame_(cmach, "E", 1L, 1L)) { rmach = eps; } else if(lsame_(cmach, "S", 1L, 1L)) { rmach = sfmin; } else if(lsame_(cmach, "B", 1L, 1L)) { rmach = base; } else if(lsame_(cmach, "P", 1L, 1L)) { rmach = prec; } else if(lsame_(cmach, "N", 1L, 1L)) { rmach = t; } else if(lsame_(cmach, "R", 1L, 1L)) { rmach = rnd; } else if(lsame_(cmach, "M", 1L, 1L)) { rmach = emin; } else if(lsame_(cmach, "U", 1L, 1L)) { rmach = rmin; } else if(lsame_(cmach, "L", 1L, 1L)) { rmach = emax; } else if(lsame_(cmach, "O", 1L, 1L)) { rmach = rmax; } ret_val = rmach; return ret_val; /* End of DLAMCH */ } /* dlamch_ */ /* *********************************************************************** */ /* Subroutine */ int dlamc1_(beta, t, rnd, ieee1) integer *beta, *t; logical *rnd, *ieee1; { /* Initialized data */ static logical first = TRUE_; /* System generated locals */ doublereal d__1, d__2; /* Local variables */ static logical lrnd; static doublereal a, b, c, f; static integer lbeta; static doublereal savec; extern doublereal dlamc3_(); static logical lieee1; static doublereal t1, t2; static integer lt; static doublereal one, qtr; /* -- LAPACK auxiliary routine (version 1.1) -- */ /* Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., */ /* Courant Institute, Argonne National Lab, and Rice University */ /* October 31, 1992 */ /* .. Scalar Arguments .. */ /* .. */ /* Purpose */ /* ======= */ /* DLAMC1 determines the machine parameters given by BETA, T, RND, and */ /* IEEE1. */ /* Arguments */ /* ========= */ /* BETA (output) INTEGER */ /* The base of the machine. */ /* T (output) INTEGER */ /* The number of ( BETA ) digits in the mantissa. */ /* RND (output) LOGICAL */ /* Specifies whether proper rounding ( RND = .TRUE. ) or */ /* chopping ( RND = .FALSE. ) occurs in addition. This may not */ /* be a reliable guide to the way in which the machine performs */ /* its arithmetic. */ /* IEEE1 (output) LOGICAL */ /* Specifies whether rounding appears to be done in the IEEE */ /* 'round to nearest' style. */ /* Further Details */ /* =============== */ /* The routine is based on the routine ENVRON by Malcolm and */ /* incorporates suggestions by Gentleman and Marovich. See */ /* Malcolm M. A. (1972) Algorithms to reveal properties of */ /* floating-point arithmetic. Comms. of the ACM, 15, 949-951. */ /* Gentleman W. M. and Marovich S. B. (1974) More on algorithms */ /* that reveal properties of floating point arithmetic units. */ /* Comms. of the ACM, 17, 276-277. */ /* ===================================================================== */ /* .. Local Scalars .. */ /* .. */ /* .. External Functions .. */ /* .. */ /* .. Save statement .. */ /* .. */ /* .. Data statements .. */ /* .. */ /* .. Executable Statements .. */ if(first) { first = FALSE_; one = 1.; /* LBETA, LIEEE1, LT and LRND are the local values of BE TA, */ /* IEEE1, T and RND. */ /* Throughout this routine we use the function DLAMC3 to ens ure */ /* that relevant values are stored and not held in registers, or */ /* are not affected by optimizers. */ /* Compute a = 2.0**m with the smallest positive integer m s uch */ /* that */ /* fl( a + 1.0 ) = a. */ a = 1.; c = 1.; /* + WHILE( C.EQ.ONE )LOOP */ L10: if(c == one) { a *= 2; c = dlamc3_(&a, &one); d__1 = -a; c = dlamc3_(&c, &d__1); goto L10; } /* + END WHILE */ /* Now compute b = 2.0**m with the smallest positive integer m */ /* such that */ /* fl( a + b ) .gt. a. */ b = 1.; c = dlamc3_(&a, &b); /* + WHILE( C.EQ.A )LOOP */ L20: if(c == a) { b *= 2; c = dlamc3_(&a, &b); goto L20; } /* + END WHILE */ /* Now compute the base. a and c are neighbouring floating po int */ /* numbers in the interval ( beta**t, beta**( t + 1 ) ) and so */ /* their difference is beta. Adding 0.25 to c is to ensure that it */ /* is truncated to beta and not ( beta - 1 ). */ qtr = one / 4; savec = c; d__1 = -a; c = dlamc3_(&c, &d__1); lbeta = (integer)(c + qtr); /* Now determine whether rounding or chopping occurs, by addin g a */ /* bit less than beta/2 and a bit more than beta/2 to a. */ b = (doublereal) lbeta; d__1 = b / 2; d__2 = -b / 100; f = dlamc3_(&d__1, &d__2); c = dlamc3_(&f, &a); if(c == a) { lrnd = TRUE_; } else { lrnd = FALSE_; } d__1 = b / 2; d__2 = b / 100; f = dlamc3_(&d__1, &d__2); c = dlamc3_(&f, &a); if(lrnd && c == a) { lrnd = FALSE_; } /* Try and decide whether rounding is done in the IEEE 'round to */ /* nearest' style. B/2 is half a unit in the last place of the two */ /* numbers A and SAVEC. Furthermore, A is even, i.e. has last bit */ /* zero, and SAVEC is odd. Thus adding B/2 to A should not cha nge */ /* A, but adding B/2 to SAVEC should change SAVEC. */ d__1 = b / 2; t1 = dlamc3_(&d__1, &a); d__1 = b / 2; t2 = dlamc3_(&d__1, &savec); lieee1 = t1 == a && t2 > savec && lrnd; /* Now find the mantissa, t. It should be the integer part of */ /* log to the base beta of a, however it is safer to determine t */ /* by powering. So we find t as the smallest positive integer for */ /* which */ /* fl( beta**t + 1.0 ) = 1.0. */ lt = 0; a = 1.; c = 1.; /* + WHILE( C.EQ.ONE )LOOP */ L30: if(c == one) { ++lt; a *= lbeta; c = dlamc3_(&a, &one); d__1 = -a; c = dlamc3_(&c, &d__1); goto L30; } /* + END WHILE */ } *beta = lbeta; *t = lt; *rnd = lrnd; *ieee1 = lieee1; return 0; /* End of DLAMC1 */ } /* dlamc1_ */ /* *********************************************************************** */ /* Subroutine */ int dlamc2_(beta, t, rnd, eps, emin, rmin, emax, rmax) integer *beta, *t; logical *rnd; doublereal *eps; integer *emin; doublereal *rmin; integer *emax; doublereal *rmax; { /* Initialized data */ static logical first = TRUE_; static logical iwarn = FALSE_; /* Format strings */ static char fmt_9999[] = "(//\002 WARNING. The value EMIN may be incorre\ ct:-\002,\002 EMIN = \002,i8,/\002 If, after inspection, the value EMIN loo\ ks\002,\002 acceptable please comment out \002,/\002 the IF block as marked \ within the code of routine\002,\002 DLAMC2,\002,/\002 otherwise supply EMIN \ explicitly.\002,/)"; /* System generated locals */ integer i__1; doublereal d__1, d__2, d__3, d__4, d__5; /* Builtin functions */ double pow_di(); integer s_wsfe(), do_fio(), e_wsfe(); /* Local variables */ static logical ieee; static doublereal half; static logical lrnd; static doublereal leps, zero, a, b, c; static integer i, lbeta; static doublereal rbase; static integer lemin, lemax, gnmin; static doublereal small; static integer gpmin; static doublereal third, lrmin, lrmax, sixth; extern /* Subroutine */ int dlamc1_(); extern doublereal dlamc3_(); static logical lieee1; extern /* Subroutine */ int dlamc4_(), dlamc5_(); static integer lt, ngnmin, ngpmin; static doublereal one, two; /* Fortran I/O blocks */ static cilist io___231 = { 0, 6, 0, fmt_9999, 0 }; /* -- LAPACK auxiliary routine (version 1.1) -- */ /* Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., */ /* Courant Institute, Argonne National Lab, and Rice University */ /* October 31, 1992 */ /* .. Scalar Arguments .. */ /* .. */ /* Purpose */ /* ======= */ /* DLAMC2 determines the machine parameters specified in its argument */ /* list. */ /* Arguments */ /* ========= */ /* BETA (output) INTEGER */ /* The base of the machine. */ /* T (output) INTEGER */ /* The number of ( BETA ) digits in the mantissa. */ /* RND (output) LOGICAL */ /* Specifies whether proper rounding ( RND = .TRUE. ) or */ /* chopping ( RND = .FALSE. ) occurs in addition. This may not */ /* be a reliable guide to the way in which the machine performs */ /* its arithmetic. */ /* EPS (output) DOUBLE PRECISION */ /* The smallest positive number such that */ /* fl( 1.0 - EPS ) .LT. 1.0, */ /* where fl denotes the computed value. */ /* EMIN (output) INTEGER */ /* The minimum exponent before (gradual) underflow occurs. */ /* RMIN (output) DOUBLE PRECISION */ /* The smallest normalized number for the machine, given by */ /* BASE**( EMIN - 1 ), where BASE is the floating point value */ /* of BETA. */ /* EMAX (output) INTEGER */ /* The maximum exponent before overflow occurs. */ /* RMAX (output) DOUBLE PRECISION */ /* The largest positive number for the machine, given by */ /* BASE**EMAX * ( 1 - EPS ), where BASE is the floating point */ /* value of BETA. */ /* Further Details */ /* =============== */ /* The computation of EPS is based on a routine PARANOIA by */ /* W. Kahan of the University of California at Berkeley. */ /* ===================================================================== */ /* .. Local Scalars .. */ /* .. */ /* .. External Functions .. */ /* .. */ /* .. External Subroutines .. */ /* .. */ /* .. Intrinsic Functions .. */ /* .. */ /* .. Save statement .. */ /* .. */ /* .. Data statements .. */ /* .. */ /* .. Executable Statements .. */ if(first) { first = FALSE_; zero = 0.; one = 1.; two = 2.; /* LBETA, LT, LRND, LEPS, LEMIN and LRMIN are the local values of */ /* BETA, T, RND, EPS, EMIN and RMIN. */ /* Throughout this routine we use the function DLAMC3 to ens ure */ /* that relevant values are stored and not held in registers, or */ /* are not affected by optimizers. */ /* DLAMC1 returns the parameters LBETA, LT, LRND and LIEEE1. */ dlamc1_(&lbeta, &lt, &lrnd, &lieee1); /* Start to find EPS. */ b = (doublereal) lbeta; i__1 = -lt; a = pow_di(&b, &i__1); leps = a; /* Try some tricks to see whether or not this is the correct E PS. */ b = two / 3; half = one / 2; d__1 = -half; sixth = dlamc3_(&b, &d__1); third = dlamc3_(&sixth, &sixth); d__1 = -half; b = dlamc3_(&third, &d__1); b = dlamc3_(&b, &sixth); b = abs(b); if(b < leps) { b = leps; } leps = 1.; /* + WHILE( ( LEPS.GT.B ).AND.( B.GT.ZERO ) )LOOP */ L10: if(leps > b && b > zero) { leps = b; d__1 = half * leps; /* Computing 5th power */ d__3 = two, d__4 = d__3, d__3 *= d__3; /* Computing 2nd power */ d__5 = leps; d__2 = d__4 * (d__3 * d__3) * (d__5 * d__5); c = dlamc3_(&d__1, &d__2); d__1 = -c; c = dlamc3_(&half, &d__1); b = dlamc3_(&half, &c); d__1 = -b; c = dlamc3_(&half, &d__1); b = dlamc3_(&half, &c); goto L10; } /* + END WHILE */ if(a < leps) { leps = a; } /* Computation of EPS complete. */ /* Now find EMIN. Let A = + or - 1, and + or - (1 + BASE**(-3 )). */ /* Keep dividing A by BETA until (gradual) underflow occurs. T his */ /* is detected when we cannot recover the previous A. */ rbase = one / lbeta; small = one; for(i = 1; i <= 3; ++i) { d__1 = small * rbase; small = dlamc3_(&d__1, &zero); /* L20: */ } a = dlamc3_(&one, &small); dlamc4_(&ngpmin, &one, &lbeta); d__1 = -one; dlamc4_(&ngnmin, &d__1, &lbeta); dlamc4_(&gpmin, &a, &lbeta); d__1 = -a; dlamc4_(&gnmin, &d__1, &lbeta); ieee = FALSE_; if(ngpmin == ngnmin && gpmin == gnmin) { if(ngpmin == gpmin) { lemin = ngpmin; /* ( Non twos-complement machines, no gradual under flow; */ /* e.g., VAX ) */ } else if(gpmin - ngpmin == 3) { lemin = ngpmin - 1 + lt; ieee = TRUE_; /* ( Non twos-complement machines, with gradual und erflow; */ /* e.g., IEEE standard followers ) */ } else { lemin = min(ngpmin, gpmin); /* ( A guess; no known machine ) */ iwarn = TRUE_; } } else if(ngpmin == gpmin && ngnmin == gnmin) { if((i__1 = ngpmin - ngnmin, abs(i__1)) == 1) { lemin = max(ngpmin, ngnmin); /* ( Twos-complement machines, no gradual underflow ; */ /* e.g., CYBER 205 ) */ } else { lemin = min(ngpmin, ngnmin); /* ( A guess; no known machine ) */ iwarn = TRUE_; } } else if((i__1 = ngpmin - ngnmin, abs(i__1)) == 1 && gpmin == gnmin) { if(gpmin - min(ngpmin, ngnmin) == 3) { lemin = max(ngpmin, ngnmin) - 1 + lt; /* ( Twos-complement machines with gradual underflo w; */ /* no known machine ) */ } else { lemin = min(ngpmin, ngnmin); /* ( A guess; no known machine ) */ iwarn = TRUE_; } } else { /* Computing MIN */ i__1 = min(ngpmin, ngnmin), i__1 = min(i__1, gpmin); lemin = min(i__1, gnmin); /* ( A guess; no known machine ) */ iwarn = TRUE_; } /* ** */ /* Comment out this if block if EMIN is ok */ if(iwarn) { first = TRUE_; s_wsfe(&io___231); do_fio(&c__1, (char *)&lemin, (ftnlen)sizeof(integer)); e_wsfe(); } /* ** */ /* Assume IEEE arithmetic if we found denormalised numbers abo ve, */ /* or if arithmetic seems to round in the IEEE style, determi ned */ /* in routine DLAMC1. A true IEEE machine should have both thi ngs */ /* true; however, faulty machines may have one or the other. */ ieee = ieee || lieee1; /* Compute RMIN by successive division by BETA. We could comp ute */ /* RMIN as BASE**( EMIN - 1 ), but some machines underflow dur ing */ /* this computation. */ lrmin = 1.; i__1 = 1 - lemin; for(i = 1; i <= i__1; ++i) { d__1 = lrmin * rbase; lrmin = dlamc3_(&d__1, &zero); /* L30: */ } /* Finally, call DLAMC5 to compute EMAX and RMAX. */ dlamc5_(&lbeta, &lt, &lemin, &ieee, &lemax, &lrmax); } *beta = lbeta; *t = lt; *rnd = lrnd; *eps = leps; *emin = lemin; *rmin = lrmin; *emax = lemax; *rmax = lrmax; return 0; /* End of DLAMC2 */ } /* dlamc2_ */ /* *********************************************************************** */ doublereal dlamc3_(a, b) doublereal *a, *b; { /* System generated locals */ doublereal ret_val; /* -- LAPACK auxiliary routine (version 1.1) -- */ /* Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., */ /* Courant Institute, Argonne National Lab, and Rice University */ /* October 31, 1992 */ /* .. Scalar Arguments .. */ /* .. */ /* Purpose */ /* ======= */ /* DLAMC3 is intended to force A and B to be stored prior to doing */ /* the addition of A and B , for use in situations where optimizers */ /* might hold one of these in a register. */ /* Arguments */ /* ========= */ /* A, B (input) DOUBLE PRECISION */ /* The values A and B. */ /* ===================================================================== */ /* .. Executable Statements .. */ ret_val = *a + *b; return ret_val; /* End of DLAMC3 */ } /* dlamc3_ */ /* *********************************************************************** */ /* Subroutine */ int dlamc4_(emin, start, base) integer *emin; doublereal *start; integer *base; { /* System generated locals */ integer i__1; doublereal d__1; /* Local variables */ static doublereal zero, a; static integer i; static doublereal rbase, b1, b2, c1, c2, d1, d2; extern doublereal dlamc3_(); static doublereal one; /* -- LAPACK auxiliary routine (version 1.1) -- */ /* Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., */ /* Courant Institute, Argonne National Lab, and Rice University */ /* October 31, 1992 */ /* .. Scalar Arguments .. */ /* .. */ /* Purpose */ /* ======= */ /* DLAMC4 is a service routine for DLAMC2. */ /* Arguments */ /* ========= */ /* EMIN (output) EMIN */ /* The minimum exponent before (gradual) underflow, computed by */ /* setting A = START and dividing by BASE until the previous A */ /* can not be recovered. */ /* START (input) DOUBLE PRECISION */ /* The starting point for determining EMIN. */ /* BASE (input) INTEGER */ /* The base of the machine. */ /* ===================================================================== */ /* .. Local Scalars .. */ /* .. */ /* .. External Functions .. */ /* .. */ /* .. Executable Statements .. */ a = *start; one = 1.; rbase = one / *base; zero = 0.; *emin = 1; d__1 = a * rbase; b1 = dlamc3_(&d__1, &zero); c1 = a; c2 = a; d1 = a; d2 = a; /* + WHILE( ( C1.EQ.A ).AND.( C2.EQ.A ).AND. */ /* $ ( D1.EQ.A ).AND.( D2.EQ.A ) )LOOP */ L10: if(c1 == a && c2 == a && d1 == a && d2 == a) { --(*emin); a = b1; d__1 = a / *base; b1 = dlamc3_(&d__1, &zero); d__1 = b1 * *base; c1 = dlamc3_(&d__1, &zero); d1 = zero; i__1 = *base; for(i = 1; i <= i__1; ++i) { d1 += b1; /* L20: */ } d__1 = a * rbase; b2 = dlamc3_(&d__1, &zero); d__1 = b2 / rbase; c2 = dlamc3_(&d__1, &zero); d2 = zero; i__1 = *base; for(i = 1; i <= i__1; ++i) { d2 += b2; /* L30: */ } goto L10; } /* + END WHILE */ return 0; /* End of DLAMC4 */ } /* dlamc4_ */ /* *********************************************************************** */ /* Subroutine */ int dlamc5_(beta, p, emin, ieee, emax, rmax) integer *beta, *p, *emin; logical *ieee; integer *emax; doublereal *rmax; { /* System generated locals */ integer i__1; doublereal d__1; /* Local variables */ static integer lexp; static doublereal oldy; static integer uexp, i; static doublereal y, z; static integer nbits; extern doublereal dlamc3_(); static doublereal recbas; static integer exbits, expsum, try_; /* -- LAPACK auxiliary routine (version 1.1) -- */ /* Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., */ /* Courant Institute, Argonne National Lab, and Rice University */ /* October 31, 1992 */ /* .. Scalar Arguments .. */ /* .. */ /* Purpose */ /* ======= */ /* DLAMC5 attempts to compute RMAX, the largest machine floating-point */ /* number, without overflow. It assumes that EMAX + abs(EMIN) sum */ /* approximately to a power of 2. It will fail on machines where this */ /* assumption does not hold, for example, the Cyber 205 (EMIN = -28625, */ /* EMAX = 28718). It will also fail if the value supplied for EMIN is */ /* too large (i.e. too close to zero), probably with overflow. */ /* Arguments */ /* ========= */ /* BETA (input) INTEGER */ /* The base of floating-point arithmetic. */ /* P (input) INTEGER */ /* The number of base BETA digits in the mantissa of a */ /* floating-point value. */ /* EMIN (input) INTEGER */ /* The minimum exponent before (gradual) underflow. */ /* IEEE (input) LOGICAL */ /* A logical flag specifying whether or not the arithmetic */ /* system is thought to comply with the IEEE standard. */ /* EMAX (output) INTEGER */ /* The largest exponent before overflow */ /* RMAX (output) DOUBLE PRECISION */ /* The largest machine floating-point number. */ /* ===================================================================== */ /* .. Parameters .. */ /* .. */ /* .. Local Scalars .. */ /* .. */ /* .. External Functions .. */ /* .. */ /* .. Intrinsic Functions .. */ /* .. */ /* .. Executable Statements .. */ /* First compute LEXP and UEXP, two powers of 2 that bound */ /* abs(EMIN). We then assume that EMAX + abs(EMIN) will sum */ /* approximately to the bound that is closest to abs(EMIN). */ /* (EMAX is the exponent of the required number RMAX). */ lexp = 1; exbits = 1; L10: try_ = lexp << 1; if(try_ <= -(*emin)) { lexp = try_; ++exbits; goto L10; } if(lexp == -(*emin)) { uexp = lexp; } else { uexp = try_; ++exbits; } /* Now -LEXP is less than or equal to EMIN, and -UEXP is greater */ /* than or equal to EMIN. EXBITS is the number of bits needed to */ /* store the exponent. */ if(uexp + *emin > -lexp - *emin) { expsum = lexp << 1; } else { expsum = uexp << 1; } /* EXPSUM is the exponent range, approximately equal to */ /* EMAX - EMIN + 1 . */ *emax = expsum + *emin - 1; nbits = exbits + 1 + *p; /* NBITS is the total number of bits needed to store a */ /* floating-point number. */ if(nbits % 2 == 1 && *beta == 2) { /* Either there are an odd number of bits used to store a */ /* floating-point number, which is unlikely, or some bits are */ /* not used in the representation of numbers, which is possible , */ /* (e.g. Cray machines) or the mantissa has an implicit bit, */ /* (e.g. IEEE machines, Dec Vax machines), which is perhaps the */ /* most likely. We have to assume the last alternative. */ /* If this is true, then we need to reduce EMAX by one because */ /* there must be some way of representing zero in an implicit-b it */ /* system. On machines like Cray, we are reducing EMAX by one */ /* unnecessarily. */ --(*emax); } if(*ieee) { /* Assume we are on an IEEE machine which reserves one exponent */ /* for infinity and NaN. */ --(*emax); } /* Now create RMAX, the largest machine number, which should */ /* be equal to (1.0 - BETA**(-P)) * BETA**EMAX . */ /* First compute 1.0 - BETA**(-P), being careful that the */ /* result is less than 1.0 . */ recbas = 1. / *beta; z = *beta - 1.; y = 0.; i__1 = *p; for(i = 1; i <= i__1; ++i) { z *= recbas; if(y < 1.) { oldy = y; } y = dlamc3_(&y, &z); /* L20: */ } if(y >= 1.) { y = oldy; } /* Now multiply by BETA**EMAX to get RMAX. */ i__1 = *emax; for(i = 1; i <= i__1; ++i) { d__1 = y * *beta; y = dlamc3_(&d__1, &c_b21); /* L30: */ } *rmax = y; return 0; /* End of DLAMC5 */ } /* dlamc5_ */ doublereal dlapy2_(x, y) doublereal *x, *y; { /* System generated locals */ doublereal ret_val, d__1; /* Builtin functions */ double sqrt(); /* Local variables */ static doublereal xabs, yabs, w, z; /* -- LAPACK auxiliary routine (version 1.1) -- */ /* Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., */ /* Courant Institute, Argonne National Lab, and Rice University */ /* October 31, 1992 */ /* .. Scalar Arguments .. */ /* .. */ /* Purpose */ /* ======= */ /* DLAPY2 returns sqrt(x**2+y**2), taking care not to cause unnecessary */ /* overflow. */ /* Arguments */ /* ========= */ /* X (input) DOUBLE PRECISION */ /* Y (input) DOUBLE PRECISION */ /* X and Y specify the values x and y. */ /* ===================================================================== */ /* .. Parameters .. */ /* .. */ /* .. Local Scalars .. */ /* .. */ /* .. Intrinsic Functions .. */ /* .. */ /* .. Executable Statements .. */ xabs = abs(*x); yabs = abs(*y); w = max(xabs, yabs); z = min(xabs, yabs); if(z == 0.) { ret_val = w; } else { /* Computing 2nd power */ d__1 = z / w; ret_val = w * sqrt(d__1 * d__1 + 1.); } return ret_val; /* End of DLAPY2 */ } /* dlapy2_ */ integer ilaenv_(ispec, name, opts, n1, n2, n3, n4, name_len, opts_len) integer *ispec; char *name, *opts; integer *n1, *n2, *n3, *n4; ftnlen name_len; ftnlen opts_len; { /* System generated locals */ integer ret_val; /* Builtin functions */ /* Subroutine */ int s_copy(); integer s_cmp(); /* Local variables */ static integer i; static logical cname, sname; static integer nbmin; static char c1[1], c2[2], c3[3], c4[2]; static integer ic, nb, iz, nx; static char subnam[6]; /* -- LAPACK auxiliary routine (preliminary version) -- */ /* Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., */ /* Courant Institute, Argonne National Lab, and Rice University */ /* February 20, 1992 */ /* .. Scalar Arguments .. */ /* .. */ /* Purpose */ /* ======= */ /* ILAENV is called from the LAPACK routines to choose problem-dependent */ /* parameters for the local environment. See ISPEC for a description of */ /* the parameters. */ /* This version provides a set of parameters which should give good, */ /* but not optimal, performance on many of the currently available */ /* computers. Users are encouraged to modify this subroutine to set */ /* the tuning parameters for their particular machine using the option */ /* and problem size information in the arguments. */ /* This routine will not function correctly if it is converted to all */ /* lower case. Converting it to all upper case is allowed. */ /* Arguments */ /* ========= */ /* ISPEC (input) INTEGER */ /* Specifies the parameter to be returned as the value of */ /* ILAENV. */ /* = 1: the optimal blocksize; if this value is 1, an unblocked */ /* algorithm will give the best performance. */ /* = 2: the minimum block size for which the block routine */ /* should be used; if the usable block size is less than */ /* this value, an unblocked routine should be used. */ /* = 3: the crossover point (in a block routine, for N less */ /* than this value, an unblocked routine should be used) */ /* = 4: the number of shifts, used in the nonsymmetric */ /* eigenvalue routines */ /* = 5: the minimum column dimension for blocking to be used; */ /* rectangular blocks must have dimension at least k by m, */ /* where k is given by ILAENV(2,...) and m by ILAENV(5,...) */ /* = 6: the crossover point for the SVD (when reducing an m by n */ /* matrix to bidiagonal form, if max(m,n)/min(m,n) exceeds */ /* this value, a QR factorization is used first to reduce */ /* the matrix to a triangular form.) */ /* = 7: the number of processors */ /* = 8: the crossover point for the multishift QR and QZ methods */ /* for nonsymmetric eigenvalue problems. */ /* NAME (input) CHARACTER*(*) */ /* The name of the calling subroutine, in either upper case or */ /* lower case. */ /* OPTS (input) CHARACTER*(*) */ /* The character options to the subroutine NAME, concatenated */ /* into a single character string. For example, UPLO = 'U', */ /* TRANS = 'T', and DIAG = 'N' for a triangular routine would */ /* be specified as OPTS = 'UTN'. */ /* N1 (input) INTEGER */ /* N2 (input) INTEGER */ /* N3 (input) INTEGER */ /* N4 (input) INTEGER */ /* Problem dimensions for the subroutine NAME; these may not all */ /* be required. */ /* (ILAENV) (output) INTEGER */ /* >= 0: the value of the parameter specified by ISPEC */ /* < 0: if ILAENV = -k, the k-th argument had an illegal value. */ /* Further Details */ /* =============== */ /* The following conventions have been used when calling ILAENV from the */ /* LAPACK routines: */ /* 1) OPTS is a concatenation of all of the character options to */ /* subroutine NAME, in the same order that they appear in the */ /* argument list for NAME, even if they are not used in determining */ /* the value of the parameter specified by ISPEC. */ /* 2) The problem dimensions N1, N2, N3, N4 are specified in the order */ /* that they appear in the argument list for NAME. N1 is used */ /* first, N2 second, and so on, and unused problem dimensions are */ /* passed a value of -1. */ /* 3) The parameter value returned by ILAENV is checked for validity in */ /* the calling subroutine. For example, ILAENV is used to retrieve */ /* the optimal blocksize for STRTRI as follows: */ /* NB = ILAENV( 1, 'STRTRI', UPLO // DIAG, N, -1, -1, -1 ) */ /* IF( NB.LE.1 ) NB = MAX( 1, N ) */ /* ===================================================================== */ /* .. Local Scalars .. */ /* .. */ /* .. Intrinsic Functions .. */ /* .. */ /* .. Executable Statements .. */ switch((int)*ispec) { case 1: goto L100; case 2: goto L100; case 3: goto L100; case 4: goto L400; case 5: goto L500; case 6: goto L600; case 7: goto L700; case 8: goto L800; } /* Invalid value for ISPEC */ ret_val = -1; return ret_val; L100: /* Convert NAME to upper case if the first character is lower case. */ ret_val = 1; s_copy(subnam, name, 6L, name_len); ic = *subnam; iz = 'Z'; if(iz == 90 || iz == 122) { /* ASCII character set */ if(ic >= 97 && ic <= 122) { *subnam = (char)(ic - 32); for(i = 2; i <= 6; ++i) { ic = (integer) subnam[i - 1]; if(ic >= 97 && ic <= 122) { subnam[i - 1] = (char)(ic - 32); } /* L10: */ } } } else if(iz == 233 || iz == 169) { /* EBCDIC character set */ if(ic >= 129 && ic <= 137 || ic >= 145 && ic <= 153 || ic >= 162 && ic <= 169) { *subnam = (char)(ic + 64); for(i = 2; i <= 6; ++i) { ic = (integer) subnam[i - 1]; if(ic >= 129 && ic <= 137 || ic >= 145 && ic <= 153 || ic >= 162 && ic <= 169) { subnam[i - 1] = (char)(ic + 64); } /* L20: */ } } } else if(iz == 218 || iz == 250) { /* Prime machines: ASCII+128 */ if(ic >= 225 && ic <= 250) { *subnam = (char)(ic - 32); for(i = 2; i <= 6; ++i) { ic = (integer) subnam[i - 1]; if(ic >= 225 && ic <= 250) { subnam[i - 1] = (char)(ic - 32); } /* L30: */ } } } *c1 = *subnam; sname = *c1 == 'S' || *c1 == 'D'; cname = *c1 == 'C' || *c1 == 'Z'; if(!(cname || sname)) { return ret_val; } s_copy(c2, subnam + 1, 2L, 2L); s_copy(c3, subnam + 3, 3L, 3L); s_copy(c4, c3 + 1, 2L, 2L); switch((int)*ispec) { case 1: goto L110; case 2: goto L200; case 3: goto L300; } L110: /* ISPEC = 1: block size */ /* In these examples, separate code is provided for setting NB for */ /* real and complex. We assume that NB will take the same value in */ /* single or double precision. */ nb = 1; if(s_cmp(c2, "GE", 2L, 2L) == 0) { if(s_cmp(c3, "TRF", 3L, 3L) == 0) { if(sname) { nb = 64; } else { nb = 64; } } else if(s_cmp(c3, "QRF", 3L, 3L) == 0 || s_cmp(c3, "RQF", 3L, 3L) == 0 || s_cmp(c3, "LQF", 3L, 3L) == 0 || s_cmp(c3, "QLF", 3L, 3L) == 0) { if(sname) { nb = 32; } else { nb = 32; } } else if(s_cmp(c3, "HRD", 3L, 3L) == 0) { if(sname) { nb = 32; } else { nb = 32; } } else if(s_cmp(c3, "BRD", 3L, 3L) == 0) { if(sname) { nb = 32; } else { nb = 32; } } else if(s_cmp(c3, "TRI", 3L, 3L) == 0) { if(sname) { nb = 64; } else { nb = 64; } } } else if(s_cmp(c2, "PO", 2L, 2L) == 0) { if(s_cmp(c3, "TRF", 3L, 3L) == 0) { if(sname) { nb = 64; } else { nb = 64; } } } else if(s_cmp(c2, "SY", 2L, 2L) == 0) { if(s_cmp(c3, "TRF", 3L, 3L) == 0) { if(sname) { nb = 64; } else { nb = 64; } } else if(sname && s_cmp(c3, "TRD", 3L, 3L) == 0) { nb = 1; } else if(sname && s_cmp(c3, "GST", 3L, 3L) == 0) { nb = 64; } } else if(cname && s_cmp(c2, "HE", 2L, 2L) == 0) { if(s_cmp(c3, "TRF", 3L, 3L) == 0) { nb = 64; } else if(s_cmp(c3, "TRD", 3L, 3L) == 0) { nb = 1; } else if(s_cmp(c3, "GST", 3L, 3L) == 0) { nb = 64; } } else if(sname && s_cmp(c2, "OR", 2L, 2L) == 0) { if(*c3 == 'G') { if(s_cmp(c4, "QR", 2L, 2L) == 0 || s_cmp(c4, "RQ", 2L, 2L) == 0 || s_cmp(c4, "LQ", 2L, 2L) == 0 || s_cmp(c4, "QL", 2L, 2L) == 0 || s_cmp(c4, "HR", 2L, 2L) == 0 || s_cmp(c4, "TR", 2L, 2L) == 0 || s_cmp(c4, "BR", 2L, 2L) == 0) { nb = 32; } } else if(*c3 == 'M') { if(s_cmp(c4, "QR", 2L, 2L) == 0 || s_cmp(c4, "RQ", 2L, 2L) == 0 || s_cmp(c4, "LQ", 2L, 2L) == 0 || s_cmp(c4, "QL", 2L, 2L) == 0 || s_cmp(c4, "HR", 2L, 2L) == 0 || s_cmp(c4, "TR", 2L, 2L) == 0 || s_cmp(c4, "BR", 2L, 2L) == 0) { nb = 32; } } } else if(cname && s_cmp(c2, "UN", 2L, 2L) == 0) { if(*c3 == 'G') { if(s_cmp(c4, "QR", 2L, 2L) == 0 || s_cmp(c4, "RQ", 2L, 2L) == 0 || s_cmp(c4, "LQ", 2L, 2L) == 0 || s_cmp(c4, "QL", 2L, 2L) == 0 || s_cmp(c4, "HR", 2L, 2L) == 0 || s_cmp(c4, "TR", 2L, 2L) == 0 || s_cmp(c4, "BR", 2L, 2L) == 0) { nb = 32; } } else if(*c3 == 'M') { if(s_cmp(c4, "QR", 2L, 2L) == 0 || s_cmp(c4, "RQ", 2L, 2L) == 0 || s_cmp(c4, "LQ", 2L, 2L) == 0 || s_cmp(c4, "QL", 2L, 2L) == 0 || s_cmp(c4, "HR", 2L, 2L) == 0 || s_cmp(c4, "TR", 2L, 2L) == 0 || s_cmp(c4, "BR", 2L, 2L) == 0) { nb = 32; } } } else if(s_cmp(c2, "GB", 2L, 2L) == 0) { if(s_cmp(c3, "TRF", 3L, 3L) == 0) { if(sname) { if(*n4 <= 64) { nb = 1; } else { nb = 32; } } else { if(*n4 <= 64) { nb = 1; } else { nb = 32; } } } } else if(s_cmp(c2, "PB", 2L, 2L) == 0) { if(s_cmp(c3, "TRF", 3L, 3L) == 0) { if(sname) { if(*n2 <= 64) { nb = 1; } else { nb = 32; } } else { if(*n2 <= 64) { nb = 1; } else { nb = 32; } } } } else if(s_cmp(c2, "TR", 2L, 2L) == 0) { if(s_cmp(c3, "TRI", 3L, 3L) == 0) { if(sname) { nb = 64; } else { nb = 64; } } } else if(s_cmp(c2, "LA", 2L, 2L) == 0) { if(s_cmp(c3, "UUM", 3L, 3L) == 0) { if(sname) { nb = 64; } else { nb = 64; } } } else if(sname && s_cmp(c2, "ST", 2L, 2L) == 0) { if(s_cmp(c3, "EBZ", 3L, 3L) == 0) { nb = 1; } } ret_val = nb; return ret_val; L200: /* ISPEC = 2: minimum block size */ nbmin = 2; if(s_cmp(c2, "GE", 2L, 2L) == 0) { if(s_cmp(c3, "QRF", 3L, 3L) == 0 || s_cmp(c3, "RQF", 3L, 3L) == 0 || s_cmp(c3, "LQF", 3L, 3L) == 0 || s_cmp(c3, "QLF", 3L, 3L) == 0) { if(sname) { nbmin = 2; } else { nbmin = 2; } } else if(s_cmp(c3, "HRD", 3L, 3L) == 0) { if(sname) { nbmin = 2; } else { nbmin = 2; } } else if(s_cmp(c3, "BRD", 3L, 3L) == 0) { if(sname) { nbmin = 2; } else { nbmin = 2; } } else if(s_cmp(c3, "TRI", 3L, 3L) == 0) { if(sname) { nbmin = 2; } else { nbmin = 2; } } } else if(s_cmp(c2, "SY", 2L, 2L) == 0) { if(s_cmp(c3, "TRF", 3L, 3L) == 0) { if(sname) { nbmin = 2; } else { nbmin = 2; } } else if(sname && s_cmp(c3, "TRD", 3L, 3L) == 0) { nbmin = 2; } } else if(cname && s_cmp(c2, "HE", 2L, 2L) == 0) { if(s_cmp(c3, "TRD", 3L, 3L) == 0) { nbmin = 2; } } else if(sname && s_cmp(c2, "OR", 2L, 2L) == 0) { if(*c3 == 'G') { if(s_cmp(c4, "QR", 2L, 2L) == 0 || s_cmp(c4, "RQ", 2L, 2L) == 0 || s_cmp(c4, "LQ", 2L, 2L) == 0 || s_cmp(c4, "QL", 2L, 2L) == 0 || s_cmp(c4, "HR", 2L, 2L) == 0 || s_cmp(c4, "TR", 2L, 2L) == 0 || s_cmp(c4, "BR", 2L, 2L) == 0) { nbmin = 2; } } else if(*c3 == 'M') { if(s_cmp(c4, "QR", 2L, 2L) == 0 || s_cmp(c4, "RQ", 2L, 2L) == 0 || s_cmp(c4, "LQ", 2L, 2L) == 0 || s_cmp(c4, "QL", 2L, 2L) == 0 || s_cmp(c4, "HR", 2L, 2L) == 0 || s_cmp(c4, "TR", 2L, 2L) == 0 || s_cmp(c4, "BR", 2L, 2L) == 0) { nbmin = 2; } } } else if(cname && s_cmp(c2, "UN", 2L, 2L) == 0) { if(*c3 == 'G') { if(s_cmp(c4, "QR", 2L, 2L) == 0 || s_cmp(c4, "RQ", 2L, 2L) == 0 || s_cmp(c4, "LQ", 2L, 2L) == 0 || s_cmp(c4, "QL", 2L, 2L) == 0 || s_cmp(c4, "HR", 2L, 2L) == 0 || s_cmp(c4, "TR", 2L, 2L) == 0 || s_cmp(c4, "BR", 2L, 2L) == 0) { nbmin = 2; } } else if(*c3 == 'M') { if(s_cmp(c4, "QR", 2L, 2L) == 0 || s_cmp(c4, "RQ", 2L, 2L) == 0 || s_cmp(c4, "LQ", 2L, 2L) == 0 || s_cmp(c4, "QL", 2L, 2L) == 0 || s_cmp(c4, "HR", 2L, 2L) == 0 || s_cmp(c4, "TR", 2L, 2L) == 0 || s_cmp(c4, "BR", 2L, 2L) == 0) { nbmin = 2; } } } ret_val = nbmin; return ret_val; L300: /* ISPEC = 3: crossover point */ nx = 0; if(s_cmp(c2, "GE", 2L, 2L) == 0) { if(s_cmp(c3, "QRF", 3L, 3L) == 0 || s_cmp(c3, "RQF", 3L, 3L) == 0 || s_cmp(c3, "LQF", 3L, 3L) == 0 || s_cmp(c3, "QLF", 3L, 3L) == 0) { if(sname) { nx = 128; } else { nx = 128; } } else if(s_cmp(c3, "HRD", 3L, 3L) == 0) { if(sname) { nx = 128; } else { nx = 128; } } else if(s_cmp(c3, "BRD", 3L, 3L) == 0) { if(sname) { nx = 128; } else { nx = 128; } } } else if(s_cmp(c2, "SY", 2L, 2L) == 0) { if(sname && s_cmp(c3, "TRD", 3L, 3L) == 0) { nx = 1; } } else if(cname && s_cmp(c2, "HE", 2L, 2L) == 0) { if(s_cmp(c3, "TRD", 3L, 3L) == 0) { nx = 1; } } else if(sname && s_cmp(c2, "OR", 2L, 2L) == 0) { if(*c3 == 'G') { if(s_cmp(c4, "QR", 2L, 2L) == 0 || s_cmp(c4, "RQ", 2L, 2L) == 0 || s_cmp(c4, "LQ", 2L, 2L) == 0 || s_cmp(c4, "QL", 2L, 2L) == 0 || s_cmp(c4, "HR", 2L, 2L) == 0 || s_cmp(c4, "TR", 2L, 2L) == 0 || s_cmp(c4, "BR", 2L, 2L) == 0) { nx = 128; } } } else if(cname && s_cmp(c2, "UN", 2L, 2L) == 0) { if(*c3 == 'G') { if(s_cmp(c4, "QR", 2L, 2L) == 0 || s_cmp(c4, "RQ", 2L, 2L) == 0 || s_cmp(c4, "LQ", 2L, 2L) == 0 || s_cmp(c4, "QL", 2L, 2L) == 0 || s_cmp(c4, "HR", 2L, 2L) == 0 || s_cmp(c4, "TR", 2L, 2L) == 0 || s_cmp(c4, "BR", 2L, 2L) == 0) { nx = 128; } } } ret_val = nx; return ret_val; L400: /* ISPEC = 4: number of shifts (used by xHSEQR) */ ret_val = 6; return ret_val; L500: /* ISPEC = 5: minimum column dimension (not used) */ ret_val = 2; return ret_val; L600: /* ISPEC = 6: crossover point for SVD (used by xGELSS and xGESVD) */ ret_val = (integer)((real) min(*n1, *n2) * (float)1.6); return ret_val; L700: /* ISPEC = 7: number of processors (not used) */ ret_val = 1; return ret_val; L800: /* ISPEC = 8: crossover point for multishift (used by xHSEQR) */ ret_val = 50; return ret_val; /* End of ILAENV */ } /* ilaenv_ */ doublereal dlansy_(norm, uplo, n, a, lda, work, norm_len, uplo_len) char *norm, *uplo; integer *n; doublereal *a; integer *lda; doublereal *work; ftnlen norm_len; ftnlen uplo_len; { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2; doublereal ret_val, d__1, d__2, d__3; /* Builtin functions */ double sqrt(); /* Local variables */ static doublereal absa; static integer i, j; static doublereal scale; extern logical lsame_(); static doublereal value; extern /* Subroutine */ int dlassq_(); static doublereal sum; /* -- LAPACK auxiliary routine (version 1.1) -- */ /* Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., */ /* Courant Institute, Argonne National Lab, and Rice University */ /* October 31, 1992 */ /* .. Scalar Arguments .. */ /* .. */ /* .. Array Arguments .. */ /* .. */ /* Purpose */ /* ======= */ /* DLANSY returns the value of the one norm, or the Frobenius norm, or */ /* the infinity norm, or the element of largest absolute value of a */ /* real symmetric matrix A. */ /* Description */ /* =========== */ /* DLANSY returns the value */ /* DLANSY = ( max(abs(A(i,j))), NORM = 'M' or 'm' */ /* ( */ /* ( norm1(A), NORM = '1', 'O' or 'o' */ /* ( */ /* ( normI(A), NORM = 'I' or 'i' */ /* ( */ /* ( normF(A), NORM = 'F', 'f', 'E' or 'e' */ /* where norm1 denotes the one norm of a matrix (maximum column sum), */ /* normI denotes the infinity norm of a matrix (maximum row sum) and */ /* normF denotes the Frobenius norm of a matrix (square root of sum of */ /* squares). Note that max(abs(A(i,j))) is not a matrix norm. */ /* Arguments */ /* ========= */ /* NORM (input) CHARACTER*1 */ /* Specifies the value to be returned in DLANSY as described */ /* above. */ /* UPLO (input) CHARACTER*1 */ /* Specifies whether the upper or lower triangular part of the */ /* symmetric matrix A is to be referenced. */ /* = 'U': Upper triangular part of A is referenced */ /* = 'L': Lower triangular part of A is referenced */ /* N (input) INTEGER */ /* The order of the matrix A. N >= 0. When N = 0, DLANSY is */ /* set to zero. */ /* A (input) DOUBLE PRECISION array, dimension (LDA,N) */ /* The symmetric matrix A. If UPLO = 'U', the leading n by n */ /* upper triangular part of A contains the upper triangular part */ /* of the matrix A, and the strictly lower triangular part of A */ /* is not referenced. If UPLO = 'L', the leading n by n lower */ /* triangular part of A contains the lower triangular part of */ /* the matrix A, and the strictly upper triangular part of A is */ /* not referenced. */ /* LDA (input) INTEGER */ /* The leading dimension of the array A. LDA >= max(N,1). */ /* WORK (workspace) DOUBLE PRECISION array, dimension (LWORK), */ /* where LWORK >= N when NORM = 'I' or '1' or 'O'; otherwise, */ /* WORK is not referenced. */ /* ===================================================================== */ /* .. Parameters .. */ /* .. */ /* .. Local Scalars .. */ /* .. */ /* .. External Subroutines .. */ /* .. */ /* .. External Functions .. */ /* .. */ /* .. Intrinsic Functions .. */ /* .. */ /* .. Executable Statements .. */ /* Parameter adjustments */ --work; a_dim1 = *lda; a_offset = a_dim1 + 1; a -= a_offset; /* Function Body */ if(*n == 0) { value = 0.; } else if(lsame_(norm, "M", 1L, 1L)) { /* Find max(abs(A(i,j))). */ value = 0.; if(lsame_(uplo, "U", 1L, 1L)) { i__1 = *n; for(j = 1; j <= i__1; ++j) { i__2 = j; for(i = 1; i <= i__2; ++i) { /* Computing MAX */ d__2 = value, d__3 = (d__1 = a[i + j * a_dim1], abs(d__1)) ; value = max(d__2, d__3); /* L10: */ } /* L20: */ } } else { i__1 = *n; for(j = 1; j <= i__1; ++j) { i__2 = *n; for(i = j; i <= i__2; ++i) { /* Computing MAX */ d__2 = value, d__3 = (d__1 = a[i + j * a_dim1], abs(d__1)) ; value = max(d__2, d__3); /* L30: */ } /* L40: */ } } } else if(lsame_(norm, "I", 1L, 1L) || lsame_(norm, "O", 1L, 1L) || * norm == '1') { /* Find normI(A) ( = norm1(A), since A is symmetric). */ value = 0.; if(lsame_(uplo, "U", 1L, 1L)) { i__1 = *n; for(j = 1; j <= i__1; ++j) { sum = 0.; i__2 = j - 1; for(i = 1; i <= i__2; ++i) { absa = (d__1 = a[i + j * a_dim1], abs(d__1)); sum += absa; work[i] += absa; /* L50: */ } work[j] = sum + (d__1 = a[j + j * a_dim1], abs(d__1)); /* L60: */ } i__1 = *n; for(i = 1; i <= i__1; ++i) { /* Computing MAX */ d__1 = value, d__2 = work[i]; value = max(d__1, d__2); /* L70: */ } } else { i__1 = *n; for(i = 1; i <= i__1; ++i) { work[i] = 0.; /* L80: */ } i__1 = *n; for(j = 1; j <= i__1; ++j) { sum = work[j] + (d__1 = a[j + j * a_dim1], abs(d__1)); i__2 = *n; for(i = j + 1; i <= i__2; ++i) { absa = (d__1 = a[i + j * a_dim1], abs(d__1)); sum += absa; work[i] += absa; /* L90: */ } value = max(value, sum); /* L100: */ } } } else if(lsame_(norm, "F", 1L, 1L) || lsame_(norm, "E", 1L, 1L)) { /* Find normF(A). */ scale = 0.; sum = 1.; if(lsame_(uplo, "U", 1L, 1L)) { i__1 = *n; for(j = 2; j <= i__1; ++j) { i__2 = j - 1; dlassq_(&i__2, &a[j * a_dim1 + 1], &c__1, &scale, &sum); /* L110: */ } } else { i__1 = *n - 1; for(j = 1; j <= i__1; ++j) { i__2 = *n - j; dlassq_(&i__2, &a[j + 1 + j * a_dim1], &c__1, &scale, &sum); /* L120: */ } } sum *= 2; i__1 = *lda + 1; dlassq_(n, &a[a_offset], &i__1, &scale, &sum); value = scale * sqrt(sum); } ret_val = value; return ret_val; /* End of DLANSY */ } /* dlansy_ */ /* Subroutine */ int dlassq_(n, x, incx, scale, sumsq) integer *n; doublereal *x; integer *incx; doublereal *scale, *sumsq; { /* System generated locals */ integer i__1, i__2; doublereal d__1; /* Local variables */ static doublereal absxi; static integer ix; /* -- LAPACK auxiliary routine (version 1.1) -- */ /* Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., */ /* Courant Institute, Argonne National Lab, and Rice University */ /* October 31, 1992 */ /* .. Scalar Arguments .. */ /* .. */ /* .. Array Arguments .. */ /* .. */ /* Purpose */ /* ======= */ /* DLASSQ returns the values scl and smsq such that */ /* ( scl**2 )*smsq = x( 1 )**2 +...+ x( n )**2 + ( scale**2 )*sumsq, */ /* where x( i ) = X( 1 + ( i - 1 )*INCX ). The value of sumsq is */ /* assumed to be non-negative and scl returns the value */ /* scl = max( scale, abs( x( i ) ) ). */ /* scale and sumsq must be supplied in SCALE and SUMSQ and */ /* scl and smsq are overwritten on SCALE and SUMSQ respectively. */ /* The routine makes only one pass through the vector x. */ /* Arguments */ /* ========= */ /* N (input) INTEGER */ /* The number of elements to be used from the vector X. */ /* X (input) DOUBLE PRECISION */ /* The vector for which a scaled sum of squares is computed. */ /* x( i ) = X( 1 + ( i - 1 )*INCX ), 1 <= i <= n. */ /* INCX (input) INTEGER */ /* The increment between successive values of the vector X. */ /* INCX > 0. */ /* SCALE (input/output) DOUBLE PRECISION */ /* On entry, the value scale in the equation above. */ /* On exit, SCALE is overwritten with scl , the scaling factor */ /* for the sum of squares. */ /* SUMSQ (input/output) DOUBLE PRECISION */ /* On entry, the value sumsq in the equation above. */ /* On exit, SUMSQ is overwritten with smsq , the basic sum of */ /* squares from which scl has been factored out. */ /* ===================================================================== */ /* .. Parameters .. */ /* .. */ /* .. Local Scalars .. */ /* .. */ /* .. Intrinsic Functions .. */ /* .. */ /* .. Executable Statements .. */ /* Parameter adjustments */ --x; /* Function Body */ if(*n > 0) { i__1 = (*n - 1) * *incx + 1; i__2 = *incx; for(ix = 1; i__2 < 0 ? ix >= i__1 : ix <= i__1; ix += i__2) { if(x[ix] != 0.) { absxi = (d__1 = x[ix], abs(d__1)); if(*scale < absxi) { /* Computing 2nd power */ d__1 = *scale / absxi; *sumsq = *sumsq * (d__1 * d__1) + 1; *scale = absxi; } else { /* Computing 2nd power */ d__1 = absxi / *scale; *sumsq += d__1 * d__1; } } /* L10: */ } } return 0; /* End of DLASSQ */ } /* dlassq_ */ doublereal dlaran_(iseed) integer *iseed; { /* System generated locals */ doublereal ret_val; /* Local variables */ static integer it1, it2, it3, it4; /* -- LAPACK auxiliary routine (version 1.1) -- */ /* Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., */ /* Courant Institute, Argonne National Lab, and Rice University */ /* February 29, 1992 */ /* .. Array Arguments .. */ /* .. */ /* Purpose */ /* ======= */ /* DLARAN returns a random DOUBLE PRECISION number from a uniform (0,1) */ /* distribution. */ /* Arguments */ /* ========= */ /* ISEED (input/output) INTEGER array, dimension (4) */ /* On entry, the seed of the random number generator; the array */ /* elements must be between 0 and 4095, and ISEED(4) must be */ /* odd. */ /* On exit, the seed is updated. */ /* Further Details */ /* =============== */ /* This routine uses a multiplicative congruential method with modulus */ /* 2**48 and multiplier 33952834046453 (see G.S.Fishman, */ /* 'Multiplicative congruential random number generators with modulus */ /* 2**b: an exhaustive analysis for b = 32 and a partial analysis for */ /* b = 48', Math. Comp. 189, pp 331-344, 1990). */ /* 48-bit integers are stored in 4 integer array elements with 12 bits */ /* per element. Hence the routine is portable across machines with */ /* integers of 32 bits or more. */ /* ===================================================================== */ /* .. Parameters .. */ /* .. */ /* .. Local Scalars .. */ /* .. */ /* .. Intrinsic Functions .. */ /* .. */ /* .. Executable Statements .. */ /* multiply the seed by the multiplier modulo 2**48 */ /* Parameter adjustments */ --iseed; /* Function Body */ it4 = iseed[4] * 2549; it3 = it4 / 4096; it4 -= it3 << 12; it3 = it3 + iseed[3] * 2549 + iseed[4] * 2508; it2 = it3 / 4096; it3 -= it2 << 12; it2 = it2 + iseed[2] * 2549 + iseed[3] * 2508 + iseed[4] * 322; it1 = it2 / 4096; it2 -= it1 << 12; it1 = it1 + iseed[1] * 2549 + iseed[2] * 2508 + iseed[3] * 322 + iseed[4] * 494; it1 %= 4096; /* return updated seed */ iseed[1] = it1; iseed[2] = it2; iseed[3] = it3; iseed[4] = it4; /* convert 48-bit integer to a DOUBLE PRECISION number in the interval (0,1)*/ ret_val = ((doublereal) it1 + ((doublereal) it2 + ((doublereal) it3 + ( doublereal) it4 * 2.44140625e-4) * 2.44140625e-4) * 2.44140625e-4) * 2.44140625e-4; return ret_val; /* End of DLARAN */ } /* dlaran_ */ logical lsame_(ca, cb, ca_len, cb_len) char *ca, *cb; ftnlen ca_len; ftnlen cb_len; { /* System generated locals */ logical ret_val; /* Local variables */ static integer inta, intb, zcode; /* -- LAPACK auxiliary routine (version 1.1) -- */ /* Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., */ /* Courant Institute, Argonne National Lab, and Rice University */ /* February 29, 1992 */ /* .. Scalar Arguments .. */ /* .. */ /* Purpose */ /* ======= */ /* LSAME returns .TRUE. if CA is the same letter as CB regardless of */ /* case. */ /* Arguments */ /* ========= */ /* CA (input) CHARACTER*1 */ /* CB (input) CHARACTER*1 */ /* CA and CB specify the single characters to be compared. */ /* .. Intrinsic Functions .. */ /* .. */ /* .. Local Scalars .. */ /* .. */ /* .. Executable Statements .. */ /* Test if the characters are equal */ ret_val = *ca == *cb; if(ret_val) { return ret_val; } /* Now test for equivalence if both characters are alphabetic. */ zcode = 'Z'; /* Use 'Z' rather than 'A' so that ASCII can be detected on Prime */ /* machines, on which ICHAR returns a value with bit 8 set. */ /* ICHAR('A') on Prime machines returns 193 which is the same as */ /* ICHAR('A') on an EBCDIC machine. */ inta = *ca; intb = *cb; if(zcode == 90 || zcode == 122) { /* ASCII is assumed - ZCODE is the ASCII code of either lower o r */ /* upper case 'Z'. */ if(inta >= 97 && inta <= 122) { inta += -32; } if(intb >= 97 && intb <= 122) { intb += -32; } } else if(zcode == 233 || zcode == 169) { /* EBCDIC is assumed - ZCODE is the EBCDIC code of either lower or */ /* upper case 'Z'. */ if(inta >= 129 && inta <= 137 || inta >= 145 && inta <= 153 || inta >= 162 && inta <= 169) { inta += 64; } if(intb >= 129 && intb <= 137 || intb >= 145 && intb <= 153 || intb >= 162 && intb <= 169) { intb += 64; } } else if(zcode == 218 || zcode == 250) { /* ASCII is assumed, on Prime machines - ZCODE is the ASCII cod e */ /* plus 128 of either lower or upper case 'Z'. */ if(inta >= 225 && inta <= 250) { inta += -32; } if(intb >= 225 && intb <= 250) { intb += -32; } } ret_val = inta == intb; /* RETURN */ /* End of LSAME */ return ret_val; } /* lsame_ */ logical lsamen_(n, ca, cb, ca_len, cb_len) integer *n; char *ca, *cb; ftnlen ca_len; ftnlen cb_len; { /* System generated locals */ integer i__1; logical ret_val; /* Builtin functions */ integer i_len(); /* Local variables */ static integer i; extern logical lsame_(); /* -- LAPACK auxiliary routine (version 1.0b) -- */ /* Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., */ /* Courant Institute, Argonne National Lab, and Rice University */ /* February 29, 1992 */ /* .. Scalar Arguments .. */ /* .. */ /* Purpose */ /* ======= */ /* LSAMEN tests if the first N letters of CA are the same as the */ /* first N letters of CB, regardless of case. */ /* LSAMEN returns .TRUE. if CA and CB are equivalent except for case */ /* and .FALSE. otherwise. LSAMEN also returns .FALSE. if LEN( CA ) */ /* or LEN( CB ) is less than N. */ /* Arguments */ /* ========= */ /* N (input) INTEGER */ /* The number of characters in CA and CB to be compared. */ /* CA (input) CHARACTER*(*) */ /* CB (input) CHARACTER*(*) */ /* CA and CB specify two character strings of length at least N. */ /* Only the first N characters of each string will be accessed. */ /* .. Local Scalars .. */ /* .. */ /* .. External Functions .. */ /* .. */ /* .. Intrinsic Functions .. */ /* .. */ /* .. Executable Statements .. */ ret_val = FALSE_; if(i_len(ca, ca_len) < *n || i_len(cb, cb_len) < *n) { goto L20; } /* Do for each character in the two strings. */ i__1 = *n; for(i = 1; i <= i__1; ++i) { /* Test if the characters are equal using LSAME. */ if(! lsame_(ca + (i - 1), cb + (i - 1), 1L, 1L)) { goto L20; } /* L10: */ } ret_val = TRUE_; L20: return ret_val; /* End of LSAMEN */ } /* lsamen_ */
radarsat1/siconos
externals/netlib/dctemplates/dlapack.c
C
apache-2.0
218,409
// // Copyright (c) 2017 The Khronos Group Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include <string.h> #if !defined(_MSC_VER) #include <stdint.h> #endif // !_MSC_VER size_t doReplace(char* dest, size_t destLength, const char* source, const char* stringToReplace1, const char* replaceWith1, const char* stringToReplace2, const char* replaceWith2) { size_t copyCount = 0; const char* sourcePtr = source; char* destPtr = dest; const char* ptr1; const char* ptr2; size_t nJump; size_t len1, len2; size_t lenReplace1, lenReplace2; len1 = strlen(stringToReplace1); len2 = strlen(stringToReplace2); lenReplace1 = strlen(replaceWith1); lenReplace2 = strlen(replaceWith2); for (; copyCount < destLength && *sourcePtr;) { ptr1 = strstr(sourcePtr, stringToReplace1); ptr2 = strstr(sourcePtr, stringToReplace2); if (ptr1 != NULL && (ptr2 == NULL || ptr2 > ptr1)) { nJump = ptr1 - sourcePtr; if (((uintptr_t)ptr1 - (uintptr_t)sourcePtr) > destLength - copyCount) { return -1; } copyCount += nJump; strncpy(destPtr, sourcePtr, nJump); destPtr += nJump; sourcePtr += nJump + len1; strcpy(destPtr, replaceWith1); destPtr += lenReplace1; } else if (ptr2 != NULL && (ptr1 == NULL || ptr1 >= ptr2)) { nJump = ptr2 - sourcePtr; if (nJump > destLength - copyCount) { return -2; } copyCount += nJump; strncpy(destPtr, sourcePtr, nJump); destPtr += nJump; sourcePtr += nJump + len2; strcpy(destPtr, replaceWith2); destPtr += lenReplace2; } else { nJump = strlen(sourcePtr); if (nJump > destLength - copyCount) { return -3; } copyCount += nJump; strcpy(destPtr, sourcePtr); destPtr += nJump; sourcePtr += nJump; } } *destPtr = '\0'; return copyCount; } size_t doSingleReplace(char* dest, size_t destLength, const char* source, const char* stringToReplace, const char* replaceWith) { size_t copyCount = 0; const char* sourcePtr = source; char* destPtr = dest; const char* ptr; size_t nJump; size_t len; size_t lenReplace; len = strlen(stringToReplace); lenReplace = strlen(replaceWith); for (; copyCount < destLength && *sourcePtr;) { ptr = strstr(sourcePtr, stringToReplace); if (ptr != NULL) { nJump = ptr - sourcePtr; if (((uintptr_t)ptr - (uintptr_t)sourcePtr) > destLength - copyCount) { return -1; } copyCount += nJump; strncpy(destPtr, sourcePtr, nJump); destPtr += nJump; sourcePtr += nJump + len; strcpy(destPtr, replaceWith); destPtr += lenReplace; } else { nJump = strlen(sourcePtr); if (nJump > destLength - copyCount) { return -3; } copyCount += nJump; strcpy(destPtr, sourcePtr); destPtr += nJump; sourcePtr += nJump; } } *destPtr = '\0'; return copyCount; }
KhronosGroup/OpenCL-CTS
test_conformance/vectors/type_replacer.cpp
C++
apache-2.0
4,064
/** * Copyright (c) 2016-present, Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef ROI_POOL_F_OP_H_ #define ROI_POOL_F_OP_H_ #include "caffe2/core/context.h" #include "caffe2/core/logging.h" #include "caffe2/core/operator.h" #include "caffe2/utils/math.h" namespace caffe2 { template <typename T, class Context> class RoIPoolFOp final : public Operator<Context> { public: RoIPoolFOp(const OperatorDef& operator_def, Workspace* ws) : Operator<Context>(operator_def, ws), spatial_scale_(OperatorBase::GetSingleArgument<float>( "spatial_scale", 1.)), pooled_height_(OperatorBase::GetSingleArgument<int>("pooled_h", 1)), pooled_width_(OperatorBase::GetSingleArgument<int>("pooled_w", 1)) { DCHECK_GT(spatial_scale_, 0); DCHECK_GT(pooled_height_, 0); DCHECK_GT(pooled_width_, 0); } USE_OPERATOR_CONTEXT_FUNCTIONS; bool RunOnDevice() override { // No CPU implementation for now CAFFE_NOT_IMPLEMENTED; } protected: float spatial_scale_; int pooled_height_; int pooled_width_; }; template <typename T, class Context> class RoIPoolFGradientOp final : public Operator<Context> { public: RoIPoolFGradientOp(const OperatorDef& def, Workspace* ws) : Operator<Context>(def, ws), spatial_scale_(OperatorBase::GetSingleArgument<float>( "spatial_scale", 1.)), pooled_height_(OperatorBase::GetSingleArgument<int>("pooled_h", 1)), pooled_width_(OperatorBase::GetSingleArgument<int>("pooled_w", 1)) { DCHECK_GT(spatial_scale_, 0); DCHECK_GT(pooled_height_, 0); DCHECK_GT(pooled_width_, 0); } USE_OPERATOR_CONTEXT_FUNCTIONS; bool RunOnDevice() override { // No CPU implementation for now CAFFE_NOT_IMPLEMENTED; } protected: float spatial_scale_; int pooled_height_; int pooled_width_; }; } // namespace caffe2 #endif // ROI_POOL_F_OP_H_
Yangqing/caffe2
modules/detectron/roi_pool_f_op.h
C
apache-2.0
2,428
# Copyright (C) 2015 The Android Open Source Project # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. archs_list = ['ARM', 'ARM64', 'MIPS', 'MIPS64', 'X86', 'X86_64']
android-art-intel/Nougat
art-extension/tools/checker/common/archs.py
Python
apache-2.0
663
// -------------------------------------------------------------------------------------------------------------------- // <copyright company="Chocolatey" file="ChocolateyService.cs"> // Copyright 2017 - Present Chocolatey Software, LLC // Copyright 2014 - 2017 Rob Reynolds, the maintainers of Chocolatey, and RealDimensions Software, LLC // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AutoMapper; using chocolatey; using chocolatey.infrastructure.app.configuration; using chocolatey.infrastructure.app.domain; using chocolatey.infrastructure.app.nuget; using chocolatey.infrastructure.app.services; using chocolatey.infrastructure.results; using chocolatey.infrastructure.services; using ChocolateyGui.Common.Models; using ChocolateyGui.Common.Properties; using ChocolateyGui.Common.Services; using ChocolateyGui.Common.Utilities; using Microsoft.VisualStudio.Threading; using NuGet; using ChocolateySource = ChocolateyGui.Common.Models.ChocolateySource; using IFileSystem = chocolatey.infrastructure.filesystem.IFileSystem; namespace ChocolateyGui.Common.Windows.Services { using ChocolateySource = ChocolateySource; using ILogger = Serilog.ILogger; public class ChocolateyService : IChocolateyService { private static readonly ILogger Logger = Serilog.Log.ForContext<ChocolateyService>(); private static readonly AsyncReaderWriterLock Lock = new AsyncReaderWriterLock(); private readonly IMapper _mapper; private readonly IProgressService _progressService; private readonly IChocolateyConfigSettingsService _configSettingsService; private readonly IXmlService _xmlService; private readonly IFileSystem _fileSystem; private readonly IConfigService _configService; private GetChocolatey _choco; private string _localAppDataPath = string.Empty; #pragma warning disable SA1401 // Fields must be private #pragma warning restore SA1401 // Fields must be private public ChocolateyService(IMapper mapper, IProgressService progressService, IChocolateyConfigSettingsService configSettingsService, IXmlService xmlService, IFileSystem fileSystem, IConfigService configService) { _mapper = mapper; _progressService = progressService; _configSettingsService = configSettingsService; _xmlService = xmlService; _fileSystem = fileSystem; _configService = configService; _choco = Lets.GetChocolatey(initializeLogging: false).SetCustomLogging(new SerilogLogger(Logger, _progressService), logExistingMessages: false, addToExistingLoggers: true); _localAppDataPath = _fileSystem.combine_paths(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData, Environment.SpecialFolderOption.DoNotVerify), "Chocolatey GUI"); } public Task<bool> IsElevated() { return Task.FromResult(Elevation.Instance.IsElevated); } public async Task<IEnumerable<Package>> GetInstalledPackages() { _choco.Set( config => { config.CommandName = CommandNameType.list.ToString(); config.ListCommand.LocalOnly = true; }); var chocoConfig = _choco.GetConfiguration(); // Not entirely sure what is going on here. When there are no sources defined, for example, when they // are all disabled, the ListAsync command isn't returning any packages installed locally. When in this // situation, use the nugetService directly to get the list of installed packages. if (chocoConfig.Sources != null) { var packages = await _choco.ListAsync<PackageResult>(); return packages .Select(package => GetMappedPackage(_choco, package, _mapper, true)) .ToArray(); } else { var nugetService = _choco.Container().GetInstance<INugetService>(); var packages = await Task.Run(() => nugetService.list_run(chocoConfig)); return packages .Select(package => GetMappedPackage(_choco, package, _mapper, true)) .ToArray(); } } public async Task<IReadOnlyList<OutdatedPackage>> GetOutdatedPackages(bool includePrerelease = false, string packageName = null, bool forceCheckForOutdatedPackages = false) { var preventAutomatedOutdatedPackagesCheck = _configService.GetEffectiveConfiguration().PreventAutomatedOutdatedPackagesCheck ?? false; if (preventAutomatedOutdatedPackagesCheck && !forceCheckForOutdatedPackages) { return new List<OutdatedPackage>(); } var outdatedPackagesFile = _fileSystem.combine_paths(_localAppDataPath, "outdatedPackages.xml"); var outdatedPackagesCacheDurationInMinutesSetting = _configService.GetEffectiveConfiguration().OutdatedPackagesCacheDurationInMinutes; int outdatedPackagesCacheDurationInMinutes = 0; if (!string.IsNullOrWhiteSpace(outdatedPackagesCacheDurationInMinutesSetting)) { int.TryParse(outdatedPackagesCacheDurationInMinutesSetting, out outdatedPackagesCacheDurationInMinutes); } if (_fileSystem.file_exists(outdatedPackagesFile) && (DateTime.Now - _fileSystem.get_file_modified_date(outdatedPackagesFile)).TotalMinutes < outdatedPackagesCacheDurationInMinutes) { return _xmlService.deserialize<List<OutdatedPackage>>(outdatedPackagesFile); } else { var choco = Lets.GetChocolatey(initializeLogging: false); choco.Set( config => { config.CommandName = "outdated"; config.PackageNames = packageName ?? chocolatey.infrastructure.app.ApplicationParameters.AllPackages; config.UpgradeCommand.NotifyOnlyAvailableUpgrades = true; config.RegularOutput = false; config.QuietOutput = true; config.Prerelease = false; }); var chocoConfig = choco.GetConfiguration(); // If there are no Sources configured, for example, if they are all disabled, then figuring out // which packages are outdated can't be completed. if (chocoConfig.Sources != null) { var nugetService = choco.Container().GetInstance<INugetService>(); var packages = await Task.Run(() => nugetService.upgrade_noop(chocoConfig, null)); var results = packages .Where(p => !p.Value.Inconclusive) .Select(p => new OutdatedPackage { Id = p.Value.Package.Id, VersionString = p.Value.Package.Version.ToNormalizedString() }) .ToArray(); try { _xmlService.serialize(results, outdatedPackagesFile); } catch (Exception ex) { Logger.Error(ex, L(nameof(Resources.Application_OutdatedPackagesError))); } return results.ToList(); } else { return new List<OutdatedPackage>(); } } } public async Task<PackageOperationResult> InstallPackage( string id, string version = null, Uri source = null, bool force = false, AdvancedInstall advancedInstallOptions = null) { using (await Lock.WriteLockAsync()) { var logger = new SerilogLogger(Logger, _progressService); var choco = Lets.GetChocolatey(initializeLogging: false).SetCustomLogging(logger, logExistingMessages: false, addToExistingLoggers: true); choco.Set( config => { config.CommandName = CommandNameType.install.ToString(); config.PackageNames = id; config.Features.UsePackageExitCodes = false; if (version != null) { config.Version = version.ToString(); } if (source != null) { config.Sources = source.ToString(); } if (force) { config.Force = true; } if (advancedInstallOptions != null) { config.InstallArguments = advancedInstallOptions.InstallArguments; config.PackageParameters = advancedInstallOptions.PackageParameters; config.CommandExecutionTimeoutSeconds = advancedInstallOptions.ExecutionTimeoutInSeconds; if (!string.IsNullOrEmpty(advancedInstallOptions.LogFile)) { config.AdditionalLogFileLocation = advancedInstallOptions.LogFile; } config.Prerelease = advancedInstallOptions.PreRelease; config.ForceX86 = advancedInstallOptions.Forcex86; config.OverrideArguments = advancedInstallOptions.OverrideArguments; config.NotSilent = advancedInstallOptions.NotSilent; config.ApplyInstallArgumentsToDependencies = advancedInstallOptions.ApplyInstallArgumentsToDependencies; config.ApplyPackageParametersToDependencies = advancedInstallOptions.ApplyPackageParametersToDependencies; config.AllowDowngrade = advancedInstallOptions.AllowDowngrade; config.AllowMultipleVersions = advancedInstallOptions.AllowMultipleVersions; config.IgnoreDependencies = advancedInstallOptions.IgnoreDependencies; config.ForceDependencies = advancedInstallOptions.ForceDependencies; config.SkipPackageInstallProvider = advancedInstallOptions.SkipPowerShell; config.Features.ChecksumFiles = !advancedInstallOptions.IgnoreChecksums; config.Features.AllowEmptyChecksums = advancedInstallOptions.AllowEmptyChecksums; config.Features.AllowEmptyChecksumsSecure = advancedInstallOptions.AllowEmptyChecksumsSecure; if (advancedInstallOptions.RequireChecksums) { config.Features.AllowEmptyChecksums = false; config.Features.AllowEmptyChecksumsSecure = false; } if (!string.IsNullOrEmpty(advancedInstallOptions.CacheLocation)) { config.CacheLocation = advancedInstallOptions.CacheLocation; } config.DownloadChecksum = advancedInstallOptions.DownloadChecksum; config.DownloadChecksum64 = advancedInstallOptions.DownloadChecksum64bit; config.DownloadChecksumType = advancedInstallOptions.DownloadChecksumType; config.DownloadChecksumType64 = advancedInstallOptions.DownloadChecksumType64bit; } }); Action<LogMessage> grabErrors; var errors = GetErrors(out grabErrors); using (logger.Intercept(grabErrors)) { await choco.RunAsync(); if (Environment.ExitCode != 0) { Environment.ExitCode = 0; return new PackageOperationResult { Successful = false, Messages = errors.ToArray() }; } return PackageOperationResult.SuccessfulCached; } } } public async Task<PackageResults> Search(string query, PackageSearchOptions options) { _choco.Set( config => { config.CommandName = CommandNameType.list.ToString(); config.Input = query; config.AllVersions = options.IncludeAllVersions; config.ListCommand.Page = options.CurrentPage; config.ListCommand.PageSize = options.PageSize; config.Prerelease = options.IncludePrerelease; config.ListCommand.LocalOnly = false; if (string.IsNullOrWhiteSpace(query) || !string.IsNullOrWhiteSpace(options.SortColumn)) { config.ListCommand.OrderByPopularity = string.IsNullOrWhiteSpace(options.SortColumn) || options.SortColumn == "DownloadCount"; } config.ListCommand.Exact = options.MatchQuery; if (!string.IsNullOrWhiteSpace(options.Source)) { config.Sources = options.Source; } #if !DEBUG config.Verbose = false; #endif // DEBUG }); var packages = (await _choco.ListAsync<PackageResult>()).Select( pckge => GetMappedPackage(_choco, pckge, _mapper)); return new PackageResults { Packages = packages.ToArray(), TotalCount = await Task.Run(() => _choco.ListCount()) }; } public async Task<Package> GetByVersionAndIdAsync(string id, string version, bool isPrerelease) { _choco.Set( config => { config.CommandName = "list"; config.Input = id; config.ListCommand.Exact = true; config.Version = version; config.QuietOutput = true; config.RegularOutput = false; #if !DEBUG config.Verbose = false; #endif // DEBUG }); var chocoConfig = _choco.GetConfiguration(); var nugetLogger = _choco.Container().GetInstance<NuGet.ILogger>(); var semvar = new SemanticVersion(version); var nugetPackage = await Task.Run(() => (NugetList.GetPackages(chocoConfig, nugetLogger) as IQueryable<IPackage>).FirstOrDefault(p => p.Version == semvar)); if (nugetPackage == null) { throw new Exception("No Package Found"); } return GetMappedPackage(_choco, new PackageResult(nugetPackage, null, chocoConfig.Sources), _mapper); } public async Task<List<SemanticVersion>> GetAvailableVersionsForPackageIdAsync(string id, int page, int pageSize, bool includePreRelease) { _choco.Set( config => { config.CommandName = "list"; config.Input = id; config.ListCommand.Exact = true; config.ListCommand.Page = page; config.ListCommand.PageSize = pageSize; config.Prerelease = includePreRelease; config.AllVersions = true; config.QuietOutput = true; config.RegularOutput = false; #if !DEBUG config.Verbose = false; #endif // DEBUG }); var chocoConfig = _choco.GetConfiguration(); var packages = await _choco.ListAsync<PackageResult>(); return packages.Select(p => new SemanticVersion(p.Version)).OrderByDescending(p => p.Version).ToList(); } public async Task<PackageOperationResult> UninstallPackage(string id, string version, bool force = false) { using (await Lock.WriteLockAsync()) { var logger = new SerilogLogger(Logger, _progressService); var choco = Lets.GetChocolatey(initializeLogging: false).SetCustomLogging(logger, logExistingMessages: false, addToExistingLoggers: true); choco.Set( config => { config.CommandName = CommandNameType.uninstall.ToString(); config.PackageNames = id; config.Features.UsePackageExitCodes = false; if (version != null) { config.Version = version.ToString(); } }); return await RunCommand(choco, logger); } } public async Task<PackageOperationResult> UpdatePackage(string id, Uri source = null) { using (await Lock.WriteLockAsync()) { var logger = new SerilogLogger(Logger, _progressService); var choco = Lets.GetChocolatey(initializeLogging: false).SetCustomLogging(logger, logExistingMessages: false, addToExistingLoggers: true); choco.Set( config => { config.CommandName = CommandNameType.upgrade.ToString(); config.PackageNames = id; config.Features.UsePackageExitCodes = false; }); return await RunCommand(choco, logger); } } public async Task<PackageOperationResult> PinPackage(string id, string version) { using (await Lock.WriteLockAsync()) { _choco.Set( config => { config.CommandName = "pin"; config.PinCommand.Command = PinCommandType.add; config.PinCommand.Name = id; config.Version = version; }); try { await _choco.RunAsync(); } catch (Exception ex) { return new PackageOperationResult { Successful = false, Exception = ex }; } return PackageOperationResult.SuccessfulCached; } } public async Task<PackageOperationResult> UnpinPackage(string id, string version) { using (await Lock.WriteLockAsync()) { _choco.Set( config => { config.CommandName = "pin"; config.PinCommand.Command = PinCommandType.remove; config.PinCommand.Name = id; config.Version = version; }); try { await _choco.RunAsync(); } catch (Exception ex) { return new PackageOperationResult { Successful = false, Exception = ex }; } return PackageOperationResult.SuccessfulCached; } } public async Task<ChocolateyFeature[]> GetFeatures() { var config = await GetConfigFile(); var features = config.Features.Select(_mapper.Map<ChocolateyFeature>); return features.OrderBy(f => f.Name).ToArray(); } public async Task SetFeature(ChocolateyFeature feature) { if (feature == null) { return; } using (await Lock.WriteLockAsync()) { _choco.Set( config => { config.CommandName = "feature"; config.FeatureCommand.Command = feature.Enabled ? chocolatey.infrastructure.app.domain.FeatureCommandType.enable : chocolatey.infrastructure.app.domain.FeatureCommandType.disable; config.FeatureCommand.Name = feature.Name; }); await _choco.RunAsync(); } } public async Task<ChocolateySetting[]> GetSettings() { var config = await GetConfigFile(); var settings = config.ConfigSettings.Select(_mapper.Map<ChocolateySetting>); return settings.OrderBy(s => s.Key).ToArray(); } public async Task SetSetting(ChocolateySetting setting) { using (await Lock.WriteLockAsync()) { _choco.Set( config => { config.CommandName = "config"; config.ConfigCommand.Command = chocolatey.infrastructure.app.domain.ConfigCommandType.set; config.ConfigCommand.Name = setting.Key; config.ConfigCommand.ConfigValue = setting.Value; }); await _choco.RunAsync(); } } public async Task<ChocolateySource[]> GetSources() { // We only want to provide the sources returned by calling choco.exe, which will exclude those // as required, based on configuration. However, in order to be able to set all properties of the source // we need to read all information from the config file, i.e. the username and password var config = await GetConfigFile(); var allSources = config.Sources.Select(_mapper.Map<ChocolateySource>).ToArray(); var filteredSourceIds = _configSettingsService.source_list(_choco.GetConfiguration()).Select(s => s.Id).ToArray(); var mappedSources = allSources.Where(s => filteredSourceIds.Contains(s.Id)).ToArray(); return mappedSources; } public async Task AddSource(ChocolateySource source) { using (await Lock.WriteLockAsync()) { _choco.Set( config => { config.CommandName = "source"; config.SourceCommand.Command = SourceCommandType.add; config.SourceCommand.Name = source.Id; config.Sources = source.Value; config.SourceCommand.Username = source.UserName; config.SourceCommand.Password = source.Password; config.SourceCommand.Certificate = source.Certificate; config.SourceCommand.CertificatePassword = source.CertificatePassword; config.SourceCommand.Priority = source.Priority; config.SourceCommand.BypassProxy = source.BypassProxy; config.SourceCommand.AllowSelfService = source.AllowSelfService; config.SourceCommand.VisibleToAdminsOnly = source.VisibleToAdminsOnly; }); await _choco.RunAsync(); if (source.Disabled) { await DisableSource(source.Id); } else { await EnableSource(source.Id); } } } public async Task DisableSource(string id) { _choco.Set( config => { config.CommandName = "source"; config.SourceCommand.Command = SourceCommandType.disable; config.SourceCommand.Name = id; }); await _choco.RunAsync(); } public async Task EnableSource(string id) { _choco.Set( config => { config.CommandName = "source"; config.SourceCommand.Command = SourceCommandType.enable; config.SourceCommand.Name = id; }); await _choco.RunAsync(); } public async Task UpdateSource(string id, ChocolateySource source) { // NOTE: The strategy of first removing, and then re-adding the source // is due to the fact that there is no "edit source" command that can // be used. This has the side effect of "having" to decrypt the password // for an authenticated source, otherwise, when re-adding the source, // the encrypted password, is re-encrypted, making it no longer work. if (id != source.Id) { await RemoveSource(id); } await AddSource(source); } public async Task<bool> RemoveSource(string id) { using (await Lock.WriteLockAsync()) { var chocoConfig = await GetConfigFile(); var sources = chocoConfig.Sources.Select(_mapper.Map<ChocolateySource>).ToList(); if (sources.All(source => source.Id != id)) { return false; } _choco.Set( config => { config.CommandName = "source"; config.SourceCommand.Command = SourceCommandType.remove; config.SourceCommand.Name = id; }); await _choco.RunAsync(); return true; } } public async Task ExportPackages(string exportFilePath, bool includeVersionNumbers) { _choco.Set( config => { config.CommandName = "export"; config.ExportCommand.OutputFilePath = exportFilePath; config.ExportCommand.IncludeVersionNumbers = includeVersionNumbers; }); await _choco.RunAsync(); } private static Package GetMappedPackage(GetChocolatey choco, PackageResult package, IMapper mapper, bool forceInstalled = false) { var mappedPackage = package == null ? null : mapper.Map<Package>(package.Package); if (mappedPackage != null) { var packageInfoService = choco.Container().GetInstance<IChocolateyPackageInformationService>(); var packageInfo = packageInfoService.get_package_information(package.Package); mappedPackage.IsPinned = packageInfo.IsPinned; mappedPackage.IsInstalled = !string.IsNullOrWhiteSpace(package.InstallLocation) || forceInstalled; mappedPackage.IsSideBySide = packageInfo.IsSideBySide; mappedPackage.IsPrerelease = !string.IsNullOrWhiteSpace(mappedPackage.Version.SpecialVersion); // Add a sanity check here for pre-release packages // By default, pre-release packages are marked as IsLatestVersion = false, however, IsLatestVersion is // what is used to show/hide the Out of Date message in the UI. In these cases, if it is a pre-release // mark IsLatestVersion as true, and then the outcome of the call to choco outdated will correct whether // it is actually Out of Date or not if (mappedPackage.IsPrerelease && mappedPackage.IsAbsoluteLatestVersion && !mappedPackage.IsLatestVersion) { mappedPackage.IsLatestVersion = true; } } return mappedPackage; } private static List<string> GetErrors(out Action<LogMessage> grabErrors) { var errors = new List<string>(); grabErrors = m => { switch (m.LogLevel) { case LogLevel.Warn: case LogLevel.Error: case LogLevel.Fatal: errors.Add(m.Message); break; } }; return errors; } private static string L(string key) { return TranslationSource.Instance[key]; } private static string L(string key, params object[] parameters) { return TranslationSource.Instance[key, parameters]; } private async Task<PackageOperationResult> RunCommand(GetChocolatey choco, SerilogLogger logger) { Action<LogMessage> grabErrors; var errors = GetErrors(out grabErrors); using (logger.Intercept(grabErrors)) { try { await choco.RunAsync(); } catch (Exception ex) { return new PackageOperationResult { Successful = false, Messages = errors.ToArray(), Exception = ex }; } if (Environment.ExitCode != 0) { Environment.ExitCode = 0; return new PackageOperationResult { Successful = false, Messages = errors.ToArray() }; } return PackageOperationResult.SuccessfulCached; } } private async Task<ConfigFileSettings> GetConfigFile() { var xmlService = _choco.Container().GetInstance<IXmlService>(); var config = await Task.Run( () => xmlService.deserialize<ConfigFileSettings>(chocolatey.infrastructure.app.ApplicationParameters.GlobalConfigFileLocation)); return config; } } }
chocolatey/ChocolateyGUI
Source/ChocolateyGui.Common.Windows/Services/ChocolateyService.cs
C#
apache-2.0
31,834
/* Copyright 2020 The Knative 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 deployments is a placeholder that allows us to pull in config files // via go mod vendor. package deployments
knative/serving
config/core/deployments/placeholder.go
GO
apache-2.0
688
package com.oklab.gitjourney.data; import java.util.Calendar; /** * Created by olgakuklina on 2017-01-15. */ public class FeedDataEntry { private final long entryId; private final String authorName; private final String avatarURL; private final String authorURL; private final String title; private final String description; private final ActionType actionType; private final Calendar date; public FeedDataEntry(long entryId, String authorName, String avatarURL, String authorURL, String title, String description, ActionType actionType, Calendar date) { this.entryId = entryId; this.authorName = authorName; this.avatarURL = avatarURL; this.authorURL = authorURL; this.title = title; this.description = description; this.actionType = actionType; this.date = date; } public long getEntryId() { return entryId; } public String getAuthorName() { return authorName; } public String getAvatarURL() { return avatarURL; } public String getTitle() { return title; } public String getDescription() { return description; } public ActionType getActionType() { return actionType; } public Calendar getDate() { return date; } public String getAuthorURL() { return authorURL; } }
OlgaKuklina/GitJourney
app/src/main/java/com/oklab/gitjourney/data/FeedDataEntry.java
Java
apache-2.0
1,413
/* * 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. */ import angular from 'angular'; import templateUrl from 'views/signin.tpl.pug'; angular .module('ignite-console.states.login', [ 'ui.router', // services 'ignite-console.user' ]) .config(['$stateProvider', 'AclRouteProvider', function($stateProvider) { // set up the states $stateProvider .state('signin', { url: '/', templateUrl, resolve: { user: ['$state', 'User', ($state, User) => { return User.read() .then(() => $state.go('base.configuration.clusters')) .catch(() => {}); }] }, controllerAs: '$ctrl', controller() {}, metaTags: { } }); }]);
a1vanov/ignite
modules/web-console/frontend/app/modules/states/signin.state.js
JavaScript
apache-2.0
1,523
/* * 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 io.milton.http.http11; import io.milton.http.Auth; import io.milton.resource.GetableResource; import io.milton.http.Response; /** * Generates the cache-control header on the response * * @author brad */ public interface CacheControlHelper { /** * * @param resource * @param response * @param auth * @param notMod - true means we're sending a not modified response */ void setCacheControl( final GetableResource resource, final Response response, Auth auth); }
skoulouzis/lobcder
milton2/milton-server-ce/src/main/java/io/milton/http/http11/CacheControlHelper.java
Java
apache-2.0
1,359
require 'chef/provider/lwrp_base' require_relative 'helpers' class Chef class Provider class MysqlService < Chef::Provider::LWRPBase # Chef 11 LWRP DSL Methods use_inline_resources if defined?(use_inline_resources) def whyrun_supported? true end # Mix in helpers from libraries/helpers.rb include MysqlCookbook::Helpers # Service related methods referred to in the :create and :delete # actions need to be implemented in the init system subclasses. # # create_stop_system_service # delete_stop_service # All other methods are found in libraries/helpers.rb # # etc_dir, run_dir, log_dir, etc action :create do # Yum, Apt, etc. From helpers.rb # configure_package_repositories # Software installation # package "#{new_resource.name} :create #{server_package_name}" do # package_name server_package_name # version parsed_version if node['platform'] == 'smartos' # version new_resource.package_version # action new_resource.package_action # end #create_stop_system_service # Apparmor #configure_apparmor # System users group "#{new_resource.name} :create mysql" do group_name 'mysql' action :create end user "#{new_resource.name} :create mysql" do username 'mysql' gid 'mysql' action :create end # Yak shaving secion. Account for random errata. # # Turns out that mysqld is hard coded to try and read # /etc/mysql/my.cnf, and its presence causes problems when # setting up multiple services. file "#{new_resource.name} :create #{prefix_dir}/etc/mysql/my.cnf" do path "#{prefix_dir}/etc/mysql/my.cnf" action :delete end file "#{new_resource.name} :create #{prefix_dir}/etc/my.cnf" do path "#{prefix_dir}/etc/my.cnf" action :delete end # mysql_install_db is broken on 5.6.13 link "#{new_resource.name} :create #{prefix_dir}/usr/share/my-default.cnf" do target_file "#{prefix_dir}/usr/share/my-default.cnf" to "#{etc_dir}/my.cnf" action :create end # Support directories directory "#{new_resource.name} :create #{etc_dir}" do path etc_dir owner new_resource.run_user group new_resource.run_group mode '0750' recursive true action :create end directory "#{new_resource.name} :create #{include_dir}" do path include_dir owner new_resource.run_user group new_resource.run_group mode '0750' recursive true action :create end directory "#{new_resource.name} :create #{run_dir}" do path run_dir owner new_resource.run_user group new_resource.run_group mode '0755' recursive true action :create end directory "#{new_resource.name} :create #{log_dir}" do path log_dir owner new_resource.run_user group new_resource.run_group mode '0750' recursive true action :create end directory "#{new_resource.name} :create #{parsed_data_dir}" do path parsed_data_dir owner new_resource.run_user group new_resource.run_group mode '0750' recursive true action :create end # Main configuration file template "#{new_resource.name} :create #{etc_dir}/my.cnf" do path "#{etc_dir}/my.cnf" source 'my.cnf.erb' cookbook 'mariadb' owner new_resource.run_user group new_resource.run_group mode '0600' variables( config: new_resource, error_log: error_log, include_dir: include_dir, lc_messages_dir: lc_messages_dir, pid_file: pid_file, socket_file: socket_file, tmp_dir: tmp_dir, data_dir: parsed_data_dir ) action :create end # initialize database and create initial records bash "#{new_resource.name} :create initial records" do code init_records_script returns [0, 1, 2] # facepalm not_if "/usr/bin/test -f #{parsed_data_dir}/mysql/user.frm" action :run end end action :delete do # Stop the service before removing support directories delete_stop_service directory "#{new_resource.name} :delete #{etc_dir}" do path etc_dir recursive true action :delete end directory "#{new_resource.name} :delete #{run_dir}" do path run_dir recursive true action :delete end directory "#{new_resource.name} :delete #{log_dir}" do path log_dir recursive true action :delete end end # # Platform specific bits # def configure_apparmor # Do not add these resource if inside a container # Only valid on Ubuntu unless ::File.exist?('/.dockerenv') || ::File.exist?('/.dockerinit') if node['platform'] == 'ubuntu' # Apparmor package "#{new_resource.name} :create apparmor" do package_name 'apparmor' action :install end directory "#{new_resource.name} :create /etc/apparmor.d/local/mysql" do path '/etc/apparmor.d/local/mysql' owner 'root' group 'root' mode '0755' recursive true action :create end template "#{new_resource.name} :create /etc/apparmor.d/local/usr.sbin.mysqld" do path '/etc/apparmor.d/local/usr.sbin.mysqld' cookbook 'mariadb' source 'apparmor/usr.sbin.mysqld-local.erb' owner 'root' group 'root' mode '0644' action :create notifies :restart, "service[#{new_resource.name} :create apparmor]", :immediately end template "#{new_resource.name} :create /etc/apparmor.d/usr.sbin.mysqld" do path '/etc/apparmor.d/usr.sbin.mysqld' cookbook 'mariadb' source 'apparmor/usr.sbin.mysqld.erb' owner 'root' group 'root' mode '0644' action :create notifies :restart, "service[#{new_resource.name} :create apparmor]", :immediately end template "#{new_resource.name} :create /etc/apparmor.d/local/mysql/#{new_resource.instance}" do path "/etc/apparmor.d/local/mysql/#{new_resource.instance}" cookbook 'mariadb' source 'apparmor/usr.sbin.mysqld-instance.erb' owner 'root' group 'root' mode '0644' variables( data_dir: parsed_data_dir, mysql_name: mysql_name, log_dir: log_dir, run_dir: run_dir, pid_file: pid_file, socket_file: socket_file ) action :create notifies :restart, "service[#{new_resource.name} :create apparmor]", :immediately end service "#{new_resource.name} :create apparmor" do service_name 'apparmor' action :nothing end end end end end end end
OSLL/mariadb-cookbooks
libraries/provider_mysql_service.rb
Ruby
apache-2.0
7,775
/* * Copyright 2007-2107 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.ymate.platform.validation.annotation; /** * <p> * ValidateRule * </p> * <p> * 验证规则注解; * </p> * * @author 刘镇(suninformation@163.com) * @version 0.0.0 * <table style="border:1px solid gray;"> * <tr> * <th width="100px">版本号</th><th width="100px">动作</th><th * width="100px">修改人</th><th width="100px">修改时间</th> * </tr> * <!-- 以 Table 方式书写修改历史 --> * <tr> * <td>0.0.0</td> * <td>创建类</td> * <td>刘镇</td> * <td>2013-4-10下午7:23:38</td> * </tr> * </table> */ public @interface ValidateRule { /** * @return 验证器名称 */ String value(); /** * @return 验证器参数集合 */ String[] params() default {}; /** * @return 错误提示信息模板 */ String message() default ""; }
aglne/ymateplatform
ymateplatform/src/main/java/net/ymate/platform/validation/annotation/ValidateRule.java
Java
apache-2.0
1,601
/* * 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.beam.sdk.extensions.sql.meta.provider.pubsub; import static org.apache.beam.sdk.extensions.sql.impl.utils.CalciteUtils.TIMESTAMP; import static org.apache.beam.sdk.extensions.sql.impl.utils.CalciteUtils.VARCHAR; import static org.apache.beam.sdk.extensions.sql.meta.provider.pubsub.PubsubMessageToRow.ATTRIBUTES_FIELD; import static org.apache.beam.sdk.extensions.sql.meta.provider.pubsub.PubsubMessageToRow.PAYLOAD_FIELD; import static org.apache.beam.sdk.extensions.sql.meta.provider.pubsub.PubsubMessageToRow.TIMESTAMP_FIELD; import static org.apache.beam.sdk.schemas.Schema.TypeName.ROW; import com.alibaba.fastjson.JSONObject; import com.google.auto.service.AutoService; import org.apache.beam.sdk.annotations.Experimental; import org.apache.beam.sdk.annotations.Internal; import org.apache.beam.sdk.extensions.sql.BeamSqlTable; import org.apache.beam.sdk.extensions.sql.meta.Table; import org.apache.beam.sdk.extensions.sql.meta.provider.InMemoryMetaTableProvider; import org.apache.beam.sdk.extensions.sql.meta.provider.TableProvider; import org.apache.beam.sdk.io.gcp.pubsub.PubsubIO; import org.apache.beam.sdk.schemas.Schema; /** * {@link TableProvider} for {@link PubsubIOJsonTable} which wraps {@link PubsubIO} for consumption * by Beam SQL. */ @Internal @Experimental @AutoService(TableProvider.class) public class PubsubJsonTableProvider extends InMemoryMetaTableProvider { @Override public String getTableType() { return "pubsub"; } @Override public BeamSqlTable buildBeamSqlTable(Table tableDefintion) { validatePubsubMessageSchema(tableDefintion); JSONObject tableProperties = tableDefintion.getProperties(); String timestampAttributeKey = tableProperties.getString("timestampAttributeKey"); String deadLetterQueue = tableProperties.getString("deadLetterQueue"); validateDlq(deadLetterQueue); return PubsubIOJsonTable.builder() .setSchema(tableDefintion.getSchema()) .setTimestampAttribute(timestampAttributeKey) .setDeadLetterQueue(deadLetterQueue) .setTopic(tableDefintion.getLocation()) .build(); } private void validatePubsubMessageSchema(Table tableDefinition) { Schema schema = tableDefinition.getSchema(); if (schema.getFieldCount() != 3 || !fieldPresent(schema, TIMESTAMP_FIELD, TIMESTAMP) || !fieldPresent( schema, ATTRIBUTES_FIELD, Schema.FieldType.map(VARCHAR.withNullable(false), VARCHAR)) || !(schema.hasField(PAYLOAD_FIELD) && ROW.equals(schema.getField(PAYLOAD_FIELD).getType().getTypeName()))) { throw new IllegalArgumentException( "Unsupported schema specified for Pubsub source in CREATE TABLE. " + "CREATE TABLE for Pubsub topic should define exactly the following fields: " + "'event_timestamp' field of type 'TIMESTAMP', 'attributes' field of type " + "MAP<VARCHAR, VARCHAR>, and 'payload' field of type 'ROW<...>' which matches the " + "payload JSON format."); } } private boolean fieldPresent(Schema schema, String field, Schema.FieldType expectedType) { return schema.hasField(field) && expectedType.equivalent( schema.getField(field).getType(), Schema.EquivalenceNullablePolicy.IGNORE); } private void validateDlq(String deadLetterQueue) { if (deadLetterQueue != null && deadLetterQueue.isEmpty()) { throw new IllegalArgumentException("Dead letter queue topic name is not specified"); } } }
mxm/incubator-beam
sdks/java/extensions/sql/src/main/java/org/apache/beam/sdk/extensions/sql/meta/provider/pubsub/PubsubJsonTableProvider.java
Java
apache-2.0
4,335
/* Copyright 2013 - $Date $ by PeopleWare n.v. 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. */ define(["contracts/doh", "../SiScalarQuantitativeValue", "./ScalarQuantitativeValue", "dojo/_base/declare", "dojo/_base/lang"], function(doh, SiScalarQuantitativeValue, testGeneratorScalarQuantitativeValue, declare, lang) { var SiSqvMock = declare([SiScalarQuantitativeValue], {}); SiSqvMock.mid = "pictoperfect-viewmodel/value/SiScalarQuantitativeValue"; SiSqvMock.baseUnit = "-BASE UNIT"; function testGeneratorSiScalarQuantitativeValue(Constructor, kwargs1, kwargs2, renameds) { testGeneratorScalarQuantitativeValue(Constructor, kwargs1, kwargs2, renameds); doh.register(Constructor.mid, [ function testGetBaseUnit() { var result = Constructor.prototype.getBaseUnit(); // post doh.t(result && true); // make it a boolean; doh evals strings } ]); var units = Constructor.prototype.getSupportedUnits(); units.forEach(function(unit) { doh.register(Constructor.mid, [ { name: "test getUnitPrefix of this (" + unit + ")", setUp: function() { this.instrumented = lang.clone(kwargs1); this.instrumented.unit = unit; this.subject = new Constructor(this.instrumented); }, runTest: function() { var result = this.subject.getUnitPrefix(); doh.invars(this.subject); if (unit.indexOf(this.subject.getBaseUnit()) >= 0) { doh.t(SiScalarQuantitativeValue.siPrefixes.contains(result)); doh.is(unit, result + this.subject.getBaseUnit()); } else { doh.is(null, result); } }, tearDown: function() { delete this.instrumented; delete this.subject; } }, { name: "test getUnitPrefix of " + unit, setUp: function() { this.subject = new Constructor(kwargs1); }, runTest: function() { var result = this.subject.getUnitPrefix(unit); doh.invars(this.subject); // post if (unit.indexOf(this.subject.getBaseUnit()) >= 0) { doh.t(SiScalarQuantitativeValue.siPrefixes.contains(result)); doh.is(unit, result + this.subject.getBaseUnit()); } else { doh.is(null, result); } }, tearDown: function() { delete this.subject; } } ]); }); } testGeneratorSiScalarQuantitativeValue( SiSqvMock, { scalarValue: 123, unit: "µ-BASE UNIT" }, { scalarValue: 456.789, unit: "-BASE UNIT" } ); return testGeneratorSiScalarQuantitativeValue; } );
jandppw/ppwcode-recovered-from-google-code
_moved2github/javascript/vernacular/value/trunk/src/test/SiScalarQuantitativeValue.js
JavaScript
apache-2.0
3,618
/* Copyright [2016] [Relevance Lab] 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. */ var mongoose = require('mongoose'); var logger = require('_pr/logger')(module); var ObjectId = require('mongoose').Types.ObjectId; var mongoosePaginate = require('mongoose-paginate'); var Schema = mongoose.Schema; var BotsSchema = new Schema ({ botId: { type: String, trim: true, required: true }, botName: { type: String, trim: true, required: true }, botType: { type: String, trim: true, required: true }, botCategory: { type: String, trim: true, required: true }, botDesc: { type: String, trim: true, required: true }, savedTime: { hours:{ type: Number, default:0 }, minutes:{ type: Number, default:0 } }, botConfig:Schema.Types.Mixed, runTimeParams:Schema.Types.Mixed, masterDetails: { orgName: { type: String, trim: true, required: false }, orgId: { type: String, trim: true, required: false }, bgName: { type: String, trim: true, required: false }, bgId: { type: String, trim: true, required: false }, projectName: { type: String, trim: true, required: false }, projectId: { type: String, trim: true, required: false }, envName: { type: String, trim: true, required: false }, envId: { type: String, trim: true, required: false } }, botLinkedCategory: { type: String, trim: true, required: false }, botLinkedSubCategory: { type: String, trim: true, required: false }, manualExecutionTime: { type: Number, default: 10 }, executionCount: { type: Number, default: 0 }, lastRunTime: { type: Number }, isBotScheduled: { type: Boolean, default: false }, botScheduler:{ cronStartOn: { type: String, required: false, trim: true }, cronEndOn: { type: String, required: false, trim: true }, cronPattern: { type: String, required: false, trim: true }, cronRepeatEvery: { type: Number, required: false }, cronFrequency: { type: String, required: false, trim: true }, cronMinute:{ type: Number, required: false, trim: true }, cronHour:{ type: Number, required: false }, cronWeekDay:{ type: Number, required: false }, cronDate:{ type: Number, required: false }, cronMonth:{ type: String, required: false, trim: true }, cronYear:{ type: Number, required: false } }, cronJobId:{ type: String, required: false, trim: true }, createdOn:{ type: Number, default: Date.now() }, isDeleted: { type: Boolean, default: false }, version: { type: String, trim: true }, domainNameCheck: { type: Boolean, default: false } }); BotsSchema.plugin(mongoosePaginate); BotsSchema.statics.createNew = function(botsDetail,callback){ var botsData = new Bots(botsDetail); botsData.save(function(err, data) { if (err) { logger.error("createNew Failed", err, data); callback(err,null); return; } callback(null,data); return; }); } BotsSchema.statics.updateBotsDetail = function(botId,botsDetail,callback){ Bots.update({botId:botId},{$set:botsDetail},{upsert:false}, function(err, updateBotDetail) { if (err) { logger.error(err); var error = new Error('Internal server error'); error.status = 500; return callback(error); } return callback(null, updateBotDetail); }); }; BotsSchema.statics.getBotsList = function(botsQuery,callback){ botsQuery.queryObj.isDeleted = false; Bots.paginate(botsQuery.queryObj, botsQuery.options, function(err, botsList) { if (err) { logger.error(err); var error = new Error('Internal server error'); error.status = 500; return callback(error); } return callback(null, botsList); }); }; BotsSchema.statics.getBotsById = function(botId,callback){ Bots.find({botId:botId}, function(err, bots) { if (err) { logger.error(err); var error = new Error('Internal server error'); error.status = 500; return callback(error); }else if(bots.length > 0){ return callback(null, bots); }else{ return callback(null, []); } }); }; BotsSchema.statics.getAllBots = function(queryParam,callback){ Bots.find(queryParam, function(err, bots) { if (err) { logger.error(err); var error = new Error('Internal server error'); error.status = 500; return callback(error); }else if(bots.length > 0){ return callback(null, bots); }else{ return callback(null, []); } }); }; BotsSchema.statics.removeBotsById = function(botId,callback){ Bots.remove({botId:botId}, function(err, bots) { if (err) { logger.error(err); var error = new Error('Internal server error'); error.status = 500; return callback(error); }else { return callback(null, bots); } }); }; BotsSchema.statics.removeSoftBotsById = function(botId,callback){ Bots.update({botId:botId},{$set:{isDeleted:true}}, function(err, bots) { if (err) { logger.error(err); var error = new Error('Internal server error'); error.status = 500; return callback(error); }else { return callback(null, bots); } }); }; BotsSchema.statics.updateBotsExecutionCount = function updateBotsExecutionCount(botId,count,callback) { Bots.update({ botId: botId, }, { $set: { executionCount: count } }, { upsert: false }, function (err, data) { if (err) { callback(err, null); return; } callback(null, data); }); }; BotsSchema.statics.getScheduledBots = function getScheduledBots(callback) { Bots.find({ isBotScheduled: true, isDeleted:false }, function (err, bots) { if (err) { logger.error(err); return callback(err, null); } return callback(null, bots); }) } BotsSchema.statics.updateCronJobIdByBotId = function updateCronJobIdByBotId(botId, cronJobId, callback) { Bots.update({ "_id": new ObjectId(botId), }, { $set: { cronJobId: cronJobId } }, { upsert: false }, function (err, data) { if (err) { callback(err, null); return; } callback(null, data); }); }; BotsSchema.statics.updateBotsScheduler = function updateBotsScheduler(botId, callback) { Bots.update({ "_id": new ObjectId(botId), }, { $set: { isBotScheduled: false } }, { upsert: false }, function (err, data) { if (err) { callback(err, null); return; } callback(null, data); }); }; var Bots = mongoose.model('bots', BotsSchema); module.exports = Bots;
Durgesh1988/core
server/app/model/bots/1.0/bots.js
JavaScript
apache-2.0
8,832
package helpers func getWhitelistedDrivers(resourceData *ResourceData) []string { tempMap := make(map[string]string) for _, driver := range resourceData.Blacklist { tempMap[driver] = "" } whitelist := []string{} for _, driver := range resourceData.Drivers { if _, ok := tempMap[driver]; !ok { whitelist = append(whitelist, driver) } } return whitelist } func isBlacklisted(resourceData *ResourceData, driver string) bool { for _, disallowedDriver := range resourceData.Blacklist { if disallowedDriver == driver { return true } } return false }
cjellick/go-machine-service
generator/helpers/utils.go
GO
apache-2.0
572
/* * * Copyright (C) 2000 Silicon Graphics, Inc. All Rights Reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * Further, this software is distributed without any warranty that it is * free of the rightful claim of any third person regarding infringement * or the like. Any license provided herein, whether implied or * otherwise, applies only to this software file. Patent licenses, if * any, provided herein do not apply to combinations of this program with * other software, or any other product whatsoever. * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy, * Mountain View, CA 94043, or: * * http://www.sgi.com * * For further information regarding this notice, see: * * http://oss.sgi.com/projects/GenInfo/NoticeExplan/ * */ // -*- C++ -*- /* * Copyright (C) 1990-93 Silicon Graphics, Inc. * _______________________________________________________________________ ______________ S I L I C O N G R A P H I C S I N C . ____________ | | $Revision: 1.2 $ | | Description: | This is an abstract base class which defines a c++ protocol | for motif components. | | Author(s): David Mott, Alain Dumesny | ______________ S I L I C O N G R A P H I C S I N C . ____________ _______________________________________________________________________ */ #ifndef _SO_XT_COMPONENT_H_ #define _SO_XT_COMPONENT_H_ #include <X11/Intrinsic.h> #include <Inventor/SbLinear.h> #include <Inventor/SbString.h> class SbDict; class SoXtComponent; class SoCallbackList; typedef void SoXtComponentCB(void *userData, SoXtComponent *comp); typedef void SoXtComponentVisibilityCB(void *userData, SbBool visibleFlag); // C-api: abstract // C-api: prefix=SoXtComp class SoXtComponent { public: // // This shows and hides the component. If this is a topLevelShell // component, then show() will Realize and Map the window, else it // will simply Manage the widget. // Hide calls the appropriate XUnmapWindow() or XtUnmanageChild() // routines (check SoXt::show and hide man pages for detail). // // In addition, show() will also pop the component window to the top // and de-iconify if necessary, to make sure the component is visible // by the user. // // C-api: expose virtual void show(); // C-api: expose virtual void hide(); // // returns TRUE if this component is mapped onto the screen. For // a component to be visible, it's widget and the shell containing // this widget must be mapped (which is FALSE when the component // is iconified). // // Subclasses should call this routine before redrawing anything // and in any sensor trigger methods. Calling this will check the // current visibility (which is really cheap) and invoke the // visibility changed callbacks if the state changes (see // addVisibilityChangeCallback()). // SbBool isVisible(); // // This returns the base widget for this component. // If the component created its own shell, this returns the // topmost widget beneath the shell. // Call getShellWidget() to obtain the shell. // Widget getWidget() const { return _baseWidget; } Widget baseWidget() const { return getWidget(); } // // Returns TRUE if this component is a top level shell component (has its // own window). Subclasses may use this to decide if they are allowed to // resize themselfves. // Also method to return the shell widget (NULL if the shell hasn't been // created by this component). // SbBool isTopLevelShell() const { return topLevelShell; } Widget getShellWidget() const { return topLevelShell ? parentWidget : NULL; } // Return the parent widget, be it a shell or not Widget getParentWidget() const { return parentWidget; } // // Convenience routines on the widget - setSize calls XtSetValue. // void setSize(const SbVec2s &size); SbVec2s getSize(); inline Display *getDisplay(); // // The title can be set for topLevel shell components or components // which are directly under a shell widget (i.e. components which // have their own window). // void setTitle(const char *newTitle); const char * getTitle() const { return title; } void setIconTitle(const char *newIconTitle); const char * getIconTitle() const { return iconTitle; } // // sets which callback to call when the user closes this component // (double click in the upper left corner) - by default hide() is // called on this component, unless a callback is set to something // other than NULL. A pointer to this class will be passed as the // callback data. // // Note: there is only one callback because the user may decide to // delete this component when it is closed. // // C-api: name=setWinCloseCB void setWindowCloseCallback( SoXtComponentCB *func, void *data = NULL) { windowCloseFunc = func; windowCloseData = data; } // // this returns the SoXtComponent for this widget. // If the widget is not a Inventor component, then NULL is returned. // // C-api: name=getComp static SoXtComponent *getComponent(Widget w); // // Widget name and class - these are used when looking up X resource // values for the widget (each subclass provides a className). // const char * getWidgetName() const { return _name; } const char * getClassName() const { return _classname.getString(); } // C-api: expose virtual ~SoXtComponent(); protected: // // If `parent` widget is suplied AND `buildInsideParent` is TRUE, this // component will build inside the given parent widget, else // it will create its own topLevelShell widget (component resides in // its own window). // The topLevelShell can either be created under the given // parent shell (`parent` != NULL) or under the main window. // // The name is used for looking up X resource values. If NULL, // then this component inherits resource values defined for its class. // // Calling setBaseWidget is needed for looking up Xt like // resources in the widget tree. It will use the class name of // the Inventor component (e.g. SoXtRenderArea) instead of // the class name of the Motif widget this component employs // (e.g. XmForm). // // Thus apps are able to do this in their app-defaults file: // // *SoXtRenderArea*BackgroundColor: salmon // SoXtComponent( Widget parent = NULL, const char *name = NULL, SbBool buildInsideParent = TRUE); // Subclasses need to call this method passing the top most // widget after it has been created. void setBaseWidget(Widget w); // Subclasses need to set the class name in the constructor // before the widget is built. void setClassName(const char *n) { _classname = n; } // this routine is called whenever the top level shell widget receives // a close action (WM_DELETE_WINDOW message) from the window manager. // Instead of destroying the widget (default shell behavior) this // routine is used, which by default calls exit(0) if it is the main // window else calls hide() on the component. // virtual void windowCloseAction(); // Support for doing things right after the widget is realized // for the first time. // The base class will set the window and icon title for shell widgets. virtual void afterRealizeHook(); SbBool firstRealize; // // Subclasses should redefine these routines to return the appropriate // default information. Those are used when creating the widget to set // the name (used for resources), window title and window icon // name. Those default values are only used if the user didn't // explicitly specify them. // virtual const char * getDefaultWidgetName() const; virtual const char * getDefaultTitle() const; virtual const char * getDefaultIconTitle() const; // // Register widget - should be called by subclasses after // they have created their top most widget (which is passed here), // and before they build any child widgets. Calling this method // ensures that the widgets name and class will be used when // calls are made to get X resource values for this widget. // // *** NOTE *** // ALL subclasses should register their top most widget within the // component, whether they retrieve resources or not, so that children // widgets can get X resources properly. // Unregister the widget when the widget is destroyed. // void registerWidget(Widget w); void unregisterWidget(Widget w); // subclasses can add a callback to be called whenever the component // becomes visible or become hidden (like when it is iconified). // Sublcasses should use this to attach or detach any sensors they // have, or stop any ongoing anymation. void addVisibilityChangeCallback( SoXtComponentVisibilityCB *func, void *userData = NULL); void removeVisibilityChangeCallback( SoXtComponentVisibilityCB *func, void *userData = NULL); // // This method can be used by subclasses to open a component help // card. The name of the file should be supplied withought a path // name. By default the file will be searched using: // 1) current working directory // 2) SO_HELP_DIR environment variable // 3) $(IVPREFIX)/share/help/Inventor // 4) else bring a no help card found dialog // void openHelpCard(const char *cardName); private: // widgetDestroyed is called when the widget is destroyed. // There is no way to reconstruct the widget tree, so calling // this simply generates an error. The component should be // deleted to dispose of the widget. virtual void widgetDestroyed(); SbBool topLevelShell; // TRUE if in its own window SbBool createdShell; // TRUE if we created that toplevel shell Widget parentWidget; // topLevel shell if in its own window Widget _baseWidget; // returned by getWidget() char *_name; // name of this widget char *title; // title for window if in its own window char *iconTitle; // title for icon if in its own window SbVec2s size; // size of the '_baseWidget' and 'shell' (if toplevel) SbString _classname; // visibiltity stuff SbBool visibleState; SbBool ShellMapped, widgetMapped; SoCallbackList *visibiltyCBList; void checkForVisibilityChange(); static void widgetStructureNotifyCB(Widget, SoXtComponent *, XEvent *, Boolean *); static void shellStructureNotifyCB(Widget, SoXtComponent *, XEvent *, Boolean *); static void widgetDestroyedCB(Widget, XtPointer, XtPointer); // window close action data SoXtComponentCB *windowCloseFunc; void *windowCloseData; static void windowCloseActionCB(Widget, SoXtComponent *, void *); // The widget dictionary maps widgets to SoXtComponents. It's used // by getComponent(), and kept up to date by registerWidget(). static SbDict *widgetDictionary; }; // Inline routines Display * SoXtComponent::getDisplay() { return (_baseWidget != NULL ? XtDisplay(_baseWidget) : NULL); } #endif // _SO_XT_COMPONENT_H_
OpenXIP/xip-libraries
src/extern/inventor/libSoXt/include/Inventor/Xt/SoXtComponent.h
C
apache-2.0
12,290
from __future__ import print_function import sys sys.path.insert(1,"../../../") import h2o from tests import pyunit_utils from h2o.utils.typechecks import assert_is_type from h2o.frame import H2OFrame def h2o_H2OFrame_ascharacter(): """ Python API test: h2o.frame.H2OFrame.ascharacter() Copied from pyunit_ascharacter.py """ h2oframe = h2o.import_file(path=pyunit_utils.locate("smalldata/junit/cars.csv")) newFrame = h2oframe['cylinders'].ascharacter() assert_is_type(newFrame, H2OFrame) assert newFrame.isstring()[0], "h2o.H2OFrame.ascharacter() command is not working." if __name__ == "__main__": pyunit_utils.standalone_test(h2o_H2OFrame_ascharacter()) else: h2o_H2OFrame_ascharacter()
spennihana/h2o-3
h2o-py/tests/testdir_apis/Data_Manipulation/pyunit_h2oH2OFrame_ascharacter.py
Python
apache-2.0
734
#!/usr/bin/python2.5 # Copyright (C) 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # An example script that demonstrates converting a proprietary format to a # Google Transit Feed Specification file. # # You can load table.txt, the example input, in Excel. It contains three # sections: # 1) A list of global options, starting with a line containing the word # 'options'. Each option has an name in the first column and most options # have a value in the second column. # 2) A table of stops, starting with a line containing the word 'stops'. Each # row of the table has 3 columns: name, latitude, longitude # 3) A list of routes. There is an empty row between each route. The first row # for a route lists the short_name and long_name. After the first row the # left-most column lists the stop names visited by the route. Each column # contains the times a single trip visits the stops. # # This is very simple example which you could use as a base for your own # transit feed builder. from __future__ import print_function import transitfeed from optparse import OptionParser import re stops = {} # table is a list of lists in this form # [ ['Short Name', 'Long Name'], # ['Stop 1', 'Stop 2', ...] # [time_at_1, time_at_2, ...] # times for trip 1 # [time_at_1, time_at_2, ...] # times for trip 2 # ... ] def AddRouteToSchedule(schedule, table): if len(table) >= 2: r = schedule.AddRoute(short_name=table[0][0], long_name=table[0][1], route_type='Bus') for trip in table[2:]: if len(trip) > len(table[1]): print("ignoring %s" % trip[len(table[1]):]) trip = trip[0:len(table[1])] t = r.AddTrip(schedule, headsign='My headsign') trip_stops = [] # Build a list of (time, stopname) tuples for i in range(0, len(trip)): if re.search(r'\S', trip[i]): trip_stops.append( (transitfeed.TimeToSecondsSinceMidnight(trip[i]), table[1][i]) ) trip_stops.sort() # Sort by time for (time, stopname) in trip_stops: t.AddStopTime(stop=stops[stopname.lower()], arrival_secs=time, departure_secs=time) def TransposeTable(table): """Transpose a list of lists, using None to extend all input lists to the same length. For example: >>> TransposeTable( [ [11, 12, 13], [21, 22], [31, 32, 33, 34]]) [ [11, 21, 31], [12, 22, 32], [13, None, 33], [None, None, 34]] """ transposed = [] rows = len(table) cols = max(len(row) for row in table) for x in range(cols): transposed.append([]) for y in range(rows): if x < len(table[y]): transposed[x].append(table[y][x]) else: transposed[x].append(None) return transposed def ProcessOptions(schedule, table): service_period = schedule.GetDefaultServicePeriod() agency_name, agency_url, agency_timezone = (None, None, None) for row in table[1:]: command = row[0].lower() if command == 'weekday': service_period.SetWeekdayService() elif command == 'start_date': service_period.SetStartDate(row[1]) elif command == 'end_date': service_period.SetEndDate(row[1]) elif command == 'add_date': service_period.SetDateHasService(date=row[1]) elif command == 'remove_date': service_period.SetDateHasService(date=row[1], has_service=False) elif command == 'agency_name': agency_name = row[1] elif command == 'agency_url': agency_url = row[1] elif command == 'agency_timezone': agency_timezone = row[1] if not (agency_name and agency_url and agency_timezone): print("You must provide agency information") schedule.NewDefaultAgency(agency_name=agency_name, agency_url=agency_url, agency_timezone=agency_timezone) def AddStops(schedule, table): for name, lat_str, lng_str in table[1:]: stop = schedule.AddStop(lat=float(lat_str), lng=float(lng_str), name=name) stops[name.lower()] = stop def ProcessTable(schedule, table): if table[0][0].lower() == 'options': ProcessOptions(schedule, table) elif table[0][0].lower() == 'stops': AddStops(schedule, table) else: transposed = [table[0]] # Keep route_short_name and route_long_name on first row # Transpose rest of table. Input contains the stop names in table[x][0], x # >= 1 with trips found in columns, so we need to transpose table[1:]. # As a diagram Transpose from # [['stop 1', '10:00', '11:00', '12:00'], # ['stop 2', '10:10', '11:10', '12:10'], # ['stop 3', '10:20', '11:20', '12:20']] # to # [['stop 1', 'stop 2', 'stop 3'], # ['10:00', '10:10', '10:20'], # ['11:00', '11:11', '11:20'], # ['12:00', '12:12', '12:20']] transposed.extend(TransposeTable(table[1:])) AddRouteToSchedule(schedule, transposed) def main(): parser = OptionParser() parser.add_option('--input', dest='input', help='Path of input file') parser.add_option('--output', dest='output', help='Path of output file, should end in .zip') parser.set_defaults(output='feed.zip') (options, args) = parser.parse_args() schedule = transitfeed.Schedule() table = [] for line in open(options.input): line = line.rstrip() if not line: ProcessTable(schedule, table) table = [] else: table.append(line.split('\t')) ProcessTable(schedule, table) schedule.WriteGoogleTransitFeed(options.output) if __name__ == '__main__': main()
google/transitfeed
examples/table.py
Python
apache-2.0
6,035
--- layout: page title: "album" description: "masonry" active: gallery header-img: "gallery/p_archive_2/p_archive_2_1.jpg" album-title: "my 1st album" images: - image_path: /gallery/p_archive_2/p_archive_2_1.jpg caption: IMAGE TITLE copyright: © thoshith - image_path: /gallery/p_archive_2/p_archive_2_2.jpg caption: IMAGE TITLE copyright: © thoshith - image_path: /gallery/p_archive_2/p_archive_2_3.jpg caption: IMAGE TITLE copyright: © thoshith - image_path: /gallery/p_archive_2/p_archive_2_4.jpg caption: IMAGE TITLE copyright: © thoshith - image_path: /gallery/p_archive_2/p_archive_2_5.jpg caption: IMAGE TITLE copyright: © thoshith - image_path: /gallery/p_archive_2/p_archive_2_6.jpg caption: IMAGE TITLE copyright: © thoshith - image_path: /gallery/p_archive_2/p_archive_2_7.jpg caption: IMAGE TITLE copyright: © thoshith - image_path: /gallery/p_archive_2/p_archive_2_8.jpg caption: IMAGE TITLE copyright: © thoshith - image_path: /gallery/p_archive_2/p_archive_2_9.jpg caption: IMAGE TITLE copyright: © thoshith --- <html class="no-js" lang="en"> <head> <meta content="charset=utf-8"> </head> <body> <section id="content" role="main"> <div class="wrapper"> <br><br> <h2>{{page.album-title}}</h2> <!-- Gallery __--> <div class="gallery masonry-gallery"> {% for image in page.images %} <figure class="gallery-item"> <header class='gallery-icon'> <a href="{{ site.url }}{{ site.baseurl }}{{ image.image_path }}" class="popup" title="{{ image.caption }}" data-caption="{{ image.copyright }}"> <img src="{{ site.url }}{{ site.baseurl }}{{ image.image_path }}"></a> </header> <figcaption class='gallery-caption'> <div class="entry-summary" id="{{ image.caption }}"> <h3>{{image.caption}}</h3> <p>{{image.copyright}}</p> </div> </figcaption> </figure> {% endfor %} </div> </div><!-- END .wrapper --> </section> <!-- jQuery --> <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <!-- include image popups --> <script src="{{ site.baseurl }}/js/jquery.magnific-popup.js"></script> <script type="text/javascript"> $(document).ready(function($) { $('a.popup').magnificPopup({ type: 'image', gallery:{ enabled:true, navigateByImgClick: true, preload: [0,1] // Will preload 0 - before current, and 1 after the current image }, image: { titleSrc: function(item) { return item.el.attr('title') + '&nbsp;' + item.el.attr('data-caption'); } } // other options }); }); </script> <script src="{{ site.baseurl }}/js/retina.min.js"></script> <!-- include Masonry --> <script src="{{ site.baseurl }}/js/isotope.pkgd.min.js"></script> <!-- include mousewheel plugins --> <script src="{{ site.baseurl }}/js/jquery.mousewheel.min.js"></script> <!-- include carousel plugins --> <script src="{{ site.baseurl}}/js/jquery.tinycarousel.min.js"></script> <!-- include svg line drawing plugin --> <script src="{{ site.baseurl }}/js/jquery.lazylinepainter.min.js"></script> <!-- include custom script --> <script src="{{ site.baseurl }}/js/scripts.js"></script> <!-- Modernizr --> <script src="{{ site.baseurl }}/js/modernizr.js"></script> </body></html>
idbytes/thoshith.github.io
gallery/p_archive_2/index.html
HTML
apache-2.0
3,406
/* * Copyright © 2014 - 2021 Leipzig University (Database Research Group) * * 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.gradoop.flink.model.impl.operators.grouping.functions; import org.gradoop.common.model.api.entities.Element; import org.gradoop.common.model.impl.properties.PropertyValue; import org.gradoop.common.model.impl.properties.PropertyValueList; import org.gradoop.flink.model.impl.operators.grouping.Grouping; import org.gradoop.flink.model.impl.operators.grouping.tuples.GroupItem; import org.gradoop.flink.model.impl.operators.grouping.tuples.LabelGroup; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Base class for vertex and edge item building. */ public class BuildGroupItemBase extends BuildBase { /** * Stores grouping properties and aggregators for vertex labels. */ private final List<LabelGroup> labelGroups; /** * Stores the information about the default label group, this is either the vertex or the * edge default label group. */ private final LabelGroup defaultLabelGroup; /** * Stores the grouping values. Used to avoid object instantiation. */ private List<PropertyValue> groupingValues; /** * Valued constructor. * * @param useLabel true if label shall be used for grouping * @param labelGroups all vertex or edge label groups */ public BuildGroupItemBase( boolean useLabel, List<LabelGroup> labelGroups) { super(useLabel); this.labelGroups = labelGroups; groupingValues = new ArrayList<>(); LabelGroup standardLabelGroup = null; // find and keep the default label group for fast access for (LabelGroup labelGroup : labelGroups) { if (labelGroup.getGroupingLabel().equals(Grouping.DEFAULT_VERTEX_LABEL_GROUP)) { standardLabelGroup = labelGroup; break; } else if (labelGroup.getGroupingLabel().equals(Grouping.DEFAULT_EDGE_LABEL_GROUP)) { standardLabelGroup = labelGroup; break; } } defaultLabelGroup = standardLabelGroup; } /** * Sets the basic values for either a vertex or an edge group item. * * @param groupItem the group item to be set * @param element the epgm element * @param labelGroup label group to be assigned * @throws IOException on failure */ protected void setGroupItem(GroupItem groupItem, Element element, LabelGroup labelGroup) throws IOException { // stores all, in the label group specified, grouping values of the element, if the element // does not have a property a null property value is stored for (String groupPropertyKey : labelGroup.getPropertyKeys()) { if (element.hasProperty(groupPropertyKey)) { groupingValues.add(element.getPropertyValue(groupPropertyKey)); } else { groupingValues.add(PropertyValue.NULL_VALUE); } } // If the label group is the default one and the labels shall be used for grouping the // elements labels are kept, otherwise the label given by the group is taken. The default // label groups label is empty and if the current label group is a manually specified one its // label is also taken. if (labelGroup.getGroupingLabel().equals(getDefaultLabelGroup().getGroupingLabel()) && useLabel()) { groupItem.setGroupLabel(element.getLabel()); } else { groupItem.setGroupLabel(labelGroup.getGroupLabel()); } groupItem.setAggregateValues(labelGroup.getIncrementValues(element)); groupItem.setLabelGroup(labelGroup); groupItem.setGroupingValues(PropertyValueList.fromPropertyValues(groupingValues)); groupingValues.clear(); } protected List<LabelGroup> getLabelGroups() { return labelGroups; } protected LabelGroup getDefaultLabelGroup() { return defaultLabelGroup; } }
galpha/gradoop
gradoop-flink/src/main/java/org/gradoop/flink/model/impl/operators/grouping/functions/BuildGroupItemBase.java
Java
apache-2.0
4,331
/* * 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 com.gemstone.gemfire.internal.cache; /** * Represents a factory for instances of {@link ReliableMessageQueue}. * The Cache will have an instance of the factory that can be obtained * from {@link GemFireCacheImpl#getReliableMessageQueueFactory}. * * @author Darrel Schneider * @since 5.0 */ public interface ReliableMessageQueueFactory { /** * Creates an instance of {@link ReliableMessageQueue} given the region * that the queue will be on. * @param region the distributed region that the created queue will service. * @return the created queue */ public ReliableMessageQueue create(DistributedRegion region); /** * Cleanly shutdown this factory flushing any persistent data to disk. * @param force true if close should always work * @throws IllegalStateException if <code>force</code> is false and the factory * is still in use. The factory is in use as long as a queue it produced remains * unclosed. */ public void close(boolean force); }
sshcherbakov/incubator-geode
gemfire-core/src/main/java/com/gemstone/gemfire/internal/cache/ReliableMessageQueueFactory.java
Java
apache-2.0
1,803
#include "extensions/filters/http/cache/simple_http_cache/simple_http_cache.h" #include "envoy/registry/registry.h" #include "common/buffer/buffer_impl.h" #include "common/http/header_map_impl.h" #include "source/extensions/filters/http/cache/simple_http_cache/config.pb.h" namespace Envoy { namespace Extensions { namespace HttpFilters { namespace Cache { namespace { class SimpleLookupContext : public LookupContext { public: SimpleLookupContext(SimpleHttpCache& cache, LookupRequest&& request) : cache_(cache), request_(std::move(request)) {} void getHeaders(LookupHeadersCallback&& cb) override { auto entry = cache_.lookup(request_); body_ = std::move(entry.body_); cb(entry.response_headers_ ? request_.makeLookupResult(std::move(entry.response_headers_), body_.size()) : LookupResult{}); } void getBody(const AdjustedByteRange& range, LookupBodyCallback&& cb) override { ASSERT(range.end() <= body_.length(), "Attempt to read past end of body."); cb(std::make_unique<Buffer::OwnedImpl>(&body_[range.begin()], range.length())); } void getTrailers(LookupTrailersCallback&&) override { // TODO(toddmgreer): Support trailers. NOT_IMPLEMENTED_GCOVR_EXCL_LINE; } const LookupRequest& request() const { return request_; } private: SimpleHttpCache& cache_; const LookupRequest request_; std::string body_; }; class SimpleInsertContext : public InsertContext { public: SimpleInsertContext(LookupContext& lookup_context, SimpleHttpCache& cache) : key_(dynamic_cast<SimpleLookupContext&>(lookup_context).request().key()), cache_(cache) {} void insertHeaders(const Http::ResponseHeaderMap& response_headers, bool end_stream) override { ASSERT(!committed_); response_headers_ = Http::createHeaderMap<Http::ResponseHeaderMapImpl>(response_headers); if (end_stream) { commit(); } } void insertBody(const Buffer::Instance& chunk, InsertCallback ready_for_next_chunk, bool end_stream) override { ASSERT(!committed_); ASSERT(ready_for_next_chunk || end_stream); body_.add(chunk); if (end_stream) { commit(); } else { ready_for_next_chunk(true); } } void insertTrailers(const Http::ResponseTrailerMap&) override { NOT_IMPLEMENTED_GCOVR_EXCL_LINE; // TODO(toddmgreer): support trailers } private: void commit() { committed_ = true; cache_.insert(key_, std::move(response_headers_), body_.toString()); } Key key_; Http::ResponseHeaderMapPtr response_headers_; SimpleHttpCache& cache_; Buffer::OwnedImpl body_; bool committed_ = false; }; } // namespace LookupContextPtr SimpleHttpCache::makeLookupContext(LookupRequest&& request) { return std::make_unique<SimpleLookupContext>(*this, std::move(request)); } void SimpleHttpCache::updateHeaders(LookupContextPtr&& lookup_context, Http::ResponseHeaderMapPtr&& response_headers) { ASSERT(lookup_context); ASSERT(response_headers); // TODO(toddmgreer): Support updating headers. NOT_IMPLEMENTED_GCOVR_EXCL_LINE; } SimpleHttpCache::Entry SimpleHttpCache::lookup(const LookupRequest& request) { absl::ReaderMutexLock lock(&mutex_); auto iter = map_.find(request.key()); if (iter == map_.end()) { return Entry{}; } ASSERT(iter->second.response_headers_); return SimpleHttpCache::Entry{ Http::createHeaderMap<Http::ResponseHeaderMapImpl>(*iter->second.response_headers_), iter->second.body_}; } void SimpleHttpCache::insert(const Key& key, Http::ResponseHeaderMapPtr&& response_headers, std::string&& body) { absl::WriterMutexLock lock(&mutex_); map_[key] = SimpleHttpCache::Entry{std::move(response_headers), std::move(body)}; } InsertContextPtr SimpleHttpCache::makeInsertContext(LookupContextPtr&& lookup_context) { ASSERT(lookup_context != nullptr); return std::make_unique<SimpleInsertContext>(*lookup_context, *this); } constexpr absl::string_view Name = "envoy.extensions.http.cache.simple"; CacheInfo SimpleHttpCache::cacheInfo() const { CacheInfo cache_info; cache_info.name_ = Name; return cache_info; } class SimpleHttpCacheFactory : public HttpCacheFactory { public: // From UntypedFactory std::string name() const override { return std::string(Name); } // From TypedFactory ProtobufTypes::MessagePtr createEmptyConfigProto() override { return std::make_unique< envoy::source::extensions::filters::http::cache::SimpleHttpCacheConfig>(); } // From HttpCacheFactory HttpCache& getCache(const envoy::extensions::filters::http::cache::v3alpha::CacheConfig&) override { return cache_; } private: SimpleHttpCache cache_; }; static Registry::RegisterFactory<SimpleHttpCacheFactory, HttpCacheFactory> register_; } // namespace Cache } // namespace HttpFilters } // namespace Extensions } // namespace Envoy
istio/envoy
source/extensions/filters/http/cache/simple_http_cache/simple_http_cache.cc
C++
apache-2.0
4,919