code
stringlengths
67
466k
docstring
stringlengths
1
13.2k
public static RgbaColor fromHsl(String hsl) { String[] parts = getHslParts(hsl).split(","); if (parts.length == 3) { float[] HSL = new float[] { parseInt(parts[0]), parseInt(parts[1]), parseInt(parts[2]) }; return fromHsl(HSL); } else { return getDefaultColor(); } }
Parses an RgbaColor from a CSS3 HSL value, e.g. hsl(25, 100%, 80%) @return the parsed color
public static RgbaColor fromHsla(String hsl) { String[] parts = getHslaParts(hsl).split(","); if (parts.length == 4) { float[] HSL = new float[] { parseInt(parts[0]), parseInt(parts[1]), parseInt(parts[2]) }; RgbaColor ret = fromHsl(HSL); if (ret != null) { ret.a = parseFloat(parts[3]); } return ret; } else { return getDefaultColor(); } }
Parses an RgbaColor from a CSS3 HSLA value, e.g. hsla(25, 100%, 80%, 0.5) @return returns the parsed color
private RgbaColor withHsl(int index, float value) { float[] HSL = convertToHsl(); HSL[index] = value; return RgbaColor.fromHsl(HSL); }
Returns a new color with a new value of the specified HSL component.
public RgbaColor adjustHue(float degrees) { float[] HSL = convertToHsl(); HSL[0] = hueCheck(HSL[0] + degrees); // ensure [0-360) return RgbaColor.fromHsl(HSL); }
Returns a new color that has the hue adjusted by the specified amount.
public RgbaColor opacify(float amount) { return new RgbaColor(r, g, b, alphaCheck(a + amount)); }
Returns a new color that has the alpha adjusted by the specified amount.
public RgbaColor[] getPaletteVaryLightness(int count) { // a max of 80 and an offset of 10 keeps us away from the // edges float[] spread = getSpreadInRange(l(), count, 80, 10); RgbaColor[] ret = new RgbaColor[count]; for (int i = 0; i < count; i++) { ret[i] = withLightness(spread[i]); } return ret; }
palettes
protected static final float[] getSpreadInRange(float member, int count, int max, int offset) { // to find the spread, we first find the min that is a // multiple of max/count away from the member int interval = max / count; float min = (member + offset) % interval; if (min == 0 && member == max) { min += interval; } float[] range = new float[count]; for (int i = 0; i < count; i++) { range[i] = min + interval * i + offset; } return range; }
Returns a spread of integers in a range [0,max) that includes count. The spread is sorted from largest to smallest.
private RgbaColor adjustSL(int index, float first, float second) { float[] HSL = convertToHsl(); float firstvalue = HSL[index] + first; // check if it's in bounds if (slCheck(firstvalue) == firstvalue) { // it is, keep this transform HSL[index] = firstvalue; } else if (second == 0) { // just take the first one because there is no second, but // bounds check it. HSL[index] = slCheck(firstvalue); } else { // always take the second if the first exceeds bounds HSL[index] = slCheck(HSL[index] + second); } return RgbaColor.fromHsl(HSL); }
Takes two adjustments and applies the one that conforms to the range. If the first modification moves the value out of range [0-100], the second modification will be applied <b>and clipped if necessary</b>. @param index The index in HSL @param first The first modification that will be applied and bounds checked @param second If 0, the first is always applied
public float[] convertToHsl() { float H, S, L; // first normalize [0,1] float R = r / 255f; float G = g / 255f; float B = b / 255f; // compute min and max float M = max(R, G, B); float m = min(R, G, B); L = (M + m) / 2f; if (M == m) { // grey H = S = 0; } else { float diff = M - m; S = (L < 0.5) ? diff / (2f * L) : diff / (2f - 2f * L); if (M == R) { H = (G - B) / diff; } else if (M == G) { H = (B - R) / diff + 2f; } else { H = (R - G) / diff + 4f; } H *= 60; } H = hueCheck(H); S = slCheck(S * 100f); L = slCheck(L * 100f); return new float[] { H, S, L }; }
Returns a triple of hue [0-360), saturation [0-100], and lightness [0-100]. These are kept as float[] so that for any RgbaColor color, color.equals(RgbaColor.fromHsl(color.convertToHsl())) is true. <p> <i>Implementation based on <a href="http://en.wikipedia.org/wiki/HSL_and_HSV" >wikipedia</a></i>
public static RgbaColor fromHsl(float H, float S, float L) { // convert to [0-1] H /= 360f; S /= 100f; L /= 100f; float R, G, B; if (S == 0) { // grey R = G = B = L; } else { float m2 = L <= 0.5 ? L * (S + 1f) : L + S - L * S; float m1 = 2f * L - m2; R = hue2rgb(m1, m2, H + 1 / 3f); G = hue2rgb(m1, m2, H); B = hue2rgb(m1, m2, H - 1 / 3f); } // convert [0-1] to [0-255] int r = Math.round(R * 255f); int g = Math.round(G * 255f); int b = Math.round(B * 255f); return new RgbaColor(r, g, b, 1); }
Creates a new RgbaColor from the specified HSL components. <p> <i>Implementation based on <a href="http://en.wikipedia.org/wiki/HSL_and_HSV">wikipedia</a> and <a href="http://www.w3.org/TR/css3-color/#hsl-color">w3c</a></i> @param H Hue [0,360) @param S Saturation [0,100] @param L Lightness [0,100]
private static float hue2rgb(float m1, float m2, float h) { if (h < 0) h += 1; if (h > 1) h -= 1; if (h * 6f < 1) return m1 + (m2 - m1) * 6f * h; if (h * 2f < 1) return m2; if (h * 3f < 2) return m1 + (m2 - m1) * (2 / 3f - h) * 6f; return m1; }
See http://www.w3.org/TR/css3-color/#hsl-color
public String toHex() { String rs = hexpad(Integer.toHexString(r)); String gs = hexpad(Integer.toHexString(g)); String bs = hexpad(Integer.toHexString(b)); return "#" + rs + gs + bs; }
Returns the color in hexadecimal format (#rrggbb)
public String toHsl() { float[] HSL = convertToHsl(); return "hsl(" + Math.round(HSL[0]) + "," + Math.round(HSL[1]) + "%," + Math.round(HSL[2]) + "%)"; }
Returns the CSS3 HSL representation, e.g. hsl(120, 100%, 50%)
public String toHsla() { float[] HSL = convertToHsl(); return "hsl(" + Math.round(HSL[0]) + "," + Math.round(HSL[1]) + "%," + Math.round(HSL[2]) + "%," + a + ")"; }
Returns the CSS3 HSLA representation, e.g. hsl(120, 100%, 50%, 0.5)
private float max(float x, float y, float z) { if (x > y) { // not y if (x > z) { return x; } else { return z; } } else { // not x if (y > z) { return y; } else { return z; } } }
misc utility methods
public Constructor<?> getCompatibleConstructor(Class<?> type, Class<?> argumentType) { try { return type.getConstructor(new Class[] { argumentType }); } catch (Exception e) { // get public classes and interfaces Class<?>[] types = type.getClasses(); for (int i = 0; i < types.length; i++) { try { return type.getConstructor(new Class[] { types[i] }); } catch (Exception e1) { } } } return null; }
Get a compatible constructor @param type Class to look for constructor in @param argumentType Argument type for constructor @return the compatible constructor or null if none found
public <T> T convert(Object source, TypeReference<T> typeReference) throws ConverterException { return (T) convert(new ConversionContext(), source, typeReference); }
Convert an object to another object with given type @param <T> @param source object to convert @param typeReference reference to {@link java.lang.reflect.Type} @return the converted object if conversion failed @throws ConverterException
public <T> T convert(Object source, Class<T> clazz) throws ConverterException { return (T) convert(new ConversionContext(), source, clazz); }
Convert an object to another object with given class @param <T> @param source object to convert @param clazz destination class @return the converted object @throws ConverterException if conversion failed
public <T> T convert(ConversionContext context, Object source, Class<T> clazz) throws ConverterException { return (T) convert(context, source, TypeReference.get(clazz)); }
Convert an object to another object with given class @param <T> @param context @param source object to convert @param clazz destination class @return the converted object @throws ConverterException if conversion failed
public <T> T convert(ConversionContext context, Object source, TypeReference<T> destinationType) throws ConverterException { try { return (T) multiConverter.convert(context, source, destinationType); } catch (ConverterException e) { throw e; } catch (Exception e) { // There is a problem with one converter. This should not happen. // Either there is a bug in this converter or it is not properly // configured throw new ConverterException( MessageFormat .format( "Could not convert given object with class ''{0}'' to object with type signature ''{1}''", source == null ? "null" : source.getClass() .getName(), destinationType), e); } }
Convert an object 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
public static double logSubtractExact(double x, double y) { if (x < y) { throw new IllegalStateException("x must be >= y. x=" + x + " y=" + y); } // p = 0 or q = 0, where x = log(p), y = log(q) if (Double.NEGATIVE_INFINITY == y) { return x; } else if (Double.NEGATIVE_INFINITY == x) { return y; } // p != 0 && q != 0 return x + Math.log1p(-exp(y - x)); }
Subtracts two probabilities that are stored as log probabilities. Note that x >= y. @param x log(p) @param y log(q) @return log(p - q) = log(exp(p) + exp(q)) @throws IllegalStateException if x < y
public static int[] sampleWithoutReplacement(int m, int n) { // This implements a modified form of the genshuf() function from // Programming Pearls pg. 129. // TODO: Design a faster method that only generates min(m, n-m) integers. int[] array = getIndexArray(n); for (int i=0; i<m; i++) { int j = Prng.nextInt(n - i) + i; // Swap array[i] and array[j] int tmp = array[i]; array[i] = array[j]; array[j] = tmp; } return Arrays.copyOf(array, m); }
Samples a set of m integers without replacement from the range [0,...,n-1]. @param m The number of integers to return. @param n The number of integers from which to sample. @return The sample as an unsorted integer array.
public static int compare(double a, double b, double delta) { if (equals(a, b, delta)) { return 0; } return Double.compare(a, b); }
Compares two double values up to some delta. @param a @param b @param delta @return The value 0 if a equals b, a value greater than 0 if if a > b, and a value less than 0 if a < b.
public static long[] getLongIndexArray(int length) { long[] index = new long[length]; for (int i=0; i<index.length; i++) { index[i] = i; } return index; }
Gets an array where array[i] = i. @param length The length of the array. @return The new index array.
public static void fill(final Object[] array, final Object value) { // final int n = array.length; // if (n > 0) { // array[0] = value; // } // for (int i = 1; i < n; i += i) { // System.arraycopy(array, 0, array, i, ((n - i) < i) ? (n - i) : i); // } for (int i=0; i<array.length; i++) { array[i] = value; } }
Faster version of Arrays.fill(). That standard version does NOT use memset, and only iterates over the array filling each value. This method works out to be much faster and seems to be using memset as appropriate.
private TypeArgSignature parseTypeArg() { int ch = peekChar(); switch (ch) { case '*': return new TypeArgSignature( (char) nextChar(TypeArgSignature.UNBOUNDED_WILDCARD), null); case '+': return new TypeArgSignature( (char) nextChar(TypeArgSignature.UPPERBOUND_WILDCARD), parseFieldTypeSignature()); case '-': return new TypeArgSignature( (char) nextChar(TypeArgSignature.LOWERBOUND_WILDCARD), parseFieldTypeSignature()); default: return new TypeArgSignature(TypeArgSignature.NO_WILDCARD, parseFieldTypeSignature()); } }
"* | ( + | - )? FieldTypeSignature" @return
private String parseJavaId() { StringBuilder sb = new StringBuilder(); int ch; while (true) { ch = peekChar(); if (ch == EOS || !isJavaIdentifierPart(ch)) { return sb.toString(); } sb.append((char) ch); nextChar(); } }
parse a java id @return
private String parseOuterClassName() { StringBuilder sb = new StringBuilder(); sb.append(parseJavaId()); while (peekChar() == packageSeparator) { // '/' or '.' nextChar(packageSeparator); sb.append('.'); sb.append(parseJavaId()); } return sb.toString(); }
parse the outer class name @return
public ClassTypeSignature parseClassName() { // read ID (/Id)* String outerClassName = parseOuterClassName(); TypeArgSignature[] typeArgSignatures = new TypeArgSignature[0]; int ch = peekChar(); if (acceptGenerics && ch == '<') { typeArgSignatures = parseTypeArgs(); } ClassTypeSignature classTypeSignature = new ClassTypeSignature( outerClassName, typeArgSignatures, null); ch = peekChar(); if (ch == innerClassPrefix) { // '.' or '$' classTypeSignature = parseInnerClasses(classTypeSignature); } return classTypeSignature; }
parse the class name (outer class and inner class) @return
private boolean isInvalidatingHEADResponse(HTTPRequest request, CacheItem item, HTTPResponse resolvedResponse) { return request.getMethod() == HTTPMethod.HEAD && item != null && resolvedResponse.getStatus() != Status.NOT_MODIFIED; }
http://tools.ietf.org/html/rfc2616#section-9.4
private boolean isSuccessfulResponseToUnsafeRequest(HTTPResponse resolvedResponse) { Status.Category category = resolvedResponse.getStatus().getCategory(); return category == Status.Category.SUCCESS || category == Status.Category.REDIRECTION; }
http://tools.ietf.org/html/draft-ietf-httpbis-p6-cache-22#section-6
public double getValue(int[] batch) { double value = 0.0; for (int i=0; i<batch.length; i++) { value += getValue(i); } return value; }
Gets value of this function at the current point, computed on the given batch of examples. @param batch A set of indices indicating the examples over which the gradient should be computed. @return The value of the function at the point.
public void getGradient(int[] batch, double[] gradient) { for (int i=0; i<batch.length; i++) { addGradient(i, gradient); } }
Gets the gradient at the current point, computed on the given batch of examples. @param batch A set of indices indicating the examples over which the gradient should be computed. @param gradient The output gradient, a vector of partial derivatives.
@Override public double getValue(IntDoubleVector params) { double sum = params.dot(params); sum *= 1./2. * lambda; return - sum; }
Gets the negated sum of squares times 1/2 \lambda.
@Override public IntDoubleVector getGradient(IntDoubleVector params) { IntDoubleDenseVector gradient = new IntDoubleDenseVector(numParams); for (int j=0; j<numParams; j++) { gradient.set(j, - params.get(j) * lambda); } return gradient; }
TODO: Why do Sutton & McCallum include the sum of the parameters here and not just the value for each term of the gradient.
public <A> Optional<A> transform(final ThrowableFunction<Payload, A, IOException> f) { if (hasPayload()) { return payload.flatMap(p -> lift(p, f)); } return Optional.empty(); }
TODO: consider removing this
public synchronized static SQLiteDatabase getConnection(Context context) { if (database == null) { // Construct the single helper and open the unique(!) db connection for the app database = new CupboardDbHelper(context.getApplicationContext()).getWritableDatabase(); } return database; }
Returns a raw handle to the SQLite database connection. Do not close! @param context A context, which is used to (when needed) set up a connection to the database @return The single, unique connection to the database, as is (also) used by our Cupboard instance
public static <T> TypeReference<T> get(Class<T> type) { return new SimpleTypeReference<T>(type); }
Gets type token for the given {@code Class} instance.
public boolean isNumber() { if (type == Byte.TYPE || type == Short.TYPE || type == Integer.TYPE || type == Long.TYPE || type == Float.TYPE || type == Double.TYPE) { return true; } else { return isRawTypeSubOf(Number.class); } }
check if type is a number type (either primitive or instance of Number) @param type @return @throws ClassNotFoundException
@SuppressWarnings("unchecked") public static Type getSuperclassTypeParameter(Class<?> subclass) { Type superclass = subclass.getGenericSuperclass(); if (superclass instanceof Class) { throw new RuntimeException("Missing type parameter."); } return ((ParameterizedType) superclass).getActualTypeArguments()[0]; }
Gets type from super class's type parameter.
@Override protected void onLoad() { super.onLoad(); // these styles need to be the same for the box and shadow so // that we can measure properly matchStyles("display"); matchStyles("fontSize"); matchStyles("fontFamily"); matchStyles("fontWeight"); matchStyles("lineHeight"); matchStyles("paddingTop"); matchStyles("paddingRight"); matchStyles("paddingBottom"); matchStyles("paddingLeft"); adjustSize(); }
Matches the styles and adjusts the size. This needs to be called after the input is added to the DOM, so we do it in onLoad.
public void matchStyles(String name) { String value = MiscUtils.getComputedStyle(box.getElement(), name); if (value != null) { try { // we might have a bogus value (e.g. width: -10px). we // just let it fail quietly. shadow.getElement().getStyle().setProperty(name, value); } catch (Exception e) { GWT.log("Exception in matchStyles for name="+name+" value="+value, e); } } }
style manipulation
@Override public void onKeyDown(KeyDownEvent event) { char c = MiscUtils.getCharCode(event.getNativeEvent()); onKeyCodeEvent(event, box.getValue()+c); }
On key down we assume the key will go at the end. It's the most common case and not that distracting if that's not true.
public String serialize() { //Construct the webservices.xml definitions StringBuilder buffer = new StringBuilder(); // header: opening webservices tag createHeader(buffer); // webservice-description subelements for (WebserviceDescriptionMetaData wm : webserviceDescriptions) buffer.append(wm.serialize()); // closing webservices tag buffer.append("</webservices>"); return buffer.toString(); }
Serialize as a String
public static void setEnabled(Element element, boolean enabled) { element.setPropertyBoolean("disabled", !enabled); setStyleName(element, "disabled", !enabled); }
It's enough to just set the disabled attribute on the element, but we want to also add a "disabled" class so that we can style it. At some point we'll just be able to use .button:disabled, but that doesn't work in IE8-
private Method getPropertySourceMethod(Object sourceObject, Object destinationObject, String destinationProperty) { BeanToBeanMapping beanToBeanMapping = beanToBeanMappings.get(ClassPair .get(sourceObject.getClass(), destinationObject .getClass())); String sourceProperty = null; if (beanToBeanMapping != null) { sourceProperty = beanToBeanMapping .getSourceProperty(destinationProperty); } if (sourceProperty == null) { sourceProperty = destinationProperty; } return BeanUtils.getGetterPropertyMethod(sourceObject.getClass(), sourceProperty); }
get the property source method corresponding to given destination property @param sourceObject @param destinationObject @param destinationProperty @return
protected TypeReference<?> getBeanPropertyType(Class<?> clazz, String propertyName, TypeReference<?> originalType) { TypeReference<?> propertyDestinationType = null; if (beanDestinationPropertyTypeProvider != null) { propertyDestinationType = beanDestinationPropertyTypeProvider .getPropertyType(clazz, propertyName, originalType); } if (propertyDestinationType == null) { propertyDestinationType = originalType; } return propertyDestinationType; }
get the bean property type @param clazz @param propertyName @param originalType @return
public void addBeanToBeanMapping(BeanToBeanMapping beanToBeanMapping) { beanToBeanMappings.put(ClassPair.get(beanToBeanMapping .getSourceClass(), beanToBeanMapping.getDestinationClass()), beanToBeanMapping); }
Add a mapping of properties between two beans @param beanToBeanMapping
public static boolean hasCacheableHeaders(Headers headers) { if (headers.contains(VARY_ALL)) { return false; } if (headers.contains(CACHE_CONTROL)) { Optional<CacheControl> cc = headers.getCacheControl(); if (OptionalUtils.exists(cc, (cc2 -> cc2.isNoCache() || cc2.isNoStore()))) { return false; } } if (headers.contains(PRAGMA)) { Optional<String> header = headers.getFirstHeaderValue(PRAGMA); if (OptionalUtils.exists(header, s -> s.contains(NO_CACHE_HEADER_VALUE))) { return false; } } if (headers.contains(EXPIRES)) { Optional<LocalDateTime> expires = headers.getExpires(); Optional<LocalDateTime> date = headers.getDate(); if (!expires.isPresent() || !date.isPresent()) { return false; } if (OptionalUtils.exists(expires, e -> e.isBefore(date.get())) || OptionalUtils.exists(expires, e -> e.isEqual(date.get()))) { return false; } } return true; }
From http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.4. <p></p> Unless specifically constrained by a cache-control (section 14.9) directive, a caching system MAY always store a successful response (see section 13.8) as a cache entry, MAY return it without validation if it is fresh, and MAY return it after successful validation. If there is neither a cache validator nor an explicit expiration time associated with a response, we do not expect it to be cached, but certain caches MAY violate this expectation (for example, when little or no network connectivity is available). A client can usually detect that such a response was taken from a cache by comparing the Date header to the current time. @param headers the headers to analyze @return {@code true} if the headers were cacheable, {@code false} if not.
public static SPIProvider getInstance() { if (me == null) { final ClassLoader cl = ClassLoaderProvider.getDefaultProvider().getServerIntegrationClassLoader(); me = SPIProviderResolver.getInstance(cl).getProvider(); } return me; }
Gets the a singleton reference to the SPIProvider returned by the SPIProviderResolver retrieved using the default server integration classloader. @return this class instance
public <T> T getSPI(Class<T> spiType) { return getSPI(spiType, SecurityActions.getContextClassLoader()); }
Gets the specified SPI, using the current thread context classloader @param <T> type of spi class @param spiType spi class to retrieve @return object
public Optional<SoyMsgBundle> resolve(final Optional<Locale> locale) throws IOException { if (!locale.isPresent()) { return Optional.absent(); } synchronized (msgBundles) { SoyMsgBundle soyMsgBundle = null; if (isHotReloadModeOff()) { soyMsgBundle = msgBundles.get(locale.get()); } if (soyMsgBundle == null) { soyMsgBundle = createSoyMsgBundle(locale.get()); if (soyMsgBundle == null) { soyMsgBundle = createSoyMsgBundle(new Locale(locale.get().getLanguage())); } if (soyMsgBundle == null && fallbackToEnglish) { soyMsgBundle = createSoyMsgBundle(Locale.ENGLISH); } if (soyMsgBundle == null) { return Optional.absent(); } if (isHotReloadModeOff()) { msgBundles.put(locale.get(), soyMsgBundle); } } return Optional.fromNullable(soyMsgBundle); } }
Based on a provided locale return a SoyMsgBundle file. If a passed in locale object is "Optional.absent()", the implementation will return Optional.absent() as well @param locale - maybe locale @return maybe soy msg bundle
protected SoyMsgBundle createSoyMsgBundle(final Locale locale) throws IOException { Preconditions.checkNotNull(messagesPath, "messagesPath cannot be null!"); final String path = messagesPath + "_" + locale.toString() + ".xlf"; final Enumeration<URL> e = Thread.currentThread().getContextClassLoader().getResources(path); final List<SoyMsgBundle> msgBundles = Lists.newArrayList(); final SoyMsgBundleHandler msgBundleHandler = new SoyMsgBundleHandler(new XliffMsgPlugin()); while (e.hasMoreElements()) { final URL msgFile = e.nextElement(); final SoyMsgBundle soyMsgBundle = msgBundleHandler.createFromResource(msgFile); msgBundles.add(soyMsgBundle); } return mergeMsgBundles(locale, msgBundles).orNull(); }
An implementation that using a ContextClassLoader iterates over all urls it finds based on a messagePath and locale, e.g. messages_de_DE.xlf and returns a merged SoyMsgBundle of SoyMsgBundle matching a a pattern it finds in a class path. @param locale - locale @return SoyMsgBundle - bundle @throws java.io.IOException - io error
private Optional<? extends SoyMsgBundle> mergeMsgBundles(final Locale locale, final List<SoyMsgBundle> soyMsgBundles) { if (soyMsgBundles.isEmpty()) { return Optional.absent(); } final List<SoyMsg> msgs = Lists.newArrayList(); for (final SoyMsgBundle smb : soyMsgBundles) { for (final Iterator<SoyMsg> it = smb.iterator(); it.hasNext();) { msgs.add(it.next()); } } return Optional.of(new SoyMsgBundleImpl(locale.toString(), msgs)); }
Merge msg bundles together, creating new MsgBundle with merges msg bundles passed in as a method argument
@Override public Optional<String> hash(final Optional<URL> url) throws IOException { if (!url.isPresent()) { return Optional.absent(); } logger.debug("Calculating md5 hash, url:{}", url); if (isHotReloadModeOff()) { final String md5 = cache.getIfPresent(url.get()); logger.debug("md5 hash:{}", md5); if (md5 != null) { return Optional.of(md5); } } final InputStream is = url.get().openStream(); final String md5 = getMD5Checksum(is); if (isHotReloadModeOff()) { logger.debug("caching url:{} with hash:{}", url, md5); cache.put(url.get(), md5); } return Optional.fromNullable(md5); }
Calculates a md5 hash for an url If a passed in url is absent then this method will return absent as well @param url - an url to a soy template file @return - md5 checksum of a template file @throws IOException - in a case there is an IO error calculating md5 checksum
public static String[] allUpperCase(String... strings){ String[] tmp = new String[strings.length]; for(int idx=0;idx<strings.length;idx++){ if(strings[idx] != null){ tmp[idx] = strings[idx].toUpperCase(); } } return tmp; }
Make all elements of a String array upper case. @param strings string array, may contain null item but can't be null @return array containing all provided elements upper case
public static String[] allLowerCase(String... strings){ String[] tmp = new String[strings.length]; for(int idx=0;idx<strings.length;idx++){ if(strings[idx] != null){ tmp[idx] = strings[idx].toLowerCase(); } } return tmp; }
Make all elements of a String array lower case. @param strings string array, may contain null item but can't be null @return array containing all provided elements lower case
private void updateInterval() { intervalMillis = getCombinedValue(endDate, endTime) - getCombinedValue(startDate, startTime); // if this is zero, most likely the times aren't set and the // dates are the same. in this case we don't really want a // zero interval. if we *really* want a zero interval, the // default would be zero so this is safe. if (intervalMillis == 0) { intervalMillis = defaultIntervalMillis; } }
interval management
private long getCombinedValue(UTCDateBox date, UTCTimeBox time) { Long dateValue = date.getValue(); Long timeValue = time.getValue(); if (dateValue != null) { if (timeValue != null) { return dateValue + timeValue; } else { return dateValue; } } else { if (timeValue != null) { return timeValue; } else { return 0; } } }
This allows us to treat a datetime as a single value, making it easy for comparison and adjustment. We don't actually expose this because the timezone issues make it too confusing to clients.
private void setCombinedValue(UTCDateBox date, UTCTimeBox time, long value, boolean setTimeValue) { date.setValue(datePartMillis(value), false); if (setTimeValue) { time.setValue(timePartMillis(value), false); } }
This allows us to treat a datetime as a single value, making it easy for comparison and adjustment. We don't actually expose this because the timezone issues make it too confusing to clients. @param setTimeValue Sometimes we don't want to set the time value explicitly. Generally this is the case when we haven't specified a time.
public FullTypeSignature getTypeErasureSignature() { if (typeErasureSignature == null) { typeErasureSignature = new ClassTypeSignature(binaryName, new TypeArgSignature[0], ownerTypeSignature == null ? null : (ClassTypeSignature) ownerTypeSignature .getTypeErasureSignature()); } return typeErasureSignature; }
get the type erasure signature
public MIMEType addParameter(String name, String value) { Map<String, String> copy = new LinkedHashMap<>(this.parameters); copy.put(name, value); return new MIMEType(type, subType, copy); }
Adds a parameter to the MIMEType. @param name name of parameter @param value value of parameter @return returns a new instance with the parameter set
@Override public List<String> contentTypes() { List<String> contentTypes = null; final HttpServletRequest request = getHttpRequest(); if (favorParameterOverAcceptHeader) { contentTypes = getFavoredParameterValueAsList(request); } else { contentTypes = getAcceptHeaderValues(request); } if (isEmpty(contentTypes)) { logger.debug("Setting content types to default: {}.", DEFAULT_SUPPORTED_CONTENT_TYPES); contentTypes = DEFAULT_SUPPORTED_CONTENT_TYPES; } return unmodifiableList(contentTypes); }
Returns requested content types or default content type if none found. @return Requested content types or default content type if none found.
public static void serialize(Serializable obj, OutputStream outputStream) { if (outputStream == null) { throw new IllegalArgumentException("The OutputStream must not be null"); } ObjectOutputStream out = null; try { // stream closed in the finally out = new ObjectOutputStream(outputStream); out.writeObject(obj); } catch (IOException ex) { throw new SerializationException(ex); } finally { try { if (out != null) { out.close(); } } catch (IOException ex) { // ignore close exception } } }
<p>Serializes an <code>Object</code> to the specified stream.</p> <p>The stream will be closed once the object is written. This avoids the need for a finally clause, and maybe also exception handling, in the application code.</p> <p>The stream passed in is not buffered internally within this method. This is the responsibility of your application if desired.</p> @param obj the object to serialize to bytes, may be null @param outputStream the stream to write to, must not be null @throws IllegalArgumentException if <code>outputStream</code> is <code>null</code> @throws SerializationException (runtime) if the serialization fails
public static byte[] serialize(Serializable obj) { ByteArrayOutputStream baos = new ByteArrayOutputStream(512); serialize(obj, baos); return baos.toByteArray(); }
<p>Serializes an <code>Object</code> to a byte array for storage/serialization.</p> @param obj the object to serialize to bytes @return a byte[] with the converted Serializable @throws SerializationException (runtime) if the serialization fails
public static Object deserialize(byte[] objectData) { if (objectData == null) { throw new IllegalArgumentException("The byte[] must not be null"); } ByteArrayInputStream bais = new ByteArrayInputStream(objectData); return deserialize(bais); }
<p>Deserializes a single <code>Object</code> from an array of bytes.</p> @param objectData the serialized object, must not be null @return the deserialized object @throws IllegalArgumentException if <code>objectData</code> is <code>null</code> @throws SerializationException (runtime) if the serialization fails
public Headers getAllHeaders() { Headers requestHeaders = getHeaders(); requestHeaders = hasPayload() ? requestHeaders.withContentType(getPayload().get().getMimeType()) : requestHeaders; //We don't want to add headers more than once. return requestHeaders; }
Returns all headers with the headers from the Payload @return All the headers
public static Optimizer<DifferentiableFunction> getRegularizedOptimizer(final Optimizer<DifferentiableFunction> opt, final double l1Lambda, final double l2Lambda) { if (l1Lambda == 0 && l2Lambda == 0) { return opt; } return new Optimizer<DifferentiableFunction>() { @Override public boolean minimize(DifferentiableFunction objective, IntDoubleVector point) { DifferentiableFunction fn = getRegularizedFn(objective, false, l1Lambda, l2Lambda); return opt.minimize(fn, point); } }; }
Converts a standard optimizer to one which the given amount of l1 or l2 regularization.
public String toRomanNumeral() { if (this.romanString == null) { this.romanString = ""; int remainder = this.value; for (int i = 0; i < BASIC_VALUES.length; i++) { while (remainder >= BASIC_VALUES[i]) { this.romanString += BASIC_ROMAN_NUMERALS[i]; remainder -= BASIC_VALUES[i]; } } } return this.romanString; }
Get the Roman Numeral of the current value @return
@Override public void init(DifferentiableBatchFunction function) { gradSumSquares = new double[function.getNumDimensions()]; Arrays.fill(gradSumSquares, prm.initialSumSquares); }
Initializes all the parameters for optimization.
public void takeNoteOfGradient(IntDoubleVector gradient) { gradient.iterate(new FnIntDoubleToVoid() { @Override public void call(int index, double value) { gradSumSquares[index] += value * value; assert !Double.isNaN(gradSumSquares[index]); } }); }
A tie-in for subclasses such as AdaGrad.
@Override public double getLearningRate(int iterCount, int i) { // We use the learning rate suggested in Leon Bottou's (2012) SGD Tricks paper. // // \gamma_t = \frac{\gamma_0}{(1 + \gamma_0 \lambda t)^p} // // For SGD p = 1.0, for ASGD p = 0.75 if (prm.power == 1.0) { return prm.initialLr / (1 + prm.initialLr * prm.lambda * iterCount); } else { return prm.initialLr / Math.pow(1 + prm.initialLr * prm.lambda * iterCount, prm.power); } }
Gets the learning rate for the current iteration. @param iterCount The current iteration. @param i The index of the current model parameter.
private ArrayTypeSignature getArrayTypeSignature( GenericArrayType genericArrayType) { FullTypeSignature componentTypeSignature = getFullTypeSignature(genericArrayType .getGenericComponentType()); ArrayTypeSignature arrayTypeSignature = new ArrayTypeSignature( componentTypeSignature); return arrayTypeSignature; }
get the ArrayTypeSignature corresponding to given generic array type @param genericArrayType @return
private ClassTypeSignature getClassTypeSignature( ParameterizedType parameterizedType) { Class<?> rawType = (Class<?>) parameterizedType.getRawType(); Type[] typeArguments = parameterizedType.getActualTypeArguments(); TypeArgSignature[] typeArgSignatures = new TypeArgSignature[typeArguments.length]; for (int i = 0; i < typeArguments.length; i++) { typeArgSignatures[i] = getTypeArgSignature(typeArguments[i]); } String binaryName = rawType.isMemberClass() ? rawType.getSimpleName() : rawType.getName(); ClassTypeSignature ownerTypeSignature = parameterizedType .getOwnerType() == null ? null : (ClassTypeSignature) getFullTypeSignature(parameterizedType .getOwnerType()); ClassTypeSignature classTypeSignature = new ClassTypeSignature( binaryName, typeArgSignatures, ownerTypeSignature); return classTypeSignature; }
get the ClassTypeSignature corresponding to given parameterized type @param parameterizedType @return
public TypeSignature getTypeSignature(Type type) { FullTypeSignature typeSignature = getFullTypeSignature(type); if (typeSignature != null) { return typeSignature; } if (type instanceof WildcardType) { return getTypeArgSignature((WildcardType) type); } return null; }
get the type signature corresponding to given java type @param type @return
private FullTypeSignature getFullTypeSignature(Type type) { if (type instanceof Class<?>) { return getTypeSignature((Class<?>) type); } if (type instanceof GenericArrayType) { return getArrayTypeSignature((GenericArrayType) type); } if (type instanceof ParameterizedType) { return getClassTypeSignature((ParameterizedType) type); } return null; }
get the type signature corresponding to given java type @param type @return
private FullTypeSignature getTypeSignature(Class<?> clazz) { StringBuilder sb = new StringBuilder(); if (clazz.isArray()) { sb.append(clazz.getName()); } else if (clazz.isPrimitive()) { sb.append(primitiveTypesMap.get(clazz).toString()); } else { sb.append('L').append(clazz.getName()).append(';'); } return TypeSignatureFactory.getTypeSignature(sb.toString(), false); }
get the type signature corresponding to given class @param clazz @return
private TypeArgSignature getTypeArgSignature(Type type) { if (type instanceof WildcardType) { WildcardType wildcardType = (WildcardType) type; Type lowerBound = wildcardType.getLowerBounds().length == 0 ? null : wildcardType.getLowerBounds()[0]; Type upperBound = wildcardType.getUpperBounds().length == 0 ? null : wildcardType.getUpperBounds()[0]; if (lowerBound == null && Object.class.equals(upperBound)) { return new TypeArgSignature( TypeArgSignature.UNBOUNDED_WILDCARD, (FieldTypeSignature) getFullTypeSignature(upperBound)); } else if (lowerBound == null && upperBound != null) { return new TypeArgSignature( TypeArgSignature.UPPERBOUND_WILDCARD, (FieldTypeSignature) getFullTypeSignature(upperBound)); } else if (lowerBound != null) { return new TypeArgSignature( TypeArgSignature.LOWERBOUND_WILDCARD, (FieldTypeSignature) getFullTypeSignature(lowerBound)); } else { throw new RuntimeException("Invalid type"); } } else { return new TypeArgSignature(TypeArgSignature.NO_WILDCARD, (FieldTypeSignature) getFullTypeSignature(type)); } }
get the TypeArgSignature corresponding to given type @param type @return
@Override public double getValue(IntDoubleVector params) { double sum = 0.0; for (int i=0; i<numParams; i++) { sum += Math.abs(params.get(i)); } return - lambda * sum; }
Gets - \lambda * |\theta|_1.
public static boolean zipFolder(File folder, String fileName){ boolean success = false; if(!folder.isDirectory()){ return false; } if(fileName == null){ fileName = folder.getAbsolutePath()+ZIP_EXT; } ZipArchiveOutputStream zipOutput = null; try { zipOutput = new ZipArchiveOutputStream(new File(fileName)); success = addFolderContentToZip(folder,zipOutput,""); zipOutput.close(); } catch (IOException e) { e.printStackTrace(); return false; } finally{ try { if(zipOutput != null){ zipOutput.close(); } } catch (IOException e) {} } return success; }
Utility function to zip the content of an entire folder, but not the folder itself. @param folder @param fileName optional @return success or not
private static boolean addFolderContentToZip(File folder, ZipArchiveOutputStream zipOutput, String folderFromRoot){ FileInputStream fileInput; try{ for(File currFile : folder.listFiles()){ ZipArchiveEntry entry = null; if(currFile.isDirectory()){ //as defined by ZipArchiveEntry: //Assumes the entry represents a directory if and only if the name ends with a forward slash "/". entry = new ZipArchiveEntry(folderFromRoot+currFile.getName()+"/"); zipOutput.putArchiveEntry(entry); zipOutput.closeArchiveEntry(); //now look for the content of this directory if(!addFolderContentToZip(currFile,zipOutput,folderFromRoot+currFile.getName()+"/")){ return false; } } else{ entry = new ZipArchiveEntry(folderFromRoot+currFile.getName()); entry.setSize(currFile.length()); zipOutput.putArchiveEntry(entry); fileInput = new FileInputStream(currFile); IOUtils.copy(fileInput, zipOutput); fileInput.close(); zipOutput.closeArchiveEntry(); } } }catch(FileNotFoundException fnfEx){ fnfEx.printStackTrace(); return false; }catch (IOException ioEx) { ioEx.printStackTrace(); return false; } return true; }
Add the content of a folder to the zip. If this folder also contains folder(s), this function is called recursively. @param folder @param zipOutput @param folderFromRoot relative path (from archive root) of this folder. @return
public static boolean unzipFileOrFolder(File zipFile, String unzippedFolder){ InputStream is; ArchiveInputStream in = null; OutputStream out = null; if(!zipFile.isFile()){ return false; } if(unzippedFolder == null){ unzippedFolder = FilenameUtils.removeExtension(zipFile.getAbsolutePath()); } try { is = new FileInputStream(zipFile); new File(unzippedFolder).mkdir(); in = new ArchiveStreamFactory().createArchiveInputStream(ArchiveStreamFactory.ZIP, is); ZipArchiveEntry entry = (ZipArchiveEntry)in.getNextEntry(); while(entry != null){ if(entry.isDirectory()){ new File(unzippedFolder,entry.getName()).mkdir(); } else{ out = new FileOutputStream(new File(unzippedFolder, entry.getName())); IOUtils.copy(in, out); out.close(); out = null; } entry = (ZipArchiveEntry)in.getNextEntry(); } } catch (FileNotFoundException e) { e.printStackTrace(); return false; } catch (ArchiveException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } finally{ if(out != null){ try { out.close(); } catch (IOException e) {} } if(in != null){ try { in.close(); } catch (IOException e) {} } } return true; }
Unzip a file or a folder @param zipFile @param unzippedFolder optional, if null the file/folder will be extracted in the same folder as zipFile @return
protected static final String formatUsingFormat(Long value, DateTimeFormat fmt) { if (value == null) { return ""; } else { // midnight GMT Date date = new Date(0); // offset by timezone and value date.setTime(UTCDateBox.timezoneOffsetMillis(date) + value.longValue()); // format it return fmt.format(date); } }
Formats the value provided with the specified DateTimeFormat
protected static final Long parseUsingFallbacksWithColon(String text, DateTimeFormat timeFormat) { if (text.indexOf(':') == -1) { text = text.replace(" ", ""); int numdigits = 0; int lastdigit = 0; for (int i = 0; i < text.length(); i++) { char c = text.charAt(i); if (Character.isDigit(c)) { numdigits++; lastdigit = i; } } if (numdigits == 1 || numdigits == 2) { // insert :00 int colon = lastdigit + 1; text = text.substring(0, colon) + ":00" + text.substring(colon); } else if (numdigits > 2) { // insert : int colon = lastdigit - 1; text = text.substring(0, colon) + ":" + text.substring(colon); } return parseUsingFallbacks(text, timeFormat); } else { return null; } }
Attempts to insert a colon so that a value without a colon can be parsed.
protected ServletDelegate getDelegate(ServletConfig servletConfig) { ClassLoaderProvider clProvider = ClassLoaderProvider.getDefaultProvider(); ClassLoader cl = clProvider.getWebServiceSubsystemClassLoader(); ServiceLoader<ServletDelegateFactory> sl = ServiceLoader.load(ServletDelegateFactory.class, cl); ServletDelegateFactory factory = sl.iterator().next(); return factory.newServletDelegate(servletConfig.getInitParameter(STACK_SERVLET_DELEGATE_CLASS)); }
Creates a ServletDelegate instance according to the STACK_SERVLET_DELEGATE_CLASS init parameter. The class is loaded through a ServletDelegateFactory that's retrieved as follows: - if a default ClassLoaderProvider is available, the webservice subsystem classloader from it is used to lookup the factory - otherwise the current thread context classloader is used to lookup the factory. @param servletConfig servlet config @return the servlet delegate
public static Class<?> getRawType(Type type) { if (type instanceof Class) { return (Class<?>) type; } else if (type instanceof ParameterizedType) { ParameterizedType actualType = (ParameterizedType) type; return getRawType(actualType.getRawType()); } else if (type instanceof GenericArrayType) { GenericArrayType genericArrayType = (GenericArrayType) type; Object rawArrayType = Array.newInstance(getRawType(genericArrayType .getGenericComponentType()), 0); return rawArrayType.getClass(); } else if (type instanceof WildcardType) { WildcardType castedType = (WildcardType) type; return getRawType(castedType.getUpperBounds()[0]); } else { throw new IllegalArgumentException( "Type \'" + type + "\' is not a Class, " + "ParameterizedType, or GenericArrayType. Can't extract class."); } }
This method returns the actual raw class associated with the specified type.
public static boolean isAssignableFrom(TypeReference<?> from, TypeReference<?> to) { if (from == null) { return false; } if (to.equals(from)) { return true; } if (to.getType() instanceof Class) { return to.getRawType().isAssignableFrom(from.getRawType()); } else if (to.getType() instanceof ParameterizedType) { return isAssignableFrom(from.getType(), (ParameterizedType) to .getType(), new HashMap<String, Type>()); } else if (to.getType() instanceof GenericArrayType) { return to.getRawType().isAssignableFrom(from.getRawType()) && isAssignableFrom(from.getType(), (GenericArrayType) to .getType()); } else { throw new AssertionError("Unexpected Type : " + to); } }
Check if this type is assignable from the given Type.
private static boolean isAssignableFrom(Type from, ParameterizedType to, Map<String, Type> typeVarMap) { if (from == null) { return false; } if (to.equals(from)) { return true; } // First figure out the class and any type information. Class<?> clazz = getRawType(from); ParameterizedType ptype = null; if (from instanceof ParameterizedType) { ptype = (ParameterizedType) from; } // Load up parameterized variable info if it was parameterized. if (ptype != null) { Type[] tArgs = ptype.getActualTypeArguments(); TypeVariable<?>[] tParams = clazz.getTypeParameters(); for (int i = 0; i < tArgs.length; i++) { Type arg = tArgs[i]; TypeVariable<?> var = tParams[i]; while (arg instanceof TypeVariable) { TypeVariable<?> v = (TypeVariable<?>) arg; arg = typeVarMap.get(v.getName()); } typeVarMap.put(var.getName(), arg); } // check if they are equivalent under our current mapping. if (typeEquals(ptype, to, typeVarMap)) { return true; } } for (Type itype : clazz.getGenericInterfaces()) { if (isAssignableFrom(itype, to, new HashMap<String, Type>( typeVarMap))) { return true; } } // Interfaces didn't work, try the superclass. Type sType = clazz.getGenericSuperclass(); if (isAssignableFrom(sType, to, new HashMap<String, Type>(typeVarMap))) { return true; } return false; }
Private recursive helper function to actually do the type-safe checking of assignability.
private static boolean typeEquals(ParameterizedType from, ParameterizedType to, Map<String, Type> typeVarMap) { if (from.getRawType().equals(to.getRawType())) { Type[] fromArgs = from.getActualTypeArguments(); Type[] toArgs = to.getActualTypeArguments(); for (int i = 0; i < fromArgs.length; i++) { if (!matches(fromArgs[i], toArgs[i], typeVarMap)) { return false; } } return true; } return false; }
Checks if two parameterized types are exactly equal, under the variable replacement described in the typeVarMap.
private static boolean matches(Type from, Type to, Map<String, Type> typeMap) { if (to.equals(from)) return true; if (from instanceof TypeVariable) { return to.equals(typeMap.get(((TypeVariable<?>) from).getName())); } return false; }
Checks if two types are the same or are equivalent under a variable mapping given in the type map that was provided.
private static boolean isAssignableFrom(Type from, GenericArrayType to) { Type toGenericComponentType = to.getGenericComponentType(); if (toGenericComponentType instanceof ParameterizedType) { Type t = from; if (from instanceof GenericArrayType) { t = ((GenericArrayType) from).getGenericComponentType(); } else if (from instanceof Class) { Class<?> classType = (Class<?>) from; while (classType.isArray()) { classType = classType.getComponentType(); } t = classType; } return isAssignableFrom(t, (ParameterizedType) toGenericComponentType, new HashMap<String, Type>()); } // No generic defined on "to"; therefore, return true and let other // checks determine assignability return true; }
Private helper function that performs some assignability checks for the provided GenericArrayType.
@Override public void setValue(String value, boolean fireEvents) { boolean added = setSelectedValue(this, value, addMissingValue); if (added && fireEvents) { ValueChangeEvent.fire(this, getValue()); } }
Selects the specified value in the list. @param value the new value @param fireEvents if true, a ValueChangeEvent event will be fired @see #setAddMissingValue
public static final String getSelectedValue(ListBox list) { int index = list.getSelectedIndex(); return (index >= 0) ? list.getValue(index) : null; }
Utility function to get the current value.
public static final String getSelectedText(ListBox list) { int index = list.getSelectedIndex(); return (index >= 0) ? list.getItemText(index) : null; }
Utility function to get the current text.
public static final int findValueInListBox(ListBox list, String value) { for (int i=0; i<list.getItemCount(); i++) { if (value.equals(list.getValue(i))) { return i; } } return -1; }
Utility function to find the first index of a value in a ListBox.
public static final boolean setSelectedValue(ListBox list, String value, boolean addMissingValues) { if (value == null) { list.setSelectedIndex(0); return false; } else { int index = findValueInListBox(list, value); if (index >= 0) { list.setSelectedIndex(index); return true; } if (addMissingValues) { list.addItem(value, value); // now that it's there, search again index = findValueInListBox(list, value); list.setSelectedIndex(index); return true; } return false; } }
Utility function to set the current value in a ListBox. @return returns true if the option corresponding to the value was successfully selected in the ListBox
private String normalize(final String viewName) { String normalized = viewName; if (normalized.startsWith("/")) { normalized = normalized.substring(0); } if (normalized.endsWith("/")) { normalized = normalized.substring(0, normalized.length() - 1); } return normalized.replaceAll("/", "."); }
Remove beginning and ending slashes, then replace all occurrences of / with . @param viewName The Spring viewName @return The name of the view, dot separated.
private double computeLearningRate(int i) { if (gradAccum[i] < 0) { throw new RuntimeException("Gradient accumulator is < 0: " + gradAccum[i]); } if (updAccum[i] < 0) { throw new RuntimeException("Update accumulator is < 0: " + updAccum[i]); } double learningRate = Math.sqrt((updAccum[i] + prm.constantAddend) / (gradAccum[i] + prm.constantAddend)); assert !Double.isNaN(learningRate); // We shouldn't ever worry about infinities because of the constantAdded being > 0. assert !Double.isInfinite(learningRate); return learningRate; }
The entire point of this method is to carefully compute the following: <p> Math.sqrt(updAccum[i] + prm.constantAddend) / Math.sqrt(gradAccum[i] + prm.constantAddend); </p> without running into boundary cases. @param i The index of the parameter for which to compute the learning rate. @return The learning rate for that parameter.
public static String capitalizePropertyName(String s) { if (s.length() == 0) { return s; } char[] chars = s.toCharArray(); chars[0] = Character.toUpperCase(chars[0]); return new String(chars); }
Return a capitalized version of the specified property name. @param s The property name
public static Map<String, Method> getSetters(Class<?> clazz) { Map<String, Method> setters = new HashMap<String, Method>(); Method[] methods = clazz.getMethods(); for (Method method : methods) { String methodName = method.getName(); if (method.getParameterTypes().length == 1 && methodName.startsWith("set") && methodName.length() > 3 && method.getReturnType() == Void.TYPE) { String propertyName = methodName.substring(3, 4).toLowerCase(); if (methodName.length() > 4) { propertyName += methodName.substring(4); } setters.put(propertyName, method); } } return setters; }
get a map of public setters (propertyName -> Method) @param clazz @return