code
stringlengths
67
466k
docstring
stringlengths
1
13.2k
public static Map<String, Method> getGetters(Class<?> clazz) { Map<String, Method> getters = new HashMap<String, Method>(); Method[] methods = clazz.getMethods(); for (Method method : methods) { String methodName = method.getName(); if (method.getParameterTypes().length == 0) { if (methodName.startsWith("get") && methodName.length() > 3) { String propertyName = methodName.substring(3, 4) .toLowerCase(); if (methodName.length() > 4) { propertyName += methodName.substring(4); } getters.put(propertyName, method); } else if (methodName.startsWith("is") && methodName.length() > 2 && Boolean.TYPE.equals(method.getReturnType())) { String propertyName = methodName.substring(2, 3) .toLowerCase(); if (methodName.length() > 3) { propertyName += methodName.substring(3); } getters.put(propertyName, method); } } } return getters; }
get a map of public getters (propertyName -> Method) @param clazz @return
public static Method getGetterPropertyMethod(Class<?> type, String propertyName) { String sourceMethodName = "get" + BeanUtils.capitalizePropertyName(propertyName); Method sourceMethod = BeanUtils.getMethod(type, sourceMethodName); if (sourceMethod == null) { sourceMethodName = "is" + BeanUtils.capitalizePropertyName(propertyName); sourceMethod = BeanUtils.getMethod(type, sourceMethodName); if (sourceMethod != null && sourceMethod.getReturnType() != Boolean.TYPE) { sourceMethod = null; } } return sourceMethod; }
get the getter method corresponding to given property
public static Method getSetterPropertyMethod(Class<?> type, String propertyName) { String sourceMethodName = "set" + BeanUtils.capitalizePropertyName(propertyName); Method sourceMethod = BeanUtils.getMethod(type, sourceMethodName); return sourceMethod; }
get the setter method corresponding to given property
@Override public Optional<SoyMapData> toSoyMap(@Nullable final Object model) throws Exception { if (model instanceof SoyMapData) { return Optional.of((SoyMapData) model); } if (model instanceof Map) { return Optional.of(new SoyMapData(model)); } return Optional.of(new SoyMapData()); }
Pass a model object and return a SoyMapData if a model object happens to be a SoyMapData. An implementation will also check if a passed in object is a Map and return a SoyMapData wrapping that map
public static String arrayToPath(final String[] array) { if (array == null) { return ""; } return Joiner.on(",").skipNulls().join(array); }
Converts a String array to a String with coma separator example: String["a.soy", "b.soy"] - output: a.soy,b.soy @param array - array @return comma separated list
@Override public void validate() { boolean valid = true; if (hasValue()) { Long value = getValue(); if (value != null) { // scrub the value to format properly setText(value2text(value)); } else { // empty is ok and value != null ok, this is invalid valid = false; } } setStyleName(CLASSNAME_INVALID, !valid); }
styling
@Override public int getShadowSize() { Element shadowElement = shadow.getElement(); shadowElement.setScrollTop(10000); return shadowElement.getScrollTop(); }
Returns the size of the shadow element
public Optional<Directives> getFirstHeaderValueAsDirectives(String headerKey) { Optional<Header> header = getFirstHeader(headerKey); return header.map(Header::getDirectives); }
TODO: Eliminate null
@SuppressWarnings("unchecked") public static <T> T parseNumber(String value, Class<T> targetClass){ if(value == null){ return null; } try{ if(Integer.class == targetClass){ return (T)Integer.valueOf(value); } else if(Float.class == targetClass){ return (T)Float.valueOf(value); } else if(Double.class == targetClass){ return (T)Double.valueOf(value); } else if(Byte.class == targetClass){ return (T)Byte.valueOf(value); } else if(Short.class == targetClass){ return (T)Short.valueOf(value); } else if(Long.class == targetClass){ return (T)Long.valueOf(value); } else{ return null; } } catch(NumberFormatException e){} return null; }
Tries to parse value into the targetClass. The implementation is no elegant, but it's faster than targetClass.getConstructor(String.class).newInstance(value); @param value @param targetClass @return T instance of value or null if the parsing failed
public static <T> T parseNumber(String value, Class<T> targetClass, T defaultValue){ T number = parseNumber(value,targetClass); if(number == null){ return defaultValue; } return number; }
Tries to parse value into the targetClass. The implementation is no elegant, but it's faster than targetClass.getConstructor(String.class).newInstance(value); @param value @param targetClass @param defaultValue default value to return if the value can not be parsed. @return T instance of value or defaultValue if the parsing failed
public Object get(IConverter converter, Object sourceObject, TypeReference<?> destinationType) { return convertedObjects.get(new ConvertedObjectsKey(converter, sourceObject, destinationType)); }
get the converted object corresponding to sourceObject as converted to destination type by converter @param converter @param sourceObject @param destinationType @return
public void add(IConverter converter, Object sourceObject, TypeReference<?> destinationType, Object convertedObject) { convertedObjects.put(new ConvertedObjectsKey(converter, sourceObject, destinationType), convertedObject); }
add a converted object to the pool @param converter the converter that made the conversion @param sourceObject the source object that has been converted @param destinationType the destination type @param convertedObject the converted object
public void remove(IConverter converter, Object sourceObject, TypeReference<?> destinationType) { convertedObjects.remove(new ConvertedObjectsKey(converter, sourceObject, destinationType)); }
remove a converted object from the pool @param converter @param sourceObject @param destinationType
public WebservicesMetaData loadFromVFSRoot(UnifiedVirtualFile root) { WebservicesMetaData webservices = null; UnifiedVirtualFile wsdd = root.findChildFailSafe("META-INF/webservices.xml"); // Maybe a web application deployment? if (null == wsdd) { wsdd = root.findChildFailSafe("WEB-INF/webservices.xml"); } // the descriptor is optional if (wsdd != null) { return load(wsdd.toURL()); } return webservices; }
Load webservices.xml from <code>META-INF/webservices.xml</code> or <code>WEB-INF/webservices.xml</code>. @param root virtual file root @return WebservicesMetaData or <code>null</code> if it cannot be found
private int[] convertBatch(int[] batch) { int[] conv = new int[batch.length]; for (int i=0; i<batch.length; i++) { conv[i] = sample[batch[i]]; } return conv; }
Converts a batch indexing into the sample, to a batch indexing into the original function. @param batch The batch indexing into the sample. @return A new batch indexing into the original function, containing only the indices from the sample.
public static boolean containsAtLeastOneNonBlank(List<String> list){ for(String str : list){ if(StringUtils.isNotBlank(str)){ return true; } } return false; }
Check that a list allowing null and empty item contains at least one element that is not blank. @param list can't be null @return
public static List<Integer> toIntegerList(List<String> strList, boolean failOnException){ List<Integer> intList = new ArrayList<Integer>(); for(String str : strList){ try{ intList.add(Integer.parseInt(str)); } catch(NumberFormatException nfe){ if(failOnException){ return null; } else{ intList.add(null); } } } return intList; }
Parse a list of String into a list of Integer. If one element can not be parsed, the behavior depends on the value of failOnException. @param strList can't be null @param failOnException if an element can not be parsed should we return null or add a null element to the list. @return list of all String parsed as Integer or null if failOnException
public static void add(double[] array1, double[] array2) { assert (array1.length == array2.length); for (int i=0; i<array1.length; i++) { array1[i] += array2[i]; } }
Each element of the second array is added to each element of the first.
public static boolean containsOnlyNull(Object... values){ for(Object o : values){ if(o!= null){ return false; } } return true; }
Check that an array only contains null elements. @param values, can't be null @return
public static boolean containsOnlyNotNull(Object... values){ for(Object o : values){ if(o== null){ return false; } } return true; }
Check that an array only contains elements that are not null. @param values, can't be null @return
@RequestMapping(value="/soy/compileJs", method=GET) public ResponseEntity<String> compile(@RequestParam(required = false, value="hash", defaultValue = "") final String hash, @RequestParam(required = true, value = "file") final String[] templateFileNames, @RequestParam(required = false, value = "locale") String locale, @RequestParam(required = false, value = "disableProcessors", defaultValue = "false") String disableProcessors, final HttpServletRequest request) throws IOException { return compileJs(templateFileNames, hash, new Boolean(disableProcessors).booleanValue(), request, locale); }
An endpoint to compile an array of soy templates to JavaScript. This endpoint is a preferred way of compiling soy templates to JavaScript but it requires a user to compose a url on their own or using a helper class TemplateUrlComposer, which calculates checksum of a file and puts this in url so that whenever a file changes, after a deployment a JavaScript, url changes and a new hash is appended to url, which enforces getting of new compiles JavaScript resource. Invocation of this url may throw two types of http exceptions: 1. notFound - usually when a TemplateResolver cannot find a template with an associated name 2. error - usually when there is a permission error and a user is not allowed to compile a template into a JavaScript @param hash - some unique number that should be used when we are caching this resource in a browser and we use http cache headers @param templateFileNames - an array of template names, e.g. client-words,server-time, which may or may not contain extension currently three modes are supported - soy extension, js extension and no extension, which is preferred @param disableProcessors - whether the controller should run registered outputProcessors after the compilation is complete. @param request - HttpServletRequest @param locale - locale @return response entity, which wraps a compiled soy to JavaScript files. @throws IOException - io error
@Override public HandlerRegistration addFocusHandler(FocusHandler handler) { return ensureHandlers().addHandler(FocusEvent.getType(), handler); }
Adds a {@link FocusEvent} handler. @param handler the handler @return returns the handler registration
@Override public HandlerRegistration addBlurHandler(BlurHandler handler) { return ensureHandlers().addHandler(BlurEvent.getType(), handler); }
Adds a {@link BlurEvent} handler. @param handler the handler @return returns the handler registration
public static void assertLogNormalized(double[] logProps, double delta) { double logPropSum = Vectors.logSum(logProps); assert(Utilities.equals(0.0, logPropSum, delta)); }
Asserts that the parameters are log-normalized within some delta.
public static XMLInputFactory createXMLInputFactory(boolean nsAware) { XMLInputFactory factory = XMLInputFactory.newInstance(); factory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, nsAware); factory.setProperty(XMLInputFactory.SUPPORT_DTD, Boolean.FALSE); factory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, Boolean.FALSE); factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE); factory.setXMLResolver(new XMLResolver() { public Object resolveEntity(String publicID, String systemID, String baseURI, String namespace) throws XMLStreamException { throw Messages.MESSAGES.readingExternalEntitiesDisabled(); } }); return factory; }
Return a new factory so that the caller can set sticky parameters. @param nsAware true is nsAware @return XMLInputFactory
public void addUsedConverter(IConverter converter, Object sourceObject, TypeReference<?> destinationType) { UsedConverter usedConverter = new UsedConverter(converter, sourceObject == null ? null : sourceObject.getClass(), destinationType); if (!usedConvertersSet.contains(usedConverter)) { usedConvertersSet.add(usedConverter); usedConvertersList.add(usedConverter); } }
add a converter that has been used to convert from sourceObject to destination type (if it has not already been added) @param converter @param sourceObject @param destinationType
public int[] sampleBatchWithReplacement() { // Sample the indices with replacement. int[] batch = new int[batchSize]; for (int i=0; i<batch.length; i++) { batch[i] = Prng.nextInt(numExamples); } return batch; }
Samples a batch of indices in the range [0, numExamples) with replacement.
public int[] sampleBatchWithoutReplacement() { int[] batch = new int[batchSize]; for (int i=0; i<batch.length; i++) { if (cur == indices.length) { cur = 0; } if (cur == 0) { IntArrays.shuffle(indices); } batch[i] = indices[cur++]; } return batch; }
Samples a batch of indices in the range [0, numExamples) without replacement.
public static StatusCode lbfgs( double[] x, MutableDouble ptr_fx, LBFGSCallback cd, LBFGSPrm _param ) { final int n = x.length; StatusCode ret, ls_ret; MutableInt ls = new MutableInt(0); int i, j, k, end, bound; double step; /* Constant parameters and their default values. */ LBFGSPrm param = (_param != null) ? _param : new LBFGSPrm(); final int m = param.m; double[] xp; double[] g, gp, pg = null; double[] d, w, pf = null; IterationData[] lm = null; IterationData it = null; double ys, yy; double xnorm, gnorm, beta; double fx = 0.; double rate = 0.; LineSearchAlgInternal linesearch_choice = LineSearchAlgInternal.morethuente; /* Check the input parameters for errors. */ if (n <= 0) { return LBFGSERR_INVALID_N; } if (param.epsilon < 0.) { return LBFGSERR_INVALID_EPSILON; } if (param.past < 0) { return LBFGSERR_INVALID_TESTPERIOD; } if (param.delta < 0.) { return LBFGSERR_INVALID_DELTA; } if (param.min_step < 0.) { return LBFGSERR_INVALID_MINSTEP; } if (param.max_step < param.min_step) { return LBFGSERR_INVALID_MAXSTEP; } if (param.ftol < 0.) { return LBFGSERR_INVALID_FTOL; } if (param.linesearch == LBFGS_LINESEARCH_BACKTRACKING_WOLFE || param.linesearch == LBFGS_LINESEARCH_BACKTRACKING_STRONG_WOLFE) { if (param.wolfe <= param.ftol || 1. <= param.wolfe) { return LBFGSERR_INVALID_WOLFE; } } if (param.gtol < 0.) { return LBFGSERR_INVALID_GTOL; } if (param.xtol < 0.) { return LBFGSERR_INVALID_XTOL; } if (param.max_linesearch <= 0) { return LBFGSERR_INVALID_MAXLINESEARCH; } if (param.orthantwise_c < 0.) { return LBFGSERR_INVALID_ORTHANTWISE; } if (param.orthantwise_start < 0 || n < param.orthantwise_start) { return LBFGSERR_INVALID_ORTHANTWISE_START; } if (param.orthantwise_end < 0) { param.orthantwise_end = n; } if (n < param.orthantwise_end) { return LBFGSERR_INVALID_ORTHANTWISE_END; } if (param.orthantwise_c != 0.) { switch (param.linesearch) { case LBFGS_LINESEARCH_BACKTRACKING_WOLFE: linesearch_choice = LineSearchAlgInternal.backtracking_owlqn; break; default: /* Only the backtracking method is available. */ return LBFGSERR_INVALID_LINESEARCH; } } else { switch (param.linesearch) { case LBFGS_LINESEARCH_MORETHUENTE: linesearch_choice = LineSearchAlgInternal.morethuente; break; case LBFGS_LINESEARCH_BACKTRACKING_ARMIJO: case LBFGS_LINESEARCH_BACKTRACKING_WOLFE: case LBFGS_LINESEARCH_BACKTRACKING_STRONG_WOLFE: linesearch_choice = LineSearchAlgInternal.backtracking; break; default: return LBFGSERR_INVALID_LINESEARCH; } } /* Allocate working space. */ xp = new double[n]; g = new double[n]; gp = new double[n]; d = new double[n]; w = new double[n]; if (param.orthantwise_c != 0.) { /* Allocate working space for OW-LQN. */ pg = new double[n]; } /* Allocate limited memory storage. */ lm = new IterationData[m]; /* Initialize the limited memory. */ for (i = 0;i < m;++i) { lm[i] = new IterationData(); it = lm[i]; it.alpha = 0; it.ys = 0; it.s = new double[n]; it.y = new double[n]; } /* Allocate an array for storing previous values of the objective function. */ if (0 < param.past) { pf = new double[param.past]; } /* Evaluate the function value and its gradient. */ fx = cd.proc_evaluate(x, g, 0); if (0. != param.orthantwise_c) { /* Compute the L1 norm of the variable and add it to the object value. */ xnorm = owlqn_x1norm(x, param.orthantwise_start, param.orthantwise_end); fx += xnorm * param.orthantwise_c; owlqn_pseudo_gradient( pg, x, g, n, param.orthantwise_c, param.orthantwise_start, param.orthantwise_end ); } /* Store the initial value of the objective function. */ if (pf != null) { pf[0] = fx; } /* Compute the direction; we assume the initial hessian matrix H_0 as the identity matrix. */ if (param.orthantwise_c == 0.) { vecncpy(d, g, n); } else { vecncpy(d, pg, n); } /* Make sure that the initial variables are not a minimizer. */ xnorm = vec2norm(x, n); if (param.orthantwise_c == 0.) { gnorm = vec2norm(g, n); } else { gnorm = vec2norm(pg, n); } if (xnorm < 1.0) xnorm = 1.0; if (gnorm / xnorm <= param.epsilon) { ptr_fx.v = fx; return LBFGS_ALREADY_MINIMIZED; } /* Compute the initial step: step = 1.0 / sqrt(vecdot(d, d, n)) */ step = vec2norminv(d, n); k = 1; end = 0; for (;;) { /* Store the current position and gradient vectors. */ veccpy(xp, x, n); veccpy(gp, g, n); /* Search for an optimal step. */ MutableDouble fxRef = new MutableDouble(fx); MutableDouble stepRef = new MutableDouble(step); if (param.orthantwise_c == 0.) { ls_ret = linesearch(n, x, fxRef, g, d, stepRef, xp, gp, w, cd, param, ls, linesearch_choice); } else { ls_ret = linesearch(n, x, fxRef, g, d, stepRef, xp, pg, w, cd, param, ls, linesearch_choice); owlqn_pseudo_gradient( pg, x, g, n, param.orthantwise_c, param.orthantwise_start, param.orthantwise_end ); } fx = fxRef.v; step = stepRef.v; if (ls_ret.ret < 0) { /* Revert to the previous point. */ veccpy(x, xp, n); veccpy(g, gp, n); ptr_fx.v = fx; return ls_ret; } /* Compute x and g norms. */ xnorm = vec2norm(x, n); if (param.orthantwise_c == 0.) { gnorm = vec2norm(g, n); } else { gnorm = vec2norm(pg, n); } /* Report the progress. */ ret = cd.proc_progress(x, g, fx, xnorm, gnorm, step, k, ls.v); if (ret.ret != 0) { ptr_fx.v = fx; return ret; } /* Convergence test. The criterion is given by the following formula: |g(x)| / \max(1, |x|) < \epsilon */ if (xnorm < 1.0) xnorm = 1.0; if (gnorm / xnorm <= param.epsilon) { /* Convergence. */ ret = LBFGS_SUCCESS; break; } /* Test for stopping criterion. The criterion is given by the following formula: (f(past_x) - f(x)) / f(x) < \delta */ if (pf != null) { /* We don't test the stopping criterion while k < past. */ if (param.past <= k) { /* Compute the relative improvement from the past. */ rate = (pf[k % param.past] - fx) / fx; /* The stopping criterion. */ if (rate < param.delta) { ret = LBFGS_STOP; break; } } /* Store the current value of the objective function. */ pf[k % param.past] = fx; } if (param.max_iterations != 0 && param.max_iterations < k+1) { /* Maximum number of iterations. */ ret = LBFGSERR_MAXIMUMITERATION; break; } /* Update vectors s and y: s_{k+1} = x_{k+1} - x_{k} = \step * d_{k}. y_{k+1} = g_{k+1} - g_{k}. */ it = lm[end]; vecdiff(it.s, x, xp, n); vecdiff(it.y, g, gp, n); /* Compute scalars ys and yy: ys = y^t \cdot s = 1 / \rho. yy = y^t \cdot y. Notice that yy is used for scaling the hessian matrix H_0 (Cholesky factor). */ ys = vecdot(it.y, it.s, n); yy = vecdot(it.y, it.y, n); it.ys = ys; /* Recursive formula to compute dir = -(H \cdot g). This is described in page 779 of: Jorge Nocedal. Updating Quasi-Newton Matrices with Limited Storage. Mathematics of Computation, Vol. 35, No. 151, pp. 773--782, 1980. */ bound = (m <= k) ? m : k; ++k; end = (end + 1) % m; /* Compute the steepest direction. */ if (param.orthantwise_c == 0.) { /* Compute the negative of gradients. */ vecncpy(d, g, n); } else { vecncpy(d, pg, n); } j = end; for (i = 0;i < bound;++i) { j = (j + m - 1) % m; /* if (--j == -1) j = m-1; */ it = lm[j]; /* \alpha_{j} = \rho_{j} s^{t}_{j} \cdot q_{k+1}. */ it.alpha = vecdot(it.s, d, n); it.alpha /= it.ys; /* q_{i} = q_{i+1} - \alpha_{i} y_{i}. */ vecadd(d, it.y, -it.alpha, n); } vecscale(d, ys / yy, n); for (i = 0;i < bound;++i) { it = lm[j]; /* \beta_{j} = \rho_{j} y^t_{j} \cdot \gamma_{i}. */ beta = vecdot(it.y, d, n); beta /= it.ys; /* \gamma_{i+1} = \gamma_{i} + (\alpha_{j} - \beta_{j}) s_{j}. */ vecadd(d, it.s, it.alpha - beta, n); j = (j + 1) % m; /* if (++j == m) j = 0; */ } /* Constrain the search direction for orthant-wise updates. */ if (param.orthantwise_c != 0.) { for (i = param.orthantwise_start;i < param.orthantwise_end;++i) { if (d[i] * pg[i] >= 0) { d[i] = 0; } } } /* Now the search direction d is ready. We try step = 1 first. */ step = 1.0; } /* Return the final value of the objective function. */ ptr_fx.v = fx; return ret; }
Start a L-BFGS optimization. @param n The number of variables. @param x The array of variables. A client program can set default values for the optimization and receive the optimization result through this array. This array must be allocated by ::lbfgs_malloc function for libLBFGS built with SSE/SSE2 optimization routine enabled. The library built without SSE/SSE2 optimization does not have such a requirement. @param ptr_fx The pointer to the variable that receives the final value of the objective function for the variables. This argument can be set to \c null if the final value of the objective function is unnecessary. @param proc_evaluate The callback function to provide function and gradient evaluations given a current values of variables. A client program must implement a callback function compatible with \ref lbfgs_evaluate_t and pass the pointer to the callback function. @param proc_progress The callback function to receive the progress (the number of iterations, the current value of the objective function) of the minimization process. This argument can be set to \c null if a progress report is unnecessary. @param instance A user data for the client program. The callback functions will receive the value of this argument. @param param The pointer to a structure representing parameters for L-BFGS optimization. A client program can set this parameter to \c null to use the default parameters. Call lbfgs_parameter_init() function to fill a structure with the default values. @retval int The status code. This function returns zero if the minimization process terminates without an error. A non-zero value indicates an error.
private static double CUBIC_MINIMIZER(double cm, double u, double fu, double du, double v, double fv, double dv) { double a, d, gamma, theta, p, q, r, s; d = (v) - (u); theta = ((fu) - (fv)) * 3 / d + (du) + (dv); p = Math.abs(theta); q = Math.abs(du); r = Math.abs(dv); s = max3(p, q, r); /* gamma = s*sqrt((theta/s)**2 - (du/s) * (dv/s)) */ a = theta / s; gamma = s * Math.sqrt(a * a - ((du) / s) * ((dv) / s)); if ((v) < (u)) gamma = -gamma; p = gamma - (du) + theta; q = gamma - (du) + gamma + (dv); r = p / q; (cm) = (u) + r * d; return cm; }
Find a minimizer of an interpolated cubic function. @param cm The minimizer of the interpolated cubic. @param u The value of one point, u. @param fu The value of f(u). @param du The value of f'(u). @param v The value of another point, v. @param fv The value of f(v). @param du The value of f'(v).
private static double CUBIC_MINIMIZER2(double cm, double u, double fu, double du, double v, double fv, double dv, double xmin, double xmax) { double a, d, gamma, theta, p, q, r, s; d = (v) - (u); theta = ((fu) - (fv)) * 3 / d + (du) + (dv); p = Math.abs(theta); q = Math.abs(du); r = Math.abs(dv); s = max3(p, q, r); /* gamma = s*sqrt((theta/s)**2 - (du/s) * (dv/s)) */ a = theta / s; gamma = s * Math.sqrt(max2(0, a * a - ((du) / s) * ((dv) / s))); if ((u) < (v)) gamma = -gamma; p = gamma - (dv) + theta; q = gamma - (dv) + gamma + (du); r = p / q; if (r < 0. && gamma != 0.) { (cm) = (v) - r * d; } else if (a < 0) { (cm) = (xmax); } else { (cm) = (xmin); } return cm; }
Find a minimizer of an interpolated cubic function. @param cm The minimizer of the interpolated cubic. @param u The value of one point, u. @param fu The value of f(u). @param du The value of f'(u). @param v The value of another point, v. @param fv The value of f(v). @param du The value of f'(v). @param xmin The maximum value. @param xmin The minimum value.
private static double QUARD_MINIMIZER(double qm, double u, double fu, double du, double v, double fv) { double a, d, gamma, theta, p, q, r, s; a = (v) - (u); (qm) = (u) + (du) / (((fu) - (fv)) / a + (du)) / 2 * a; return qm; }
Find a minimizer of an interpolated quadratic function. @param qm The minimizer of the interpolated quadratic. @param u The value of one point, u. @param fu The value of f(u). @param du The value of f'(u). @param v The value of another point, v. @param fv The value of f(v).
private static double QUARD_MINIMIZER2(double qm, double u, double du, double v, double dv) { double a, d, gamma, theta, p, q, r, s; a = (u) - (v); (qm) = (v) + (dv) / ((dv) - (du)) * a; return qm; }
Find a minimizer of an interpolated quadratic function. @param qm The minimizer of the interpolated quadratic. @param u The value of one point, u. @param du The value of f'(u). @param v The value of another point, v. @param dv The value of f'(v).
private static StatusCode update_trial_interval(UpdVals uv) { double x = uv.x; double fx = uv.fx; double dx = uv.dx; double y = uv.y; double fy = uv.fy; double dy = uv.dy; double t = uv.t; double ft = uv.ft; double dt = uv.dt; double tmin = uv.tmin; double tmax = uv.tmax; int brackt = uv.brackt; int bound; boolean dsign = fsigndiff(dt, dx); double mc = 0; /* minimizer of an interpolated cubic. */ double mq = 0; /* minimizer of an interpolated quadratic. */ double newt = 0; /* new trial value. */ // TODO: Remove: USES_MINIMIZER; /* for CUBIC_MINIMIZER and QUARD_MINIMIZER. */ /* Check the input parameters for errors. */ if (brackt != 0) { if (t <= min2(x, y) || max2(x, y) <= t) { /* The trival value t is out of the interval. */ return LBFGSERR_OUTOFINTERVAL; } if (0. <= dx * (t - x)) { /* The function must decrease from x. */ return LBFGSERR_INCREASEGRADIENT; } if (tmax < tmin) { /* Incorrect tmin and tmax specified. */ return LBFGSERR_INCORRECT_TMINMAX; } } /* Trial value selection. */ if (fx < ft) { /* Case 1: a higher function value. The minimum is brackt. If the cubic minimizer is closer to x than the quadratic one, the cubic one is taken, else the average of the minimizers is taken. */ brackt = 1; bound = 1; mc = CUBIC_MINIMIZER(mc, x, fx, dx, t, ft, dt); mq = QUARD_MINIMIZER(mq, x, fx, dx, t, ft); if (Math.abs(mc - x) < Math.abs(mq - x)) { newt = mc; } else { newt = mc + 0.5 * (mq - mc); } } else if (dsign) { /* Case 2: a lower function value and derivatives of opposite sign. The minimum is brackt. If the cubic minimizer is closer to x than the quadratic (secant) one, the cubic one is taken, else the quadratic one is taken. */ brackt = 1; bound = 0; mc = CUBIC_MINIMIZER(mc, x, fx, dx, t, ft, dt); mq = QUARD_MINIMIZER2(mq, x, dx, t, dt); if (Math.abs(mc - t) > Math.abs(mq - t)) { newt = mc; } else { newt = mq; } } else if (Math.abs(dt) < Math.abs(dx)) { /* Case 3: a lower function value, derivatives of the same sign, and the magnitude of the derivative decreases. The cubic minimizer is only used if the cubic tends to infinity in the direction of the minimizer or if the minimum of the cubic is beyond t. Otherwise the cubic minimizer is defined to be either tmin or tmax. The quadratic (secant) minimizer is also computed and if the minimum is brackt then the the minimizer closest to x is taken, else the one farthest away is taken. */ bound = 1; mc = CUBIC_MINIMIZER2(mc, x, fx, dx, t, ft, dt, tmin, tmax); mq = QUARD_MINIMIZER2(mq, x, dx, t, dt); if (brackt != 0) { if (Math.abs(t - mc) < Math.abs(t - mq)) { newt = mc; } else { newt = mq; } } else { if (Math.abs(t - mc) > Math.abs(t - mq)) { newt = mc; } else { newt = mq; } } } else { /* Case 4: a lower function value, derivatives of the same sign, and the magnitude of the derivative does not decrease. If the minimum is not brackt, the step is either tmin or tmax, else the cubic minimizer is taken. */ bound = 0; if (brackt != 0) { newt = CUBIC_MINIMIZER(newt, t, ft, dt, y, fy, dy); } else if (x < t) { newt = tmax; } else { newt = tmin; } } /* Update the interval of uncertainty. This update does not depend on the new step or the case analysis above. - Case a: if f(x) < f(t), x <- x, y <- t. - Case b: if f(t) <= f(x) && f'(t)*f'(x) > 0, x <- t, y <- y. - Case c: if f(t) <= f(x) && f'(t)*f'(x) < 0, x <- t, y <- x. */ if (fx < ft) { /* Case a */ y = t; fy = ft; dy = dt; } else { /* Case c */ if (dsign) { y = x; fy = fx; dy = dx; } /* Cases b and c */ x = t; fx = ft; dx = dt; } /* Clip the new trial value in [tmin, tmax]. */ if (tmax < newt) newt = tmax; if (newt < tmin) newt = tmin; /* Redefine the new trial value if it is close to the upper bound of the interval. */ if (brackt != 0 && bound != 0) { mq = x + 0.66 * (y - x); if (x < y) { if (mq < newt) newt = mq; } else { if (newt < mq) newt = mq; } } /* Return the new trial value. */ t = newt; uv.x = x; uv.fx = fx; uv.dx = dx; uv.y = y; uv.fy = fy; uv.dy = dy; uv.t = t; uv.ft = ft; uv.dt = dt; //uv.tmin = tmin; //uv.tmax = tmax; uv.brackt = brackt; return LBFGS_CONTINUE; }
int *brackt
@Override public void show() { boolean fireOpen = !isShowing(); super.show(); // adjust the size of the glass if (isShowing()) { adjustGlassSize(); } // fire the open event if (fireOpen) { OpenEvent.fire(this, this); } }
Overrides show to call {@link #adjustGlassSize()} if the dialog is already showing and fires an {@link OpenEvent} after the normal show.
public void adjustGlassSize() { if (isGlassEnabled()) { ResizeHandler handler = getGlassResizer(); if (handler != null) handler.onResize(null); } }
This can be called to adjust the size of the dialog glass. It is implemented using JSNI to bypass the "private" keyword on the glassResizer.
public static Bounds getSymmetricBounds(int dim, double l, double u) { double [] L = new double[dim]; double [] U = new double[dim]; for(int i=0; i<dim; i++) { L[i] = l; U[i] = u; } return new Bounds(L, U); }
Gets bounds which are identical for all dimensions. @param dim The number of dimensions. @param l The value of all lower bounds. @param u The value of all upper bounds. @return The new bounds.
public double transformFromUnitInterval(int i, double d){ return (B[i]-A[i])*(d-1.0)+B[i]; }
Maps d \in [0,1] to transformed(d), such that transformed(d) \in [A[i], B[i]]. The transform is just a linear one. It does *NOT* check for +/- infinity.
public double transformRangeLinearly(double l, double u, int i, double d){ return (B[i]-A[i])/(u-l)*(d-u)+B[i]; }
Maps d \in [l,u] to transformed(d), such that transformed(d) \in [A[i], B[i]]. The transform is just a linear one. It does *NOT* check for +/- infinity.
public static Optional<Tag> parse(final String httpTag) { Tag result = null; boolean weak = false; String internal = httpTag; if (internal.startsWith("W/")) { weak = true; internal = internal.substring(2); } if (internal.startsWith("\"") && internal.endsWith("\"")) { result = new Tag( internal.substring(1, internal.length() - 1), weak); } else if (internal.equals("*")) { result = new Tag("*", weak); } return Optional.ofNullable(result); }
Parses a tag formatted as defined by the HTTP standard. @param httpTag The HTTP tag string; if it starts with 'W/' the tag will be marked as weak and the data following the 'W/' used as the tag; otherwise it should be surrounded with quotes (e.g., "sometag"). @return A new tag instance. @see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11">HTTP Entity Tags</a>
public String format() { if (getName().equals("*")) { return "*"; } else { StringBuilder sb = new StringBuilder(); if (isWeak()) { sb.append("W/"); } return sb.append('"').append(getName()).append('"').toString(); } }
Returns tag formatted as an HTTP tag string. @return The formatted HTTP tag string. @see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11">HTTP Entity Tags</a>
public static final Long getValueForNextHour() { Date date = new Date(); long value = UTCDateBox.date2utc(date); // remove anything after an hour and add an hour long hour = 60 * 60 * 1000; value = value % UTCDateBox.DAY_IN_MS; return value - (value % hour) + hour; }
utils
private String parseOuterClassName() { StringBuilder sb = new StringBuilder(); sb.append(lexer.nextToken(TokenType.JAVA_ID).text); Token token = lexer.peekToken(0); boolean isFullyQualifiedName = false; while (token.tokenType == TokenType.PACKAGE_SEPARATOR) { isFullyQualifiedName = true; token = lexer.nextToken(); sb.append('.'); token = lexer.nextToken(TokenType.JAVA_ID); sb.append(token.text); token = lexer.peekToken(0); } if (!isFullyQualifiedName) { return getFullyQualifiedName(sb.toString()); } else { return sb.toString(); } }
parse the outer class name @return
private String parseJavaId() { StringBuilder sb = new StringBuilder(); int ch; while (true) { ch = characterBuffer.peekChar(); if (ch == CharacterBuffer.EOS || !isJavaIdentifierPart(ch)) { if (sb.length() == 0) { return null; } return sb.toString(); } sb.append((char) ch); characterBuffer.nextChar(); } }
parse a java id @return
public static PropertyResourceBundle getBundle(String baseName, Locale locale) throws UnsupportedEncodingException, IOException{ InputStream is = UTF8PropertyResourceBundle.class.getResourceAsStream("/"+baseName + "_"+locale.toString()+PROPERTIES_EXT); if(is != null){ return new PropertyResourceBundle(new InputStreamReader(is, "UTF-8")); } return null; }
Get a PropertyResourceBundle able to read an UTF-8 properties file. @param baseName @param locale @return new ResourceBundle or null if no bundle can be found. @throws UnsupportedEncodingException @throws IOException
public static Locale getLocaleFromString(String localeString) { if (localeString == null) { return null; } localeString = localeString.trim(); if (localeString.toLowerCase().equals("default")) { return Locale.getDefault(); } // Extract language int languageIndex = localeString.indexOf('_'); String language = null; if (languageIndex == -1) { // No further "_" so is "{language}" only return new Locale(localeString, ""); } else { language = localeString.substring(0, languageIndex); } // Extract country int countryIndex = localeString.indexOf('_', languageIndex + 1); String country = null; if (countryIndex == -1) { // No further "_" so is "{language}_{country}" country = localeString.substring(languageIndex + 1); return new Locale(language, country); } else { // Assume all remaining is the variant so is "{language}_{country}_{variant}" country = localeString.substring(languageIndex + 1, countryIndex); String variant = localeString.substring(countryIndex + 1); return new Locale(language, country, variant); } }
Convert a string based locale into a Locale Object. Assumes the string has form "{language}_{country}_{variant}". Examples: "en", "de_DE", "_GB", "en_US_WIN", "de__POSIX", "fr_MAC" @param localeString The String @return the Locale
@Override public boolean minimize(DifferentiableBatchFunction function, IntDoubleVector point) { return minimize(function, point, null); }
Minimize the function starting at the given initial point.
@SuppressWarnings("unchecked") public <T> T convertElement(ConversionContext context, Object source, TypeReference<T> destinationType) throws ConverterException { return (T) elementConverter.convert(context, source, destinationType); }
Convert element to another object given a parameterized type signature @param context @param destinationType the destination type @param source the source object @return the converted object @throws ConverterException if conversion failed
boolean isCacheableResponse(HTTPResponse response) { if (!cacheableStatuses.contains(response.getStatus())) { return false; } Headers headers = response.getHeaders(); return headers.isCachable(); }
A response received with a status code of 200, 203, 206, 300, 301 or 410 MAY be stored by a cache and used in reply to a subsequent request, subject to the expiration mechanism, unless a cache-control directive prohibits caching. However, a cache that does not support the Range and Content-Range headers MUST NOT cache 206 (Partial Content) responses. We do not support 206 (Partial Content). See: http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.4 @param response the response to analyze @return {@code true} if the response is cacheable. {@code false} if not.
public Conditionals addIfMatch(Tag tag) { Preconditions.checkArgument(!modifiedSince.isPresent(), String.format(ERROR_MESSAGE, HeaderConstants.IF_MATCH, HeaderConstants.IF_MODIFIED_SINCE)); Preconditions.checkArgument(noneMatch.isEmpty(), String.format(ERROR_MESSAGE, HeaderConstants.IF_MATCH, HeaderConstants.IF_NONE_MATCH)); List<Tag> match = new ArrayList<>(this.match); if (tag == null) { tag = Tag.ALL; } if (Tag.ALL.equals(tag)) { match.clear(); } if (!match.contains(Tag.ALL)) { if (!match.contains(tag)) { match.add(tag); } } else { throw new IllegalArgumentException("Tag ALL already in the list"); } return new Conditionals(Collections.unmodifiableList(match), empty(), Optional.empty(), unModifiedSince); }
Adds tags to the If-Match header. @param tag the tag to add, may be null. This means the same as adding {@link Tag#ALL} @throws IllegalArgumentException if ALL is supplied more than once, or you add a null tag more than once. @return a new Conditionals object with the If-Match tag added.
public Conditionals ifModifiedSince(LocalDateTime time) { Preconditions.checkArgument(match.isEmpty(), String.format(ERROR_MESSAGE, HeaderConstants.IF_MODIFIED_SINCE, HeaderConstants.IF_MATCH)); Preconditions.checkArgument(!unModifiedSince.isPresent(), String.format(ERROR_MESSAGE, HeaderConstants.IF_MODIFIED_SINCE, HeaderConstants.IF_UNMODIFIED_SINCE)); time = time.withNano(0); return new Conditionals(empty(), noneMatch, Optional.of(time), Optional.empty()); }
You should use the server's time here. Otherwise you might get unexpected results. The typical use case is: <pre> HTTPResponse response = .... HTTPRequest request = createRequest(); request = request.conditionals(new Conditionals().ifModifiedSince(response.getLastModified()); </pre> @param time the time to check. @return the conditionals with the If-Modified-Since date set.
public Conditionals ifUnModifiedSince(LocalDateTime time) { Preconditions.checkArgument(noneMatch.isEmpty(), String.format(ERROR_MESSAGE, HeaderConstants.IF_UNMODIFIED_SINCE, HeaderConstants.IF_NONE_MATCH)); Preconditions.checkArgument(!modifiedSince.isPresent(), String.format(ERROR_MESSAGE, HeaderConstants.IF_UNMODIFIED_SINCE, HeaderConstants.IF_MODIFIED_SINCE)); time = time.withNano(0); return new Conditionals(match, empty(), Optional.empty(), Optional.of(time)); }
You should use the server's time here. Otherwise you might get unexpected results. The typical use case is: <pre> HTTPResponse response = .... HTTPRequest request = createRequest(); request = request.conditionals(new Conditionals().ifUnModifiedSince(response.getLastModified()); </pre> @param time the time to check. @return the conditionals with the If-Unmodified-Since date set.
public Headers toHeaders() { Headers headers = new Headers(); if (!getMatch().isEmpty()) { headers = headers.add(new Header(HeaderConstants.IF_MATCH, buildTagHeaderValue(getMatch()))); } if (!getNoneMatch().isEmpty()) { headers = headers.add(new Header(HeaderConstants.IF_NONE_MATCH, buildTagHeaderValue(getNoneMatch()))); } if (modifiedSince.isPresent()) { headers = headers.set(HeaderUtils.toHttpDate(HeaderConstants.IF_MODIFIED_SINCE, modifiedSince.get())); } if (unModifiedSince.isPresent()) { headers = headers.set(HeaderUtils.toHttpDate(HeaderConstants.IF_UNMODIFIED_SINCE, unModifiedSince.get())); } return headers; }
Converts the Conditionals into real headers. @return real headers.
public Collection<QName> getPortComponentQNames() { //TODO:Check if there is just one QName that drives all portcomponents //or each port component can have a distinct QName (namespace/prefix) //Maintain uniqueness of the QName Map<String, QName> map = new HashMap<String, QName>(); for (PortComponentMetaData pcm : portComponents) { QName qname = pcm.getWsdlPort(); map.put(qname.getPrefix(), qname); } return map.values(); }
Get the QNames of the port components to be declared in the namespaces @return collection of QNames
public PortComponentMetaData getPortComponentByWsdlPort(String name) { ArrayList<String> pcNames = new ArrayList<String>(); for (PortComponentMetaData pc : portComponents) { String wsdlPortName = pc.getWsdlPort().getLocalPart(); if (wsdlPortName.equals(name)) return pc; pcNames.add(wsdlPortName); } Loggers.METADATA_LOGGER.cannotGetPortComponentName(name, pcNames); return null; }
Lookup a PortComponentMetaData by wsdl-port local part @param name - the wsdl-port local part @return PortComponentMetaData if found, null otherwise
public String serialize() { StringBuilder buffer = new StringBuilder("<webservice-description>"); buffer.append("<webservice-description-name>").append(webserviceDescriptionName).append("</webservice-description-name>"); buffer.append("<wsdl-file>").append(wsdlFile).append("</wsdl-file>"); buffer.append("<jaxrpc-mapping-file>").append(jaxrpcMappingFile).append("</jaxrpc-mapping-file>"); for (PortComponentMetaData pm : portComponents) buffer.append(pm.serialize()); buffer.append("</webservice-description>"); return buffer.toString(); }
Serialize as a String @return string
public static final int getW(Element e) { int ret = e.getOffsetWidth(); ret -= MiscUtils.getComputedStyleInt(e, "paddingLeft"); ret -= MiscUtils.getComputedStyleInt(e, "paddingRight"); ret -= MiscUtils.getComputedStyleInt(e, "borderLeftWidth"); ret -= MiscUtils.getComputedStyleInt(e, "borderRightWidth"); return Math.max(ret, 0); }
Updated to factor in border and padding
public static final int getH(Element e) { int ret = e.getOffsetHeight(); ret -= MiscUtils.getComputedStyleInt(e, "paddingTop"); ret -= MiscUtils.getComputedStyleInt(e, "paddingBottom"); ret -= MiscUtils.getComputedStyleInt(e, "borderTopWidth"); ret -= MiscUtils.getComputedStyleInt(e, "borderBottomWidth"); return Math.max(ret, 0); }
Updated to factor in border and padding
public static final void setBounds(UIObject o, Rect bounds) { setPosition(o, bounds); setSize(o, bounds); }
Sets the bounds of a UIObject, moving and sizing to match the bounds specified. Currently used for the itemhover and useful for other absolutely positioned elements.
public static final void setPosition(UIObject o, Rect pos) { Style style = o.getElement().getStyle(); style.setPropertyPx("left", pos.x); style.setPropertyPx("top", pos.y); }
Sets the position of a UIObject
public static final void setSize(UIObject o, Rect size) { o.setPixelSize(size.w, size.h); }
Sets the size of a UIObject
public static final boolean isInside(int x, int y, Rect box) { return (box.x < x && x < box.x + box.w && box.y < y && y < box.y + box.h); }
Determines if a point is inside a box.
public static final boolean isMouseInside(NativeEvent event, Element element) { return isInside(event.getClientX() + Window.getScrollLeft(), event.getClientY() + Window.getScrollTop(), getBounds(element)); }
Determines if a mouse event is inside a box.
public static final Rect getViewportBounds() { return new Rect(Window.getScrollLeft(), Window.getScrollTop(), Window.getClientWidth(), Window.getClientHeight()); }
This takes into account scrolling and will be in absolute coordinates where the top left corner of the page is 0,0 but the viewport may be scrolled to something else.
public static final Date utc2date(Long time) { // don't accept negative values if (time == null || time < 0) return null; // add the timezone offset time += timezoneOffsetMillis(new Date(time)); return new Date(time); }
Converts a time in UTC to a gwt Date object which is in the timezone of the current browser. @return The Date corresponding to the time, adjusted for the timezone of the current browser. null if the specified time is null or represents a negative number.
public static final Long date2utc(Date date) { // use null for a null date if (date == null) return null; long time = date.getTime(); // remove the timezone offset time -= timezoneOffsetMillis(date); return time; }
Converts a gwt Date in the timezone of the current browser to a time in UTC. @return A Long corresponding to the number of milliseconds since January 1, 1970, 00:00:00 GMT or null if the specified Date is null.
public static final Long getTimeBoxValue(TimeZone zone, Date date) { if (date == null) return null; // use a Calendar in the specified timezone to figure out the // time which is edited in a format independent of TimeZone. Calendar cal = GregorianCalendar.getInstance(zone); cal.setTime(date); // hh:mm (seconds and milliseconds are generally zero but we // include them as well) int hours = cal.get(Calendar.HOUR_OF_DAY); int minutes = cal.get(Calendar.MINUTE); int seconds = cal.get(Calendar.SECOND); int millis = cal.get(Calendar.MILLISECOND); return (((((hours * 60L) + minutes) * 60L) + seconds) * 1000L) + millis; }
Returns an appropriate value for the UTCTimeBox for a specified {@link TimeZone} and {@link Date}. @param zone The {@link TimeZone} in which the Date will be rendered. @param date The Date which should be displayed in the UTCTimeBox @return the value for the UTCTimeBox or null if the supplied date is null
public static final Long getDateBoxValue(TimeZone zone, Date date) { if (date == null) return null; // use a Calendar in the specified timezone to figure out the // date and then convert to GMT Calendar cal = GregorianCalendar.getInstance(zone); cal.setTime(date); Calendar gmt = GregorianCalendar.getInstance(TimeZone.getTimeZone("GMT")); // copy the year, month, and day gmt.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH)); // zero everything else out (for midnight) gmt.set(Calendar.HOUR_OF_DAY, 0); gmt.set(Calendar.MINUTE, 0); gmt.set(Calendar.SECOND, 0); gmt.set(Calendar.MILLISECOND, 0); // midnight at GMT on the date specified return gmt.getTimeInMillis(); }
Returns the value for the UTCDateBox for a specified {@link TimeZone} and {@link Date}. @param zone The {@link TimeZone} in which the Date will be rendered. @param date The Date which should be displayed in the UTCTimeBox @return the value for the UTCDateBox or null if the supplied date is null
public static final Date getDateValue(TimeZone zone, Long dateBoxValue, Long timeBoxValue) { if (dateBoxValue == null) return null; Calendar gmt = GregorianCalendar.getInstance(TimeZone.getTimeZone("GMT")); gmt.setTimeInMillis(dateBoxValue.longValue()); Calendar cal = GregorianCalendar.getInstance(zone); cal.set(gmt.get(Calendar.YEAR), gmt.get(Calendar.MONTH), gmt.get(Calendar.DAY_OF_MONTH)); int hours, minutes, extraMillis; if (timeBoxValue != null) { // figure out how many hours and minutes to add to // midnight in the specified time zone. long localTimeInDay = timeBoxValue.longValue(); // figure out if there are extra millis in the value // (there shoudn't be since the time box control doesn't // typically render millis) extraMillis = (int) (localTimeInDay % (60 * 1000)); // trim off the seconds localTimeInDay -= extraMillis; minutes = (int) ((localTimeInDay / 60 / 1000) % 60); // trim off the minutes localTimeInDay -= minutes; hours = (int) (localTimeInDay / 60 / 60 / 1000); } else { // midnight hours = 0; minutes = 0; extraMillis = 0; } cal.set(Calendar.HOUR_OF_DAY, hours); cal.set(Calendar.MINUTE, minutes); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return new Date(cal.getTimeInMillis() + extraMillis); }
Returns the {@link Date} for the values of the UTCDateBox and UTCTimeBox which were edited in the specified {@link TimeZone}. @param zone The {@link TimeZone} in which the Date was edited. @param dateBoxValue The value of the {@link UTCDateBox} control. @param timeBoxValue The value of the {@link UTCTimeBox} control. @return The {@link Date} that has been selected from the controls or null if the supplied dateBoxValue is null. If the timeBoxValue is null, midnight is returned.
public final void moveInside(Rect bounds) { // check the right edge int distanceOffRightSide = (x + w) - (bounds.x + bounds.w); if (distanceOffRightSide > 0) { x -= distanceOffRightSide; } // check the left edge (we prefer this to fit) int distanceOffLeftSide = bounds.x - x; if (distanceOffLeftSide > 0) { x += distanceOffLeftSide; } // check the bottom edge int distanceOffBottom = (y + h) - (bounds.y + bounds.h); if (distanceOffBottom > 0) { y -= distanceOffBottom; } // check the top edge (we prefer this to fit) int distanceOffTop = bounds.y - y; if (distanceOffTop > 0) { y += distanceOffTop; } }
Note, this actually changes this Rect (if that wasn't obvious)
public static FullTypeSignature getTypeSignature(String typeSignatureString, boolean useInternalFormFullyQualifiedName) { String key; if (!useInternalFormFullyQualifiedName) { key = typeSignatureString.replace('.', '/') .replace('$', '.'); } else { key = typeSignatureString; } // we always use the internal form as a key for cache FullTypeSignature typeSignature = typeSignatureCache .get(key); if (typeSignature == null) { ClassFileTypeSignatureParser typeSignatureParser = new ClassFileTypeSignatureParser( typeSignatureString); typeSignatureParser.setUseInternalFormFullyQualifiedName(useInternalFormFullyQualifiedName); typeSignature = typeSignatureParser.parseTypeSignature(); typeSignatureCache.put(typeSignatureString, typeSignature); } return typeSignature; }
get TypeSignature given the signature @param typeSignature @param useInternalFormFullyQualifiedName if true, fqn in parameterizedTypeSignature must be in the form 'java/lang/Thread'. If false fqn must be of the form 'java.lang.Thread' @return
public static FullTypeSignature getTypeSignature(Class<?> clazz, Class<?>[] typeArgs) { ClassTypeSignature rawClassTypeSignature = (ClassTypeSignature) javaTypeToTypeSignature .getTypeSignature(clazz); TypeArgSignature[] typeArgSignatures = new TypeArgSignature[typeArgs.length]; for (int i = 0; i < typeArgs.length; i++) { typeArgSignatures[i] = new TypeArgSignature( TypeArgSignature.NO_WILDCARD, (FieldTypeSignature) javaTypeToTypeSignature .getTypeSignature(typeArgs[i])); } ClassTypeSignature classTypeSignature = new ClassTypeSignature( rawClassTypeSignature.getBinaryName(), typeArgSignatures, rawClassTypeSignature.getOwnerTypeSignature()); return classTypeSignature; }
get the TypeSignature corresponding to given class with given type arguments @param clazz @param typeArgs @return
public static OptionalString ofNullable(ResourceKey key, String value) { return new GenericOptionalString(RUNTIME_SOURCE, key, value); }
Returns new instance of OptionalString with given key and value @param key key of the returned OptionalString @param value wrapped string @return given object wrapped in OptionalString with given key
public void set(final T value) { if (this.value.compareAndSet(null, value)) { this.listeners.clear(); this.cdl.countDown(); } }
All callers to get() are now returned.<br> Multiple calls are ignored.<br> Calls after cancel are ignored. @param value Value
public void set(final Exception e) { if (this.value.compareAndSet(null, e)) { this.listeners.clear(); this.cdl.countDown(); } }
The get() method throws this exception wrapped as the cause of an ExecutionException.<br> Multiple calls are ignored.<br> Calls after cancel are ignored. @param e Exception
public void addCancelListener(final CancelListener<T> listener) { final Object v = this.value.get(); if (v == null) { this.listeners.add(listener); } else if (FutureImpl.CANCELLED_FLAG.equals(v)) { listener.wasCancelled(this.getId()); } }
IMPORTANT: In the event that the Cancel listener is added after cancel() was called the event is immediately fired.<br> IMPORTANT2: Keep in mind, that the Cancel listener may not be called from your own thread, so you must care about thread-safety! @param listener Cancel listener
public static @NotNull String urlEncode(@Nullable String value) { if (value == null) { return ""; } try { return URLEncoder.encode(value, CharEncoding.UTF_8); } catch (UnsupportedEncodingException ex) { throw new RuntimeException(ex); } }
Applies URL-Encoding to the given parameter name or value. Uses {@link URLEncoder#encode(String, String)} with UTF-8 character set, while avoiding the need to catch the UnsupportedEncodingException. @param value the parameter name or value to encode @return URL-encoded string - or empty string if the specified value was null @throws RuntimeException in the very unlikely case that UTF-8 is not supported on the current system
public static @NotNull String validName(@NotNull String value) { // convert to lowercase String text = value.toLowerCase(); // replace some special chars first text = StringUtils.replace(text, "ä", "ae"); text = StringUtils.replace(text, "ö", "oe"); text = StringUtils.replace(text, "ü", "ue"); text = StringUtils.replace(text, "ß", "ss"); // replace all invalid chars StringBuilder sb = new StringBuilder(text); for (int i = 0; i < sb.length(); i++) { char ch = sb.charAt(i); if (!((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') || (ch == '_'))) { ch = '-'; sb.setCharAt(i, ch); } } return sb.toString(); }
Creates a valid node name. Replaces all chars not in a-z, A-Z and 0-9 or '_' with '-' and converts all to lowercase. @param value String to be labelized. @return The labelized string.
public static @NotNull String validFilename(@NotNull String value) { String fileExtension = StringUtils.substringAfterLast(value, "."); String fileName = StringUtils.substringBeforeLast(value, "."); if (StringUtils.isEmpty(fileExtension)) { return validName(fileName); } return validName(fileName) + "." + validName(fileExtension); }
Create valid filename by applying method {@link Escape#validName(String)} on filename and extension. @param value Filename @return Valid filename
@SuppressWarnings({ "unused", "null" }) public static @NotNull String jcrQueryLiteral(@NotNull String value) { if (value == null) { throw new IllegalArgumentException("Invalid query string value: " + value); } return "'" + StringUtils.replace(value, "'", "''") + "'"; }
Convert a string to a literal, suitable for inclusion in a query (XPath or JCR-SQL2). See JSR-283 specification v2.0, Section 4.6.6.19. @param value Any string. @return A valid JCR query string literal, including enclosing quotes.
@SuppressWarnings("null") public static @NotNull String jcrQueryContainsExpr(@NotNull String value) { if (value == null || value.isEmpty()) { throw new IllegalArgumentException("Invalid query string value: " + value); } // Escape special characters not allowed in jcr:contains expression return jcrQueryLiteral(Text.escapeIllegalXpathSearchChars(value)); }
Convert a string to a JCR search expression literal, suitable for use in jcr:contains() (inside XPath) or contains (JCR-SQL2). The characters - and " have special meaning, and may be escaped with a backslash to obtain their literal value. See JSR-283 specification v2.0, Section 4.6.6.19. @param value Any string. @return A valid string literal suitable for use in JCR contains clauses, including enclosing quotes.
public Archetype parse(String adl) { try { return parse(new StringReader(adl)); } catch (IOException e) { // StringReader should never throw an IOException throw new AssertionError(e); } }
Parses an adl source into a differential archetype. @param adl contents of an adl source file @return parsed archetype @throws org.openehr.adl.parser.AdlParserException if an error occurred while parsing
public static boolean isAnnotationPresent(final Class<? extends Annotation> annotation, final Method method) { final Annotation e = DaemonScanner.getAnnotation(annotation, method); return e != null; }
Checks also the inheritance hierarchy. @param annotation Annotation @param method Method @return Is present?
public static <A extends Annotation> A getAnnotation(final Class<A> annotation, final Method method) { try { return DaemonScanner.isAnnotationPresent(annotation, method.getDeclaringClass(), method.getName(), method.getParameterTypes()); } catch(final NoSuchMethodException e) { return null; } }
Checks also the inheritance hierarchy. @param annotation Annotation @param method Method @param <A> Annotation @return Annotation or null
@SuppressWarnings({"unchecked", "unused"}) public static <T> T[] object2Array(final Class<T> clazz, final Object obj) { return (T[]) obj; }
We try to convert an Object to an Array and this is not easy in Java so we need a little bit of nasty magic. @param <T> Type of elements @param clazz Clazz of the Objct elements @param obj Object @return Array
public void pauseUpload() throws LocalOperationException { if (state == State.UPLOADING) { setState(State.PAUSED); executor.hardStop(); } else { throw new LocalOperationException("Attempt to pause upload while assembly is not uploading"); } }
Pauses the file upload. This is a blocking function that would try to wait till the assembly file uploads have actually been paused if possible. @throws LocalOperationException if the method is called while no upload is going on.
protected AssemblyResponse watchStatus() throws LocalOperationException, RequestException { AssemblyResponse response; do { response = getClient().getAssemblyByUrl(url); try { Thread.sleep(1000); } catch (InterruptedException e) { throw new LocalOperationException(e); } } while (!response.isFinished()); setState(State.FINISHED); return response; }
Runs intermediate check on the Assembly status until it is finished executing, then returns it as a response. @return {@link AssemblyResponse} @throws LocalOperationException if something goes wrong while running non-http operations. @throws RequestException if request to Transloadit server fails.
@Override protected void uploadTusFiles() throws IOException, ProtocolException { setState(State.UPLOADING); while (uploads.size() > 0) { final TusUploader tusUploader; // don't recreate uploader if it already exists. // this is to avoid multiple connections being open. And to avoid some connections left unclosed. if (lastTusUploader != null) { tusUploader = lastTusUploader; lastTusUploader = null; } else { tusUploader = tusClient.resumeOrCreateUpload(uploads.get(0)); if (getUploadChunkSize() > 0) { tusUploader.setChunkSize(getUploadChunkSize()); } } TusExecutor tusExecutor = new TusExecutor() { @Override protected void makeAttempt() throws ProtocolException, IOException { while (state == State.UPLOADING) { int chunkUploaded = tusUploader.uploadChunk(); if (chunkUploaded > 0) { uploadedBytes += chunkUploaded; listener.onUploadPogress(uploadedBytes, totalUploadSize); } else { // upload is complete break; } } } }; tusExecutor.makeAttempts(); if (state != State.UPLOADING) { // if upload is paused, save the uploader so it can be reused on resume, then leave the method early. lastTusUploader = tusUploader; return; } // remove upload instance from list uploads.remove(0); tusUploader.finish(); } setState(State.UPLOAD_COMPLETE); }
Does the actual uploading of files (when tus is enabled) @throws IOException when there's a failure with file retrieval @throws ProtocolException when there's a failure with tus upload
@Override protected void handleTusUpload(AssemblyResponse response) throws IOException, ProtocolException { url = response.getSslUrl(); totalUploadSize = getTotalUploadSize(); processTusFiles(url); startExecutor(); }
If tus uploads are enabled, this method would be called by {@link Assembly#save()} to handle the file uploads @param response {@link AssemblyResponse} @throws IOException when there's a failure with file retrieval. @throws ProtocolException when there's a failure with tus upload.
private long getTotalUploadSize() throws IOException { long size = 0; for (Map.Entry<String, File> entry : files.entrySet()) { size += entry.getValue().length(); } for (Map.Entry<String, InputStream> entry : fileStreams.entrySet()) { size += entry.getValue().available(); } return size; }
used for upload progress
public static <T extends InterconnectObject> T fromJson(String data, Class<T> clazz) throws IOException { return InterconnectMapper.mapper.readValue(data, clazz); }
Creates an object from the given JSON data. @param data the JSON data @param clazz the class object for the content of the JSON data @param <T> the type of the class object extending {@link InterconnectObject} @return the object contained in the given JSON data @throws JsonParseException if a the JSON data could not be parsed @throws JsonMappingException if the mapping of the JSON data to the IVO failed @throws IOException if an I/O related problem occurred
public static <T extends InterconnectObject> T cloneObject(T object) throws IOException { return InterconnectMapper.fromJson(InterconnectMapper.toJson(object), (Class<T>) object.getClass()); }
Returns a clone of the given object using JSON (de)serialization. @param object the object to be cloned @return a clone of this object. @throws JsonGenerationException if the JSON data could not be generated @throws JsonMappingException if the object could not be mapped to a JSON string @throws IOException if an I/O related problem occurred
@Override public MessageResponse deserialize(JsonElement element, Type alsoIgnored, JsonDeserializationContext ignored) { List<String> results = new ArrayList<String>(); String reason = ""; String details = ""; JsonObject body = element.getAsJsonObject(); boolean succeeded = body.get("outcome").getAsString().equals("SUCCESS"); if (succeeded) { if (body.get("results") != null) { for (JsonElement result : body.get("results").getAsJsonArray()) { if(result.isJsonNull()) results.add(null); else if(result.isJsonObject()) results.add(result.toString()); else results.add(result.getAsString()); } } } else { reason = body.get("reason").getAsString(); details = body.get("details").getAsString(); } return new MessageResponse(succeeded, results, reason, details); }
Create a {@code MessageResponse} object from a serialized JSON representation.
public static String stringFor(int n) { switch (n) { case CUDNN_CONVOLUTION_BWD_FILTER_ALGO_0: return "CUDNN_CONVOLUTION_BWD_FILTER_ALGO_0"; case CUDNN_CONVOLUTION_BWD_FILTER_ALGO_1: return "CUDNN_CONVOLUTION_BWD_FILTER_ALGO_1"; case CUDNN_CONVOLUTION_BWD_FILTER_ALGO_FFT: return "CUDNN_CONVOLUTION_BWD_FILTER_ALGO_FFT"; case CUDNN_CONVOLUTION_BWD_FILTER_ALGO_3: return "CUDNN_CONVOLUTION_BWD_FILTER_ALGO_3"; case CUDNN_CONVOLUTION_BWD_FILTER_ALGO_WINOGRAD: return "CUDNN_CONVOLUTION_BWD_FILTER_ALGO_WINOGRAD"; case CUDNN_CONVOLUTION_BWD_FILTER_ALGO_WINOGRAD_NONFUSED: return "CUDNN_CONVOLUTION_BWD_FILTER_ALGO_WINOGRAD_NONFUSED"; case CUDNN_CONVOLUTION_BWD_FILTER_ALGO_FFT_TILING: return "CUDNN_CONVOLUTION_BWD_FILTER_ALGO_FFT_TILING"; case CUDNN_CONVOLUTION_BWD_FILTER_ALGO_COUNT: return "CUDNN_CONVOLUTION_BWD_FILTER_ALGO_COUNT"; } return "INVALID cudnnConvolutionBwdFilterAlgo: "+n; }
Returns a string representation of the given constant @return A string representation of the given constant
public Response save() throws RequestException, LocalOperationException { Map<String, Object> templateData = new HashMap<String, Object>(); templateData.put("name", name); options.put("steps", steps.toMap()); templateData.put("template", options); Request request = new Request(transloadit); return new Response(request.post("/templates", templateData)); }
Submits the configured template to Transloadit. @return {@link Response} @throws RequestException if request to transloadit server fails. @throws LocalOperationException if something goes wrong while running non-http operations.
public void setMappings(Map<String,ResourceObjectProvider> mappings) { this.mappings = new ArrayList<>(mappings.size()); for (Map.Entry<String, ResourceObjectProvider> entry : mappings.entrySet()) { this.mappings.add(new Mapping(compile(entry.getKey()), entry.getValue())); } }
Specify list of pattern to resource object provider mappings. Note, that if the actual object name matches two or more patterns, first one in the map will be used. You may use {@link LinkedHashMap} to specify exact order. @param mappings a set of pattern-factory pairs stored in {@link Map}
public boolean matches(String resourcePath) { if (!valid) { return false; } if (resourcePath == null) { return acceptsContextPathEmpty; } if (contextPathRegex != null && !contextPathRegex.matcher(resourcePath).matches()) { return false; } if (contextPathBlacklistRegex != null && contextPathBlacklistRegex.matcher(resourcePath).matches()) { return false; } return true; }
Checks if this service implementation accepts the given resource path. @param resourcePath Resource path @return true if the implementation matches and the configuration is not invalid.
private ClassLoaderInterface getClassLoader() { Map<String, Object> application = ActionContext.getContext().getApplication(); if (application != null) { return (ClassLoaderInterface) application.get(ClassLoaderInterface.CLASS_LOADER_INTERFACE); } return null; }
this class loader interface can be used by other plugins to lookup resources from the bundles. A temporary class loader interface is set during other configuration loading as well @return ClassLoaderInterface (BundleClassLoaderInterface)
@SuppressWarnings("unchecked") public @NotNull QueryStringBuilder param(@NotNull String name, @Nullable Object value) { if (value instanceof Iterable) { Iterable<Object> valueItems = (Iterable)value; for (Object valueItem : valueItems) { params.add(new NameValuePair(name, valueItem)); } } else if (isArray(value)) { int length = Array.getLength(value); for (int i = 0; i < length; i++) { Object valueItem = Array.get(value, i); params.add(new NameValuePair(name, valueItem)); } } else { params.add(new NameValuePair(name, value)); } return this; }
Add parameter to query string. @param name Parameter name @param value Parameter value. Will be converted to string. If value is an array or {@link Iterable} the value items will be added as separate parameters. @return this
public @NotNull QueryStringBuilder params(@NotNull Map<String, Object> values) { for (Map.Entry<String, Object> entry : values.entrySet()) { param(entry.getKey(), entry.getValue()); } return this; }
Add map of parameters to query string. @param values Map with parameter names and values. Values will be converted to strings. If a value is an array or {@link Iterable} the value items will be added as separate parameters. @return this