id
int32
0
165k
repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
144,000
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java
ExcelFunctions.datedif
public static int datedif(EvaluationContext ctx, Object startDate, Object endDate, Object unit) { LocalDate _startDate = Conversions.toDate(startDate, ctx); LocalDate _endDate = Conversions.toDate(endDate, ctx); String _unit = Conversions.toString(unit, ctx).toLowerCase(); if (_startDate.isAfter(_endDate)) { throw new RuntimeException("Start date cannot be after end date"); } switch (_unit) { case "y": return (int) ChronoUnit.YEARS.between(_startDate, _endDate); case "m": return (int) ChronoUnit.MONTHS.between(_startDate, _endDate); case "d": return (int) ChronoUnit.DAYS.between(_startDate, _endDate); case "md": return Period.between(_startDate, _endDate).getDays(); case "ym": return Period.between(_startDate, _endDate).getMonths(); case "yd": return (int) ChronoUnit.DAYS.between(_startDate.withYear(_endDate.getYear()), _endDate); } throw new RuntimeException("Invalid unit value: " + _unit); }
java
public static int datedif(EvaluationContext ctx, Object startDate, Object endDate, Object unit) { LocalDate _startDate = Conversions.toDate(startDate, ctx); LocalDate _endDate = Conversions.toDate(endDate, ctx); String _unit = Conversions.toString(unit, ctx).toLowerCase(); if (_startDate.isAfter(_endDate)) { throw new RuntimeException("Start date cannot be after end date"); } switch (_unit) { case "y": return (int) ChronoUnit.YEARS.between(_startDate, _endDate); case "m": return (int) ChronoUnit.MONTHS.between(_startDate, _endDate); case "d": return (int) ChronoUnit.DAYS.between(_startDate, _endDate); case "md": return Period.between(_startDate, _endDate).getDays(); case "ym": return Period.between(_startDate, _endDate).getMonths(); case "yd": return (int) ChronoUnit.DAYS.between(_startDate.withYear(_endDate.getYear()), _endDate); } throw new RuntimeException("Invalid unit value: " + _unit); }
[ "public", "static", "int", "datedif", "(", "EvaluationContext", "ctx", ",", "Object", "startDate", ",", "Object", "endDate", ",", "Object", "unit", ")", "{", "LocalDate", "_startDate", "=", "Conversions", ".", "toDate", "(", "startDate", ",", "ctx", ")", ";", "LocalDate", "_endDate", "=", "Conversions", ".", "toDate", "(", "endDate", ",", "ctx", ")", ";", "String", "_unit", "=", "Conversions", ".", "toString", "(", "unit", ",", "ctx", ")", ".", "toLowerCase", "(", ")", ";", "if", "(", "_startDate", ".", "isAfter", "(", "_endDate", ")", ")", "{", "throw", "new", "RuntimeException", "(", "\"Start date cannot be after end date\"", ")", ";", "}", "switch", "(", "_unit", ")", "{", "case", "\"y\"", ":", "return", "(", "int", ")", "ChronoUnit", ".", "YEARS", ".", "between", "(", "_startDate", ",", "_endDate", ")", ";", "case", "\"m\"", ":", "return", "(", "int", ")", "ChronoUnit", ".", "MONTHS", ".", "between", "(", "_startDate", ",", "_endDate", ")", ";", "case", "\"d\"", ":", "return", "(", "int", ")", "ChronoUnit", ".", "DAYS", ".", "between", "(", "_startDate", ",", "_endDate", ")", ";", "case", "\"md\"", ":", "return", "Period", ".", "between", "(", "_startDate", ",", "_endDate", ")", ".", "getDays", "(", ")", ";", "case", "\"ym\"", ":", "return", "Period", ".", "between", "(", "_startDate", ",", "_endDate", ")", ".", "getMonths", "(", ")", ";", "case", "\"yd\"", ":", "return", "(", "int", ")", "ChronoUnit", ".", "DAYS", ".", "between", "(", "_startDate", ".", "withYear", "(", "_endDate", ".", "getYear", "(", ")", ")", ",", "_endDate", ")", ";", "}", "throw", "new", "RuntimeException", "(", "\"Invalid unit value: \"", "+", "_unit", ")", ";", "}" ]
Calculates the number of days, months, or years between two dates.
[ "Calculates", "the", "number", "of", "days", "months", "or", "years", "between", "two", "dates", "." ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java#L214-L239
144,001
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java
ExcelFunctions.datevalue
public static LocalDate datevalue(EvaluationContext ctx, Object text) { return Conversions.toDate(text, ctx); }
java
public static LocalDate datevalue(EvaluationContext ctx, Object text) { return Conversions.toDate(text, ctx); }
[ "public", "static", "LocalDate", "datevalue", "(", "EvaluationContext", "ctx", ",", "Object", "text", ")", "{", "return", "Conversions", ".", "toDate", "(", "text", ",", "ctx", ")", ";", "}" ]
Converts date stored in text to an actual date
[ "Converts", "date", "stored", "in", "text", "to", "an", "actual", "date" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java#L244-L246
144,002
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java
ExcelFunctions.days
public static int days(EvaluationContext ctx, Object endDate, Object startDate) { return datedif(ctx, startDate, endDate, "d"); }
java
public static int days(EvaluationContext ctx, Object endDate, Object startDate) { return datedif(ctx, startDate, endDate, "d"); }
[ "public", "static", "int", "days", "(", "EvaluationContext", "ctx", ",", "Object", "endDate", ",", "Object", "startDate", ")", "{", "return", "datedif", "(", "ctx", ",", "startDate", ",", "endDate", ",", "\"d\"", ")", ";", "}" ]
Returns the number of days between two dates.
[ "Returns", "the", "number", "of", "days", "between", "two", "dates", "." ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java#L258-L260
144,003
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java
ExcelFunctions.edate
public static Temporal edate(EvaluationContext ctx, Object date, Object months) { Temporal dateOrDateTime = Conversions.toDateOrDateTime(date, ctx); int _months = Conversions.toInteger(months, ctx); return dateOrDateTime.plus(_months, ChronoUnit.MONTHS); }
java
public static Temporal edate(EvaluationContext ctx, Object date, Object months) { Temporal dateOrDateTime = Conversions.toDateOrDateTime(date, ctx); int _months = Conversions.toInteger(months, ctx); return dateOrDateTime.plus(_months, ChronoUnit.MONTHS); }
[ "public", "static", "Temporal", "edate", "(", "EvaluationContext", "ctx", ",", "Object", "date", ",", "Object", "months", ")", "{", "Temporal", "dateOrDateTime", "=", "Conversions", ".", "toDateOrDateTime", "(", "date", ",", "ctx", ")", ";", "int", "_months", "=", "Conversions", ".", "toInteger", "(", "months", ",", "ctx", ")", ";", "return", "dateOrDateTime", ".", "plus", "(", "_months", ",", "ChronoUnit", ".", "MONTHS", ")", ";", "}" ]
Moves a date by the given number of months
[ "Moves", "a", "date", "by", "the", "given", "number", "of", "months" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java#L265-L269
144,004
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java
ExcelFunctions.time
public static OffsetTime time(EvaluationContext ctx, Object hours, Object minutes, Object seconds) { int _hours = Conversions.toInteger(hours, ctx); int _minutes = Conversions.toInteger(minutes, ctx); int _seconds = Conversions.toInteger(seconds, ctx); LocalTime localTime = LocalTime.of(_hours, _minutes, _seconds); return ZonedDateTime.of(LocalDate.now(ctx.getTimezone()), localTime, ctx.getTimezone()).toOffsetDateTime().toOffsetTime(); }
java
public static OffsetTime time(EvaluationContext ctx, Object hours, Object minutes, Object seconds) { int _hours = Conversions.toInteger(hours, ctx); int _minutes = Conversions.toInteger(minutes, ctx); int _seconds = Conversions.toInteger(seconds, ctx); LocalTime localTime = LocalTime.of(_hours, _minutes, _seconds); return ZonedDateTime.of(LocalDate.now(ctx.getTimezone()), localTime, ctx.getTimezone()).toOffsetDateTime().toOffsetTime(); }
[ "public", "static", "OffsetTime", "time", "(", "EvaluationContext", "ctx", ",", "Object", "hours", ",", "Object", "minutes", ",", "Object", "seconds", ")", "{", "int", "_hours", "=", "Conversions", ".", "toInteger", "(", "hours", ",", "ctx", ")", ";", "int", "_minutes", "=", "Conversions", ".", "toInteger", "(", "minutes", ",", "ctx", ")", ";", "int", "_seconds", "=", "Conversions", ".", "toInteger", "(", "seconds", ",", "ctx", ")", ";", "LocalTime", "localTime", "=", "LocalTime", ".", "of", "(", "_hours", ",", "_minutes", ",", "_seconds", ")", ";", "return", "ZonedDateTime", ".", "of", "(", "LocalDate", ".", "now", "(", "ctx", ".", "getTimezone", "(", ")", ")", ",", "localTime", ",", "ctx", ".", "getTimezone", "(", ")", ")", ".", "toOffsetDateTime", "(", ")", ".", "toOffsetTime", "(", ")", ";", "}" ]
Defines a time value
[ "Defines", "a", "time", "value" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java#L309-L315
144,005
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java
ExcelFunctions.timevalue
public static OffsetTime timevalue(EvaluationContext ctx, Object text) { return Conversions.toTime(text, ctx); }
java
public static OffsetTime timevalue(EvaluationContext ctx, Object text) { return Conversions.toTime(text, ctx); }
[ "public", "static", "OffsetTime", "timevalue", "(", "EvaluationContext", "ctx", ",", "Object", "text", ")", "{", "return", "Conversions", ".", "toTime", "(", "text", ",", "ctx", ")", ";", "}" ]
Converts time stored in text to an actual time
[ "Converts", "time", "stored", "in", "text", "to", "an", "actual", "time" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java#L320-L322
144,006
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java
ExcelFunctions.today
public static LocalDate today(EvaluationContext ctx) { return ctx.getNow().atZone(ctx.getTimezone()).toLocalDate(); }
java
public static LocalDate today(EvaluationContext ctx) { return ctx.getNow().atZone(ctx.getTimezone()).toLocalDate(); }
[ "public", "static", "LocalDate", "today", "(", "EvaluationContext", "ctx", ")", "{", "return", "ctx", ".", "getNow", "(", ")", ".", "atZone", "(", "ctx", ".", "getTimezone", "(", ")", ")", ".", "toLocalDate", "(", ")", ";", "}" ]
Returns the current date
[ "Returns", "the", "current", "date" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java#L326-L328
144,007
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java
ExcelFunctions.year
public static int year(EvaluationContext ctx, Object date) { return Conversions.toDateOrDateTime(date, ctx).get(ChronoField.YEAR); }
java
public static int year(EvaluationContext ctx, Object date) { return Conversions.toDateOrDateTime(date, ctx).get(ChronoField.YEAR); }
[ "public", "static", "int", "year", "(", "EvaluationContext", "ctx", ",", "Object", "date", ")", "{", "return", "Conversions", ".", "toDateOrDateTime", "(", "date", ",", "ctx", ")", ".", "get", "(", "ChronoField", ".", "YEAR", ")", ";", "}" ]
Returns only the year of a date
[ "Returns", "only", "the", "year", "of", "a", "date" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java#L341-L343
144,008
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java
ExcelFunctions.abs
public static BigDecimal abs(EvaluationContext ctx, Object number) { return Conversions.toDecimal(number, ctx).abs(); }
java
public static BigDecimal abs(EvaluationContext ctx, Object number) { return Conversions.toDecimal(number, ctx).abs(); }
[ "public", "static", "BigDecimal", "abs", "(", "EvaluationContext", "ctx", ",", "Object", "number", ")", "{", "return", "Conversions", ".", "toDecimal", "(", "number", ",", "ctx", ")", ".", "abs", "(", ")", ";", "}" ]
Returns the absolute value of a number
[ "Returns", "the", "absolute", "value", "of", "a", "number" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java#L352-L354
144,009
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java
ExcelFunctions.exp
public static BigDecimal exp(EvaluationContext ctx, Object number) { BigDecimal _number = Conversions.toDecimal(number, ctx); return ExpressionUtils.decimalPow(E, _number); }
java
public static BigDecimal exp(EvaluationContext ctx, Object number) { BigDecimal _number = Conversions.toDecimal(number, ctx); return ExpressionUtils.decimalPow(E, _number); }
[ "public", "static", "BigDecimal", "exp", "(", "EvaluationContext", "ctx", ",", "Object", "number", ")", "{", "BigDecimal", "_number", "=", "Conversions", ".", "toDecimal", "(", "number", ",", "ctx", ")", ";", "return", "ExpressionUtils", ".", "decimalPow", "(", "E", ",", "_number", ")", ";", "}" ]
Returns e raised to the power of number
[ "Returns", "e", "raised", "to", "the", "power", "of", "number" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java#L370-L373
144,010
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java
ExcelFunctions._int
public static int _int(EvaluationContext ctx, Object number) { return Conversions.toDecimal(number, ctx).setScale(0, RoundingMode.FLOOR).intValue(); }
java
public static int _int(EvaluationContext ctx, Object number) { return Conversions.toDecimal(number, ctx).setScale(0, RoundingMode.FLOOR).intValue(); }
[ "public", "static", "int", "_int", "(", "EvaluationContext", "ctx", ",", "Object", "number", ")", "{", "return", "Conversions", ".", "toDecimal", "(", "number", ",", "ctx", ")", ".", "setScale", "(", "0", ",", "RoundingMode", ".", "FLOOR", ")", ".", "intValue", "(", ")", ";", "}" ]
Rounds a number down to the nearest integer
[ "Rounds", "a", "number", "down", "to", "the", "nearest", "integer" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java#L378-L380
144,011
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java
ExcelFunctions.min
public static BigDecimal min(EvaluationContext ctx, Object... args) { if (args.length == 0) { throw new RuntimeException("Wrong number of arguments"); } BigDecimal result = null; for (Object arg : args) { BigDecimal _arg = Conversions.toDecimal(arg, ctx); result = result != null ? _arg.min(result) : _arg; } return result; }
java
public static BigDecimal min(EvaluationContext ctx, Object... args) { if (args.length == 0) { throw new RuntimeException("Wrong number of arguments"); } BigDecimal result = null; for (Object arg : args) { BigDecimal _arg = Conversions.toDecimal(arg, ctx); result = result != null ? _arg.min(result) : _arg; } return result; }
[ "public", "static", "BigDecimal", "min", "(", "EvaluationContext", "ctx", ",", "Object", "...", "args", ")", "{", "if", "(", "args", ".", "length", "==", "0", ")", "{", "throw", "new", "RuntimeException", "(", "\"Wrong number of arguments\"", ")", ";", "}", "BigDecimal", "result", "=", "null", ";", "for", "(", "Object", "arg", ":", "args", ")", "{", "BigDecimal", "_arg", "=", "Conversions", ".", "toDecimal", "(", "arg", ",", "ctx", ")", ";", "result", "=", "result", "!=", "null", "?", "_arg", ".", "min", "(", "result", ")", ":", "_arg", ";", "}", "return", "result", ";", "}" ]
Returns the minimum of all arguments
[ "Returns", "the", "minimum", "of", "all", "arguments" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java#L401-L412
144,012
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java
ExcelFunctions.mod
public static BigDecimal mod(EvaluationContext ctx, Object number, Object divisor) { BigDecimal _number = Conversions.toDecimal(number, ctx); BigDecimal _divisor = Conversions.toDecimal(divisor, ctx); return _number.subtract(_divisor.multiply(new BigDecimal(_int(ctx, _number.divide(_divisor, 10, RoundingMode.HALF_UP))))); }
java
public static BigDecimal mod(EvaluationContext ctx, Object number, Object divisor) { BigDecimal _number = Conversions.toDecimal(number, ctx); BigDecimal _divisor = Conversions.toDecimal(divisor, ctx); return _number.subtract(_divisor.multiply(new BigDecimal(_int(ctx, _number.divide(_divisor, 10, RoundingMode.HALF_UP))))); }
[ "public", "static", "BigDecimal", "mod", "(", "EvaluationContext", "ctx", ",", "Object", "number", ",", "Object", "divisor", ")", "{", "BigDecimal", "_number", "=", "Conversions", ".", "toDecimal", "(", "number", ",", "ctx", ")", ";", "BigDecimal", "_divisor", "=", "Conversions", ".", "toDecimal", "(", "divisor", ",", "ctx", ")", ";", "return", "_number", ".", "subtract", "(", "_divisor", ".", "multiply", "(", "new", "BigDecimal", "(", "_int", "(", "ctx", ",", "_number", ".", "divide", "(", "_divisor", ",", "10", ",", "RoundingMode", ".", "HALF_UP", ")", ")", ")", ")", ")", ";", "}" ]
Returns the remainder after number is divided by divisor
[ "Returns", "the", "remainder", "after", "number", "is", "divided", "by", "divisor" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java#L417-L421
144,013
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java
ExcelFunctions.power
public static BigDecimal power(EvaluationContext ctx, Object number, Object power) { BigDecimal _number = Conversions.toDecimal(number, ctx); BigDecimal _power = Conversions.toDecimal(power, ctx); return ExpressionUtils.decimalPow(_number, _power); }
java
public static BigDecimal power(EvaluationContext ctx, Object number, Object power) { BigDecimal _number = Conversions.toDecimal(number, ctx); BigDecimal _power = Conversions.toDecimal(power, ctx); return ExpressionUtils.decimalPow(_number, _power); }
[ "public", "static", "BigDecimal", "power", "(", "EvaluationContext", "ctx", ",", "Object", "number", ",", "Object", "power", ")", "{", "BigDecimal", "_number", "=", "Conversions", ".", "toDecimal", "(", "number", ",", "ctx", ")", ";", "BigDecimal", "_power", "=", "Conversions", ".", "toDecimal", "(", "power", ",", "ctx", ")", ";", "return", "ExpressionUtils", ".", "decimalPow", "(", "_number", ",", "_power", ")", ";", "}" ]
Returns the result of a number raised to a power
[ "Returns", "the", "result", "of", "a", "number", "raised", "to", "a", "power" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java#L426-L430
144,014
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java
ExcelFunctions.randbetween
public static int randbetween(EvaluationContext ctx, Object bottom, Object top) { int _bottom = Conversions.toInteger(bottom, ctx); int _top = Conversions.toInteger(top, ctx); return (int)(Math.random() * (_top + 1 - _bottom)) + _bottom; }
java
public static int randbetween(EvaluationContext ctx, Object bottom, Object top) { int _bottom = Conversions.toInteger(bottom, ctx); int _top = Conversions.toInteger(top, ctx); return (int)(Math.random() * (_top + 1 - _bottom)) + _bottom; }
[ "public", "static", "int", "randbetween", "(", "EvaluationContext", "ctx", ",", "Object", "bottom", ",", "Object", "top", ")", "{", "int", "_bottom", "=", "Conversions", ".", "toInteger", "(", "bottom", ",", "ctx", ")", ";", "int", "_top", "=", "Conversions", ".", "toInteger", "(", "top", ",", "ctx", ")", ";", "return", "(", "int", ")", "(", "Math", ".", "random", "(", ")", "*", "(", "_top", "+", "1", "-", "_bottom", ")", ")", "+", "_bottom", ";", "}" ]
Returns a random integer number between the numbers you specify
[ "Returns", "a", "random", "integer", "number", "between", "the", "numbers", "you", "specify" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java#L442-L447
144,015
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java
ExcelFunctions.round
public static BigDecimal round(EvaluationContext ctx, Object number, Object numDigits) { BigDecimal _number = Conversions.toDecimal(number, ctx); int _numDigits = Conversions.toInteger(numDigits, ctx); return ExpressionUtils.decimalRound(_number, _numDigits, RoundingMode.HALF_UP); }
java
public static BigDecimal round(EvaluationContext ctx, Object number, Object numDigits) { BigDecimal _number = Conversions.toDecimal(number, ctx); int _numDigits = Conversions.toInteger(numDigits, ctx); return ExpressionUtils.decimalRound(_number, _numDigits, RoundingMode.HALF_UP); }
[ "public", "static", "BigDecimal", "round", "(", "EvaluationContext", "ctx", ",", "Object", "number", ",", "Object", "numDigits", ")", "{", "BigDecimal", "_number", "=", "Conversions", ".", "toDecimal", "(", "number", ",", "ctx", ")", ";", "int", "_numDigits", "=", "Conversions", ".", "toInteger", "(", "numDigits", ",", "ctx", ")", ";", "return", "ExpressionUtils", ".", "decimalRound", "(", "_number", ",", "_numDigits", ",", "RoundingMode", ".", "HALF_UP", ")", ";", "}" ]
Rounds a number to a specified number of digits
[ "Rounds", "a", "number", "to", "a", "specified", "number", "of", "digits" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java#L452-L457
144,016
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java
ExcelFunctions.rounddown
public static BigDecimal rounddown(EvaluationContext ctx, Object number, Object numDigits) { BigDecimal _number = Conversions.toDecimal(number, ctx); int _numDigits = Conversions.toInteger(numDigits, ctx); return ExpressionUtils.decimalRound(_number, _numDigits, RoundingMode.DOWN); }
java
public static BigDecimal rounddown(EvaluationContext ctx, Object number, Object numDigits) { BigDecimal _number = Conversions.toDecimal(number, ctx); int _numDigits = Conversions.toInteger(numDigits, ctx); return ExpressionUtils.decimalRound(_number, _numDigits, RoundingMode.DOWN); }
[ "public", "static", "BigDecimal", "rounddown", "(", "EvaluationContext", "ctx", ",", "Object", "number", ",", "Object", "numDigits", ")", "{", "BigDecimal", "_number", "=", "Conversions", ".", "toDecimal", "(", "number", ",", "ctx", ")", ";", "int", "_numDigits", "=", "Conversions", ".", "toInteger", "(", "numDigits", ",", "ctx", ")", ";", "return", "ExpressionUtils", ".", "decimalRound", "(", "_number", ",", "_numDigits", ",", "RoundingMode", ".", "DOWN", ")", ";", "}" ]
Rounds a number down, toward zero
[ "Rounds", "a", "number", "down", "toward", "zero" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java#L462-L467
144,017
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java
ExcelFunctions.roundup
public static BigDecimal roundup(EvaluationContext ctx, Object number, Object numDigits) { BigDecimal _number = Conversions.toDecimal(number, ctx); int _numDigits = Conversions.toInteger(numDigits, ctx); return ExpressionUtils.decimalRound(_number, _numDigits, RoundingMode.UP); }
java
public static BigDecimal roundup(EvaluationContext ctx, Object number, Object numDigits) { BigDecimal _number = Conversions.toDecimal(number, ctx); int _numDigits = Conversions.toInteger(numDigits, ctx); return ExpressionUtils.decimalRound(_number, _numDigits, RoundingMode.UP); }
[ "public", "static", "BigDecimal", "roundup", "(", "EvaluationContext", "ctx", ",", "Object", "number", ",", "Object", "numDigits", ")", "{", "BigDecimal", "_number", "=", "Conversions", ".", "toDecimal", "(", "number", ",", "ctx", ")", ";", "int", "_numDigits", "=", "Conversions", ".", "toInteger", "(", "numDigits", ",", "ctx", ")", ";", "return", "ExpressionUtils", ".", "decimalRound", "(", "_number", ",", "_numDigits", ",", "RoundingMode", ".", "UP", ")", ";", "}" ]
Rounds a number up, away from zero
[ "Rounds", "a", "number", "up", "away", "from", "zero" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java#L472-L477
144,018
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java
ExcelFunctions.sum
public static BigDecimal sum(EvaluationContext ctx, Object... args) { if (args.length == 0) { throw new RuntimeException("Wrong number of arguments"); } BigDecimal result = BigDecimal.ZERO; for (Object arg : args) { result = result.add(Conversions.toDecimal(arg, ctx)); } return result; }
java
public static BigDecimal sum(EvaluationContext ctx, Object... args) { if (args.length == 0) { throw new RuntimeException("Wrong number of arguments"); } BigDecimal result = BigDecimal.ZERO; for (Object arg : args) { result = result.add(Conversions.toDecimal(arg, ctx)); } return result; }
[ "public", "static", "BigDecimal", "sum", "(", "EvaluationContext", "ctx", ",", "Object", "...", "args", ")", "{", "if", "(", "args", ".", "length", "==", "0", ")", "{", "throw", "new", "RuntimeException", "(", "\"Wrong number of arguments\"", ")", ";", "}", "BigDecimal", "result", "=", "BigDecimal", ".", "ZERO", ";", "for", "(", "Object", "arg", ":", "args", ")", "{", "result", "=", "result", ".", "add", "(", "Conversions", ".", "toDecimal", "(", "arg", ",", "ctx", ")", ")", ";", "}", "return", "result", ";", "}" ]
Returns the sum of all arguments
[ "Returns", "the", "sum", "of", "all", "arguments" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java#L482-L492
144,019
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java
ExcelFunctions.trunc
public static int trunc(EvaluationContext ctx, Object number) { return Conversions.toDecimal(number, ctx).setScale(0, RoundingMode.DOWN).intValue(); }
java
public static int trunc(EvaluationContext ctx, Object number) { return Conversions.toDecimal(number, ctx).setScale(0, RoundingMode.DOWN).intValue(); }
[ "public", "static", "int", "trunc", "(", "EvaluationContext", "ctx", ",", "Object", "number", ")", "{", "return", "Conversions", ".", "toDecimal", "(", "number", ",", "ctx", ")", ".", "setScale", "(", "0", ",", "RoundingMode", ".", "DOWN", ")", ".", "intValue", "(", ")", ";", "}" ]
Truncates a number to an integer by removing the fractional part of the number
[ "Truncates", "a", "number", "to", "an", "integer", "by", "removing", "the", "fractional", "part", "of", "the", "number" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java#L497-L499
144,020
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java
ExcelFunctions.and
public static boolean and(EvaluationContext ctx, Object... args) { for (Object arg : args) { if (!Conversions.toBoolean(arg, ctx)) { return false; } } return true; }
java
public static boolean and(EvaluationContext ctx, Object... args) { for (Object arg : args) { if (!Conversions.toBoolean(arg, ctx)) { return false; } } return true; }
[ "public", "static", "boolean", "and", "(", "EvaluationContext", "ctx", ",", "Object", "...", "args", ")", "{", "for", "(", "Object", "arg", ":", "args", ")", "{", "if", "(", "!", "Conversions", ".", "toBoolean", "(", "arg", ",", "ctx", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Returns TRUE if and only if all its arguments evaluate to TRUE
[ "Returns", "TRUE", "if", "and", "only", "if", "all", "its", "arguments", "evaluate", "to", "TRUE" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java#L508-L515
144,021
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java
ExcelFunctions._if
public static Object _if(EvaluationContext ctx, Object logicalTest, @IntegerDefault(0) Object valueIfTrue, @BooleanDefault(false) Object valueIfFalse) { return Conversions.toBoolean(logicalTest, ctx) ? valueIfTrue : valueIfFalse; }
java
public static Object _if(EvaluationContext ctx, Object logicalTest, @IntegerDefault(0) Object valueIfTrue, @BooleanDefault(false) Object valueIfFalse) { return Conversions.toBoolean(logicalTest, ctx) ? valueIfTrue : valueIfFalse; }
[ "public", "static", "Object", "_if", "(", "EvaluationContext", "ctx", ",", "Object", "logicalTest", ",", "@", "IntegerDefault", "(", "0", ")", "Object", "valueIfTrue", ",", "@", "BooleanDefault", "(", "false", ")", "Object", "valueIfFalse", ")", "{", "return", "Conversions", ".", "toBoolean", "(", "logicalTest", ",", "ctx", ")", "?", "valueIfTrue", ":", "valueIfFalse", ";", "}" ]
Returns one value if the condition evaluates to TRUE, and another value if it evaluates to FALSE
[ "Returns", "one", "value", "if", "the", "condition", "evaluates", "to", "TRUE", "and", "another", "value", "if", "it", "evaluates", "to", "FALSE" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java#L527-L529
144,022
GenesysPureEngage/authentication-client-java
src/main/java/com/genesys/internal/authentication/api/AuthenticationApi.java
AuthenticationApi.pingWithHttpInfo
public ApiResponse<ModelApiResponse> pingWithHttpInfo() throws ApiException { com.squareup.okhttp.Call call = pingValidateBeforeCall(null, null); Type localVarReturnType = new TypeToken<ModelApiResponse>(){}.getType(); return apiClient.execute(call, localVarReturnType); }
java
public ApiResponse<ModelApiResponse> pingWithHttpInfo() throws ApiException { com.squareup.okhttp.Call call = pingValidateBeforeCall(null, null); Type localVarReturnType = new TypeToken<ModelApiResponse>(){}.getType(); return apiClient.execute(call, localVarReturnType); }
[ "public", "ApiResponse", "<", "ModelApiResponse", ">", "pingWithHttpInfo", "(", ")", "throws", "ApiException", "{", "com", ".", "squareup", ".", "okhttp", ".", "Call", "call", "=", "pingValidateBeforeCall", "(", "null", ",", "null", ")", ";", "Type", "localVarReturnType", "=", "new", "TypeToken", "<", "ModelApiResponse", ">", "(", ")", "{", "}", ".", "getType", "(", ")", ";", "return", "apiClient", ".", "execute", "(", "call", ",", "localVarReturnType", ")", ";", "}" ]
Check connection Return 200 if user is authenticated otherwise 403 @return ApiResponse&lt;ModelApiResponse&gt; @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
[ "Check", "connection", "Return", "200", "if", "user", "is", "authenticated", "otherwise", "403" ]
eb0d58343ee42ebd3c037163c1137f611dfcbb3a
https://github.com/GenesysPureEngage/authentication-client-java/blob/eb0d58343ee42ebd3c037163c1137f611dfcbb3a/src/main/java/com/genesys/internal/authentication/api/AuthenticationApi.java#L797-L801
144,023
GenesysPureEngage/authentication-client-java
src/main/java/com/genesys/internal/authentication/api/AuthenticationApi.java
AuthenticationApi.retrievePCTokenUsingPOSTWithHttpInfo
public ApiResponse<Object> retrievePCTokenUsingPOSTWithHttpInfo() throws ApiException { com.squareup.okhttp.Call call = retrievePCTokenUsingPOSTValidateBeforeCall(null, null); Type localVarReturnType = new TypeToken<Object>(){}.getType(); return apiClient.execute(call, localVarReturnType); }
java
public ApiResponse<Object> retrievePCTokenUsingPOSTWithHttpInfo() throws ApiException { com.squareup.okhttp.Call call = retrievePCTokenUsingPOSTValidateBeforeCall(null, null); Type localVarReturnType = new TypeToken<Object>(){}.getType(); return apiClient.execute(call, localVarReturnType); }
[ "public", "ApiResponse", "<", "Object", ">", "retrievePCTokenUsingPOSTWithHttpInfo", "(", ")", "throws", "ApiException", "{", "com", ".", "squareup", ".", "okhttp", ".", "Call", "call", "=", "retrievePCTokenUsingPOSTValidateBeforeCall", "(", "null", ",", "null", ")", ";", "Type", "localVarReturnType", "=", "new", "TypeToken", "<", "Object", ">", "(", ")", "{", "}", ".", "getType", "(", ")", ";", "return", "apiClient", ".", "execute", "(", "call", ",", "localVarReturnType", ")", ";", "}" ]
Retrieve PC token Returns PC token @return ApiResponse&lt;Object&gt; @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
[ "Retrieve", "PC", "token", "Returns", "PC", "token" ]
eb0d58343ee42ebd3c037163c1137f611dfcbb3a
https://github.com/GenesysPureEngage/authentication-client-java/blob/eb0d58343ee42ebd3c037163c1137f611dfcbb3a/src/main/java/com/genesys/internal/authentication/api/AuthenticationApi.java#L910-L914
144,024
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/CustomFunctions.java
CustomFunctions.field
public static String field(EvaluationContext ctx, Object text, Object index, @StringDefault(" ") Object delimiter) { String _text = Conversions.toString(text, ctx); int _index = Conversions.toInteger(index, ctx); String _delimiter = Conversions.toString(delimiter, ctx); String[] splits = StringUtils.splitByWholeSeparator(_text, _delimiter); if (_index < 1) { throw new RuntimeException("Field index cannot be less than 1"); } if (_index <= splits.length) { return splits[_index - 1]; } else { return ""; } }
java
public static String field(EvaluationContext ctx, Object text, Object index, @StringDefault(" ") Object delimiter) { String _text = Conversions.toString(text, ctx); int _index = Conversions.toInteger(index, ctx); String _delimiter = Conversions.toString(delimiter, ctx); String[] splits = StringUtils.splitByWholeSeparator(_text, _delimiter); if (_index < 1) { throw new RuntimeException("Field index cannot be less than 1"); } if (_index <= splits.length) { return splits[_index - 1]; } else { return ""; } }
[ "public", "static", "String", "field", "(", "EvaluationContext", "ctx", ",", "Object", "text", ",", "Object", "index", ",", "@", "StringDefault", "(", "\" \"", ")", "Object", "delimiter", ")", "{", "String", "_text", "=", "Conversions", ".", "toString", "(", "text", ",", "ctx", ")", ";", "int", "_index", "=", "Conversions", ".", "toInteger", "(", "index", ",", "ctx", ")", ";", "String", "_delimiter", "=", "Conversions", ".", "toString", "(", "delimiter", ",", "ctx", ")", ";", "String", "[", "]", "splits", "=", "StringUtils", ".", "splitByWholeSeparator", "(", "_text", ",", "_delimiter", ")", ";", "if", "(", "_index", "<", "1", ")", "{", "throw", "new", "RuntimeException", "(", "\"Field index cannot be less than 1\"", ")", ";", "}", "if", "(", "_index", "<=", "splits", ".", "length", ")", "{", "return", "splits", "[", "_index", "-", "1", "]", ";", "}", "else", "{", "return", "\"\"", ";", "}", "}" ]
Reference a field in string separated by a delimiter
[ "Reference", "a", "field", "in", "string", "separated", "by", "a", "delimiter" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/CustomFunctions.java#L26-L42
144,025
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/CustomFunctions.java
CustomFunctions.first_word
public static String first_word(EvaluationContext ctx, Object text) { // In Excel this would be IF(ISERR(FIND(" ",A2)),"",LEFT(A2,FIND(" ",A2)-1)) return word(ctx, text, 1, false); }
java
public static String first_word(EvaluationContext ctx, Object text) { // In Excel this would be IF(ISERR(FIND(" ",A2)),"",LEFT(A2,FIND(" ",A2)-1)) return word(ctx, text, 1, false); }
[ "public", "static", "String", "first_word", "(", "EvaluationContext", "ctx", ",", "Object", "text", ")", "{", "// In Excel this would be IF(ISERR(FIND(\" \",A2)),\"\",LEFT(A2,FIND(\" \",A2)-1))", "return", "word", "(", "ctx", ",", "text", ",", "1", ",", "false", ")", ";", "}" ]
Returns the first word in the given text string
[ "Returns", "the", "first", "word", "in", "the", "given", "text", "string" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/CustomFunctions.java#L47-L50
144,026
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/CustomFunctions.java
CustomFunctions.percent
public static String percent(EvaluationContext ctx, Object number) { BigDecimal percent = Conversions.toDecimal(number, ctx).multiply(new BigDecimal(100)); return Conversions.toInteger(percent, ctx) + "%"; }
java
public static String percent(EvaluationContext ctx, Object number) { BigDecimal percent = Conversions.toDecimal(number, ctx).multiply(new BigDecimal(100)); return Conversions.toInteger(percent, ctx) + "%"; }
[ "public", "static", "String", "percent", "(", "EvaluationContext", "ctx", ",", "Object", "number", ")", "{", "BigDecimal", "percent", "=", "Conversions", ".", "toDecimal", "(", "number", ",", "ctx", ")", ".", "multiply", "(", "new", "BigDecimal", "(", "100", ")", ")", ";", "return", "Conversions", ".", "toInteger", "(", "percent", ",", "ctx", ")", "+", "\"%\"", ";", "}" ]
Formats a number as a percentage
[ "Formats", "a", "number", "as", "a", "percentage" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/CustomFunctions.java#L55-L58
144,027
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/CustomFunctions.java
CustomFunctions.epoch
public static BigDecimal epoch(EvaluationContext ctx, Object datetime) { Instant instant = Conversions.toDateTime(datetime, ctx).toInstant(); BigDecimal nanos = new BigDecimal(instant.getEpochSecond() * 1000000000 + instant.getNano()); return nanos.divide(new BigDecimal(1000000000)); }
java
public static BigDecimal epoch(EvaluationContext ctx, Object datetime) { Instant instant = Conversions.toDateTime(datetime, ctx).toInstant(); BigDecimal nanos = new BigDecimal(instant.getEpochSecond() * 1000000000 + instant.getNano()); return nanos.divide(new BigDecimal(1000000000)); }
[ "public", "static", "BigDecimal", "epoch", "(", "EvaluationContext", "ctx", ",", "Object", "datetime", ")", "{", "Instant", "instant", "=", "Conversions", ".", "toDateTime", "(", "datetime", ",", "ctx", ")", ".", "toInstant", "(", ")", ";", "BigDecimal", "nanos", "=", "new", "BigDecimal", "(", "instant", ".", "getEpochSecond", "(", ")", "*", "1000000000", "+", "instant", ".", "getNano", "(", ")", ")", ";", "return", "nanos", ".", "divide", "(", "new", "BigDecimal", "(", "1000000000", ")", ")", ";", "}" ]
Converts the given date to the number of nanoseconds since January 1st, 1970 UTC
[ "Converts", "the", "given", "date", "to", "the", "number", "of", "nanoseconds", "since", "January", "1st", "1970", "UTC" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/CustomFunctions.java#L63-L67
144,028
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/CustomFunctions.java
CustomFunctions.read_digits
public static String read_digits(EvaluationContext ctx, Object text) { String _text = Conversions.toString(text, ctx).trim(); if (StringUtils.isEmpty(_text)) { return ""; } // trim off the plus for phone numbers if (_text.startsWith("+")) { _text = _text.substring(1); } if (_text.length() == 9) { // SSN return StringUtils.join(_text.substring(0, 3).toCharArray(), ' ') + " , " + StringUtils.join(_text.substring(3, 5).toCharArray(), ' ') + " , " + StringUtils.join(_text.substring(5).toCharArray(), ' '); } else if (_text.length() % 3 == 0 && _text.length() > 3) { // triplets, most international phone numbers List<String> chunks = chunk(_text, 3); return StringUtils.join(StringUtils.join(chunks, ',').toCharArray(), ' '); } else if (_text.length() % 4 == 0) { // quads, credit cards List<String> chunks = chunk(_text, 4); return StringUtils.join(StringUtils.join(chunks, ',').toCharArray(), ' '); } else { // otherwise, just put a comma between each number return StringUtils.join(_text.toCharArray(), ','); } }
java
public static String read_digits(EvaluationContext ctx, Object text) { String _text = Conversions.toString(text, ctx).trim(); if (StringUtils.isEmpty(_text)) { return ""; } // trim off the plus for phone numbers if (_text.startsWith("+")) { _text = _text.substring(1); } if (_text.length() == 9) { // SSN return StringUtils.join(_text.substring(0, 3).toCharArray(), ' ') + " , " + StringUtils.join(_text.substring(3, 5).toCharArray(), ' ') + " , " + StringUtils.join(_text.substring(5).toCharArray(), ' '); } else if (_text.length() % 3 == 0 && _text.length() > 3) { // triplets, most international phone numbers List<String> chunks = chunk(_text, 3); return StringUtils.join(StringUtils.join(chunks, ',').toCharArray(), ' '); } else if (_text.length() % 4 == 0) { // quads, credit cards List<String> chunks = chunk(_text, 4); return StringUtils.join(StringUtils.join(chunks, ',').toCharArray(), ' '); } else { // otherwise, just put a comma between each number return StringUtils.join(_text.toCharArray(), ','); } }
[ "public", "static", "String", "read_digits", "(", "EvaluationContext", "ctx", ",", "Object", "text", ")", "{", "String", "_text", "=", "Conversions", ".", "toString", "(", "text", ",", "ctx", ")", ".", "trim", "(", ")", ";", "if", "(", "StringUtils", ".", "isEmpty", "(", "_text", ")", ")", "{", "return", "\"\"", ";", "}", "// trim off the plus for phone numbers", "if", "(", "_text", ".", "startsWith", "(", "\"+\"", ")", ")", "{", "_text", "=", "_text", ".", "substring", "(", "1", ")", ";", "}", "if", "(", "_text", ".", "length", "(", ")", "==", "9", ")", "{", "// SSN", "return", "StringUtils", ".", "join", "(", "_text", ".", "substring", "(", "0", ",", "3", ")", ".", "toCharArray", "(", ")", ",", "'", "'", ")", "+", "\" , \"", "+", "StringUtils", ".", "join", "(", "_text", ".", "substring", "(", "3", ",", "5", ")", ".", "toCharArray", "(", ")", ",", "'", "'", ")", "+", "\" , \"", "+", "StringUtils", ".", "join", "(", "_text", ".", "substring", "(", "5", ")", ".", "toCharArray", "(", ")", ",", "'", "'", ")", ";", "}", "else", "if", "(", "_text", ".", "length", "(", ")", "%", "3", "==", "0", "&&", "_text", ".", "length", "(", ")", ">", "3", ")", "{", "// triplets, most international phone numbers", "List", "<", "String", ">", "chunks", "=", "chunk", "(", "_text", ",", "3", ")", ";", "return", "StringUtils", ".", "join", "(", "StringUtils", ".", "join", "(", "chunks", ",", "'", "'", ")", ".", "toCharArray", "(", ")", ",", "'", "'", ")", ";", "}", "else", "if", "(", "_text", ".", "length", "(", ")", "%", "4", "==", "0", ")", "{", "// quads, credit cards", "List", "<", "String", ">", "chunks", "=", "chunk", "(", "_text", ",", "4", ")", ";", "return", "StringUtils", ".", "join", "(", "StringUtils", ".", "join", "(", "chunks", ",", "'", "'", ")", ".", "toCharArray", "(", ")", ",", "'", "'", ")", ";", "}", "else", "{", "// otherwise, just put a comma between each number", "return", "StringUtils", ".", "join", "(", "_text", ".", "toCharArray", "(", ")", ",", "'", "'", ")", ";", "}", "}" ]
Formats digits in text for reading in TTS
[ "Formats", "digits", "in", "text", "for", "reading", "in", "TTS" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/CustomFunctions.java#L72-L100
144,029
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/CustomFunctions.java
CustomFunctions.remove_first_word
public static String remove_first_word(EvaluationContext ctx, Object text) { String _text = StringUtils.stripStart(Conversions.toString(text, ctx), null); String firstWord = first_word(ctx, _text); if (StringUtils.isNotEmpty(firstWord)) { return StringUtils.stripStart(_text.substring(firstWord.length()), null); } else { return ""; } }
java
public static String remove_first_word(EvaluationContext ctx, Object text) { String _text = StringUtils.stripStart(Conversions.toString(text, ctx), null); String firstWord = first_word(ctx, _text); if (StringUtils.isNotEmpty(firstWord)) { return StringUtils.stripStart(_text.substring(firstWord.length()), null); } else { return ""; } }
[ "public", "static", "String", "remove_first_word", "(", "EvaluationContext", "ctx", ",", "Object", "text", ")", "{", "String", "_text", "=", "StringUtils", ".", "stripStart", "(", "Conversions", ".", "toString", "(", "text", ",", "ctx", ")", ",", "null", ")", ";", "String", "firstWord", "=", "first_word", "(", "ctx", ",", "_text", ")", ";", "if", "(", "StringUtils", ".", "isNotEmpty", "(", "firstWord", ")", ")", "{", "return", "StringUtils", ".", "stripStart", "(", "_text", ".", "substring", "(", "firstWord", ".", "length", "(", ")", ")", ",", "null", ")", ";", "}", "else", "{", "return", "\"\"", ";", "}", "}" ]
Removes the first word from the given text string
[ "Removes", "the", "first", "word", "from", "the", "given", "text", "string" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/CustomFunctions.java#L105-L114
144,030
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/CustomFunctions.java
CustomFunctions.word
public static String word(EvaluationContext ctx, Object text, Object number, @BooleanDefault(false) Object bySpaces) { return word_slice(ctx, text, number, Conversions.toInteger(number, ctx) + 1, bySpaces); }
java
public static String word(EvaluationContext ctx, Object text, Object number, @BooleanDefault(false) Object bySpaces) { return word_slice(ctx, text, number, Conversions.toInteger(number, ctx) + 1, bySpaces); }
[ "public", "static", "String", "word", "(", "EvaluationContext", "ctx", ",", "Object", "text", ",", "Object", "number", ",", "@", "BooleanDefault", "(", "false", ")", "Object", "bySpaces", ")", "{", "return", "word_slice", "(", "ctx", ",", "text", ",", "number", ",", "Conversions", ".", "toInteger", "(", "number", ",", "ctx", ")", "+", "1", ",", "bySpaces", ")", ";", "}" ]
Extracts the nth word from the given text string
[ "Extracts", "the", "nth", "word", "from", "the", "given", "text", "string" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/CustomFunctions.java#L119-L121
144,031
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/CustomFunctions.java
CustomFunctions.word_count
public static int word_count(EvaluationContext ctx, Object text, @BooleanDefault(false) Object bySpaces) { String _text = Conversions.toString(text, ctx); boolean _bySpaces = Conversions.toBoolean(bySpaces, ctx); return getWords(_text, _bySpaces).size(); }
java
public static int word_count(EvaluationContext ctx, Object text, @BooleanDefault(false) Object bySpaces) { String _text = Conversions.toString(text, ctx); boolean _bySpaces = Conversions.toBoolean(bySpaces, ctx); return getWords(_text, _bySpaces).size(); }
[ "public", "static", "int", "word_count", "(", "EvaluationContext", "ctx", ",", "Object", "text", ",", "@", "BooleanDefault", "(", "false", ")", "Object", "bySpaces", ")", "{", "String", "_text", "=", "Conversions", ".", "toString", "(", "text", ",", "ctx", ")", ";", "boolean", "_bySpaces", "=", "Conversions", ".", "toBoolean", "(", "bySpaces", ",", "ctx", ")", ";", "return", "getWords", "(", "_text", ",", "_bySpaces", ")", ".", "size", "(", ")", ";", "}" ]
Returns the number of words in the given text string
[ "Returns", "the", "number", "of", "words", "in", "the", "given", "text", "string" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/CustomFunctions.java#L126-L130
144,032
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/CustomFunctions.java
CustomFunctions.word_slice
public static String word_slice(EvaluationContext ctx, Object text, Object start, @IntegerDefault(0) Object stop, @BooleanDefault(false) Object bySpaces) { String _text = Conversions.toString(text, ctx); int _start = Conversions.toInteger(start, ctx); Integer _stop = Conversions.toInteger(stop, ctx); boolean _bySpaces = Conversions.toBoolean(bySpaces, ctx); if (_start == 0) { throw new RuntimeException("Start word cannot be zero"); } else if (_start > 0) { _start -= 1; // convert to a zero-based offset } if (_stop == 0) { // zero is treated as no end _stop = null; } else if (_stop > 0) { _stop -= 1; // convert to a zero-based offset } List<String> words = getWords(_text, _bySpaces); List<String> selection = ExpressionUtils.slice(words, _start, _stop); // re-combine selected words with a single space return StringUtils.join(selection, ' '); }
java
public static String word_slice(EvaluationContext ctx, Object text, Object start, @IntegerDefault(0) Object stop, @BooleanDefault(false) Object bySpaces) { String _text = Conversions.toString(text, ctx); int _start = Conversions.toInteger(start, ctx); Integer _stop = Conversions.toInteger(stop, ctx); boolean _bySpaces = Conversions.toBoolean(bySpaces, ctx); if (_start == 0) { throw new RuntimeException("Start word cannot be zero"); } else if (_start > 0) { _start -= 1; // convert to a zero-based offset } if (_stop == 0) { // zero is treated as no end _stop = null; } else if (_stop > 0) { _stop -= 1; // convert to a zero-based offset } List<String> words = getWords(_text, _bySpaces); List<String> selection = ExpressionUtils.slice(words, _start, _stop); // re-combine selected words with a single space return StringUtils.join(selection, ' '); }
[ "public", "static", "String", "word_slice", "(", "EvaluationContext", "ctx", ",", "Object", "text", ",", "Object", "start", ",", "@", "IntegerDefault", "(", "0", ")", "Object", "stop", ",", "@", "BooleanDefault", "(", "false", ")", "Object", "bySpaces", ")", "{", "String", "_text", "=", "Conversions", ".", "toString", "(", "text", ",", "ctx", ")", ";", "int", "_start", "=", "Conversions", ".", "toInteger", "(", "start", ",", "ctx", ")", ";", "Integer", "_stop", "=", "Conversions", ".", "toInteger", "(", "stop", ",", "ctx", ")", ";", "boolean", "_bySpaces", "=", "Conversions", ".", "toBoolean", "(", "bySpaces", ",", "ctx", ")", ";", "if", "(", "_start", "==", "0", ")", "{", "throw", "new", "RuntimeException", "(", "\"Start word cannot be zero\"", ")", ";", "}", "else", "if", "(", "_start", ">", "0", ")", "{", "_start", "-=", "1", ";", "// convert to a zero-based offset", "}", "if", "(", "_stop", "==", "0", ")", "{", "// zero is treated as no end", "_stop", "=", "null", ";", "}", "else", "if", "(", "_stop", ">", "0", ")", "{", "_stop", "-=", "1", ";", "// convert to a zero-based offset", "}", "List", "<", "String", ">", "words", "=", "getWords", "(", "_text", ",", "_bySpaces", ")", ";", "List", "<", "String", ">", "selection", "=", "ExpressionUtils", ".", "slice", "(", "words", ",", "_start", ",", "_stop", ")", ";", "// re-combine selected words with a single space", "return", "StringUtils", ".", "join", "(", "selection", ",", "'", "'", ")", ";", "}" ]
Extracts a substring spanning from start up to but not-including stop
[ "Extracts", "a", "substring", "spanning", "from", "start", "up", "to", "but", "not", "-", "including", "stop" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/CustomFunctions.java#L135-L158
144,033
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/CustomFunctions.java
CustomFunctions.format_date
public static String format_date(EvaluationContext ctx, Object text) { ZonedDateTime _dt = Conversions.toDateTime(text, ctx).withZoneSameInstant(ctx.getTimezone()); return ctx.getDateFormatter(true).format(_dt); }
java
public static String format_date(EvaluationContext ctx, Object text) { ZonedDateTime _dt = Conversions.toDateTime(text, ctx).withZoneSameInstant(ctx.getTimezone()); return ctx.getDateFormatter(true).format(_dt); }
[ "public", "static", "String", "format_date", "(", "EvaluationContext", "ctx", ",", "Object", "text", ")", "{", "ZonedDateTime", "_dt", "=", "Conversions", ".", "toDateTime", "(", "text", ",", "ctx", ")", ".", "withZoneSameInstant", "(", "ctx", ".", "getTimezone", "(", ")", ")", ";", "return", "ctx", ".", "getDateFormatter", "(", "true", ")", ".", "format", "(", "_dt", ")", ";", "}" ]
Formats a date according to the default org format
[ "Formats", "a", "date", "according", "to", "the", "default", "org", "format" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/CustomFunctions.java#L163-L166
144,034
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/CustomFunctions.java
CustomFunctions.regex_group
public static String regex_group(EvaluationContext ctx, Object text, Object pattern, Object groupNum) { String _text = Conversions.toString(text, ctx); String _pattern = Conversions.toString(pattern, ctx); int _groupNum = Conversions.toInteger(groupNum, ctx); try { // check whether we match int flags = Pattern.CASE_INSENSITIVE | Pattern.MULTILINE; Pattern regex = Pattern.compile(_pattern, flags); Matcher matcher = regex.matcher(_text); if (matcher.find()) { if (_groupNum < 0 || _groupNum > matcher.groupCount()) { throw new RuntimeException("No such matching group " + _groupNum); } return matcher.group(_groupNum); } } catch (PatternSyntaxException ignored) {} return ""; }
java
public static String regex_group(EvaluationContext ctx, Object text, Object pattern, Object groupNum) { String _text = Conversions.toString(text, ctx); String _pattern = Conversions.toString(pattern, ctx); int _groupNum = Conversions.toInteger(groupNum, ctx); try { // check whether we match int flags = Pattern.CASE_INSENSITIVE | Pattern.MULTILINE; Pattern regex = Pattern.compile(_pattern, flags); Matcher matcher = regex.matcher(_text); if (matcher.find()) { if (_groupNum < 0 || _groupNum > matcher.groupCount()) { throw new RuntimeException("No such matching group " + _groupNum); } return matcher.group(_groupNum); } } catch (PatternSyntaxException ignored) {} return ""; }
[ "public", "static", "String", "regex_group", "(", "EvaluationContext", "ctx", ",", "Object", "text", ",", "Object", "pattern", ",", "Object", "groupNum", ")", "{", "String", "_text", "=", "Conversions", ".", "toString", "(", "text", ",", "ctx", ")", ";", "String", "_pattern", "=", "Conversions", ".", "toString", "(", "pattern", ",", "ctx", ")", ";", "int", "_groupNum", "=", "Conversions", ".", "toInteger", "(", "groupNum", ",", "ctx", ")", ";", "try", "{", "// check whether we match", "int", "flags", "=", "Pattern", ".", "CASE_INSENSITIVE", "|", "Pattern", ".", "MULTILINE", ";", "Pattern", "regex", "=", "Pattern", ".", "compile", "(", "_pattern", ",", "flags", ")", ";", "Matcher", "matcher", "=", "regex", ".", "matcher", "(", "_text", ")", ";", "if", "(", "matcher", ".", "find", "(", ")", ")", "{", "if", "(", "_groupNum", "<", "0", "||", "_groupNum", ">", "matcher", ".", "groupCount", "(", ")", ")", "{", "throw", "new", "RuntimeException", "(", "\"No such matching group \"", "+", "_groupNum", ")", ";", "}", "return", "matcher", ".", "group", "(", "_groupNum", ")", ";", "}", "}", "catch", "(", "PatternSyntaxException", "ignored", ")", "{", "}", "return", "\"\"", ";", "}" ]
Tries to match the text with the given pattern and returns the value of matching group
[ "Tries", "to", "match", "the", "text", "with", "the", "given", "pattern", "and", "returns", "the", "value", "of", "matching", "group" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/CustomFunctions.java#L180-L201
144,035
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/CustomFunctions.java
CustomFunctions.getWords
private static List<String> getWords(String text, boolean bySpaces) { if (bySpaces) { List<String> words = new ArrayList<>(); for (String split : text.split("\\s+")) { if (StringUtils.isNotEmpty(split)) { words.add(split); } } return words; } else { return Arrays.asList(ExpressionUtils.tokenize(text)); } }
java
private static List<String> getWords(String text, boolean bySpaces) { if (bySpaces) { List<String> words = new ArrayList<>(); for (String split : text.split("\\s+")) { if (StringUtils.isNotEmpty(split)) { words.add(split); } } return words; } else { return Arrays.asList(ExpressionUtils.tokenize(text)); } }
[ "private", "static", "List", "<", "String", ">", "getWords", "(", "String", "text", ",", "boolean", "bySpaces", ")", "{", "if", "(", "bySpaces", ")", "{", "List", "<", "String", ">", "words", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "String", "split", ":", "text", ".", "split", "(", "\"\\\\s+\"", ")", ")", "{", "if", "(", "StringUtils", ".", "isNotEmpty", "(", "split", ")", ")", "{", "words", ".", "add", "(", "split", ")", ";", "}", "}", "return", "words", ";", "}", "else", "{", "return", "Arrays", ".", "asList", "(", "ExpressionUtils", ".", "tokenize", "(", "text", ")", ")", ";", "}", "}" ]
Helper function which splits the given text string into words. If by_spaces is false, then text like '01-02-2014' will be split into 3 separate words. For backwards compatibility, this is the default for all expression functions. @param text the text to split @param bySpaces whether words should be split only by spaces or by punctuation like '-', '.' etc @return the words as a list of strings
[ "Helper", "function", "which", "splits", "the", "given", "text", "string", "into", "words", ".", "If", "by_spaces", "is", "false", "then", "text", "like", "01", "-", "02", "-", "2014", "will", "be", "split", "into", "3", "separate", "words", ".", "For", "backwards", "compatibility", "this", "is", "the", "default", "for", "all", "expression", "functions", "." ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/CustomFunctions.java#L214-L226
144,036
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/CustomFunctions.java
CustomFunctions.chunk
private static List<String> chunk(String text, int size) { List<String> chunks = new ArrayList<>(); for (int i = 0; i < text.length(); i += size) { chunks.add(StringUtils.substring(text, i, i + size)); } return chunks; }
java
private static List<String> chunk(String text, int size) { List<String> chunks = new ArrayList<>(); for (int i = 0; i < text.length(); i += size) { chunks.add(StringUtils.substring(text, i, i + size)); } return chunks; }
[ "private", "static", "List", "<", "String", ">", "chunk", "(", "String", "text", ",", "int", "size", ")", "{", "List", "<", "String", ">", "chunks", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "text", ".", "length", "(", ")", ";", "i", "+=", "size", ")", "{", "chunks", ".", "add", "(", "StringUtils", ".", "substring", "(", "text", ",", "i", ",", "i", "+", "size", ")", ")", ";", "}", "return", "chunks", ";", "}" ]
Splits a string into equally sized chunks @param text the text to split @param size the chunk size @return the list of chunks
[ "Splits", "a", "string", "into", "equally", "sized", "chunks" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/CustomFunctions.java#L234-L240
144,037
RestExpress/PluginExpress
cors/src/main/java/com/strategicgains/restexpress/plugin/cors/CorsHeaderPlugin.java
CorsHeaderPlugin.flag
public CorsHeaderPlugin flag(String flagValue) { if (isRegistered()) throw new UnsupportedOperationException("CorsHeaderPlugin.flag(String) must be called before register()"); if (!flags.contains(flagValue)) { flags.add(flagValue); } return this; }
java
public CorsHeaderPlugin flag(String flagValue) { if (isRegistered()) throw new UnsupportedOperationException("CorsHeaderPlugin.flag(String) must be called before register()"); if (!flags.contains(flagValue)) { flags.add(flagValue); } return this; }
[ "public", "CorsHeaderPlugin", "flag", "(", "String", "flagValue", ")", "{", "if", "(", "isRegistered", "(", ")", ")", "throw", "new", "UnsupportedOperationException", "(", "\"CorsHeaderPlugin.flag(String) must be called before register()\"", ")", ";", "if", "(", "!", "flags", ".", "contains", "(", "flagValue", ")", ")", "{", "flags", ".", "add", "(", "flagValue", ")", ";", "}", "return", "this", ";", "}" ]
Set a flag on the automatically generated OPTIONS route for pre-flight CORS requests. @param flagValue @return a reference to this plugin to support method chaining.
[ "Set", "a", "flag", "on", "the", "automatically", "generated", "OPTIONS", "route", "for", "pre", "-", "flight", "CORS", "requests", "." ]
aeb13907c23bf31ef2b2b17ae4c0ca4a6f5bee69
https://github.com/RestExpress/PluginExpress/blob/aeb13907c23bf31ef2b2b17ae4c0ca4a6f5bee69/cors/src/main/java/com/strategicgains/restexpress/plugin/cors/CorsHeaderPlugin.java#L135-L145
144,038
RestExpress/PluginExpress
cors/src/main/java/com/strategicgains/restexpress/plugin/cors/CorsHeaderPlugin.java
CorsHeaderPlugin.addPreflightOptionsRequestSupport
private void addPreflightOptionsRequestSupport(RestExpress server, CorsOptionsController corsOptionsController) { RouteBuilder rb; for (String pattern : methodsByPattern.keySet()) { rb = server.uri(pattern, corsOptionsController) .action("options", HttpMethod.OPTIONS) .noSerialization() // Disable both authentication and authorization which are usually use header such as X-Authorization. // When browser does CORS preflight with OPTIONS request, such headers are not included. .flag(Flags.Auth.PUBLIC_ROUTE) .flag(Flags.Auth.NO_AUTHORIZATION); for (String flag : flags) { rb.flag(flag); } for (Entry<String, Object> entry : parameters.entrySet()) { rb.parameter(entry.getKey(), entry.getValue()); } routeBuilders.add(rb); } }
java
private void addPreflightOptionsRequestSupport(RestExpress server, CorsOptionsController corsOptionsController) { RouteBuilder rb; for (String pattern : methodsByPattern.keySet()) { rb = server.uri(pattern, corsOptionsController) .action("options", HttpMethod.OPTIONS) .noSerialization() // Disable both authentication and authorization which are usually use header such as X-Authorization. // When browser does CORS preflight with OPTIONS request, such headers are not included. .flag(Flags.Auth.PUBLIC_ROUTE) .flag(Flags.Auth.NO_AUTHORIZATION); for (String flag : flags) { rb.flag(flag); } for (Entry<String, Object> entry : parameters.entrySet()) { rb.parameter(entry.getKey(), entry.getValue()); } routeBuilders.add(rb); } }
[ "private", "void", "addPreflightOptionsRequestSupport", "(", "RestExpress", "server", ",", "CorsOptionsController", "corsOptionsController", ")", "{", "RouteBuilder", "rb", ";", "for", "(", "String", "pattern", ":", "methodsByPattern", ".", "keySet", "(", ")", ")", "{", "rb", "=", "server", ".", "uri", "(", "pattern", ",", "corsOptionsController", ")", ".", "action", "(", "\"options\"", ",", "HttpMethod", ".", "OPTIONS", ")", ".", "noSerialization", "(", ")", "// Disable both authentication and authorization which are usually use header such as X-Authorization.", "// When browser does CORS preflight with OPTIONS request, such headers are not included.", ".", "flag", "(", "Flags", ".", "Auth", ".", "PUBLIC_ROUTE", ")", ".", "flag", "(", "Flags", ".", "Auth", ".", "NO_AUTHORIZATION", ")", ";", "for", "(", "String", "flag", ":", "flags", ")", "{", "rb", ".", "flag", "(", "flag", ")", ";", "}", "for", "(", "Entry", "<", "String", ",", "Object", ">", "entry", ":", "parameters", ".", "entrySet", "(", ")", ")", "{", "rb", ".", "parameter", "(", "entry", ".", "getKey", "(", ")", ",", "entry", ".", "getValue", "(", ")", ")", ";", "}", "routeBuilders", ".", "add", "(", "rb", ")", ";", "}", "}" ]
Add an 'OPTIONS' method supported on all routes for the pre-flight CORS request. @param server a RestExpress server instance.
[ "Add", "an", "OPTIONS", "method", "supported", "on", "all", "routes", "for", "the", "pre", "-", "flight", "CORS", "request", "." ]
aeb13907c23bf31ef2b2b17ae4c0ca4a6f5bee69
https://github.com/RestExpress/PluginExpress/blob/aeb13907c23bf31ef2b2b17ae4c0ca4a6f5bee69/cors/src/main/java/com/strategicgains/restexpress/plugin/cors/CorsHeaderPlugin.java#L230-L256
144,039
RestExpress/PluginExpress
correlation-id/src/main/java/org/restexpress/plugin/correlationid/CorrelationIdPlugin.java
CorrelationIdPlugin.process
@Override public void process(Request request) { String correlationId = request.getHeader(CORRELATION_ID); // Generation on empty causes problems, since the request already has a value for Correlation-Id in this case. // The method call request.addHeader() only adds ANOTHER header to the request and doesn't fix the problem. // Currently then, the plugin only adds the header if it doesn't exist, assuming that if a client sets the // header to ANYTHING, that's the correlation ID they desired. if (correlationId == null) // || correlationId.trim().isEmpty()) { correlationId = UUID.randomUUID().toString(); } RequestContext.put(CORRELATION_ID, correlationId); request.addHeader(CORRELATION_ID, correlationId); }
java
@Override public void process(Request request) { String correlationId = request.getHeader(CORRELATION_ID); // Generation on empty causes problems, since the request already has a value for Correlation-Id in this case. // The method call request.addHeader() only adds ANOTHER header to the request and doesn't fix the problem. // Currently then, the plugin only adds the header if it doesn't exist, assuming that if a client sets the // header to ANYTHING, that's the correlation ID they desired. if (correlationId == null) // || correlationId.trim().isEmpty()) { correlationId = UUID.randomUUID().toString(); } RequestContext.put(CORRELATION_ID, correlationId); request.addHeader(CORRELATION_ID, correlationId); }
[ "@", "Override", "public", "void", "process", "(", "Request", "request", ")", "{", "String", "correlationId", "=", "request", ".", "getHeader", "(", "CORRELATION_ID", ")", ";", "// Generation on empty causes problems, since the request already has a value for Correlation-Id in this case.", "// The method call request.addHeader() only adds ANOTHER header to the request and doesn't fix the problem.", "// Currently then, the plugin only adds the header if it doesn't exist, assuming that if a client sets the", "// header to ANYTHING, that's the correlation ID they desired.", "if", "(", "correlationId", "==", "null", ")", "// || correlationId.trim().isEmpty())", "{", "correlationId", "=", "UUID", ".", "randomUUID", "(", ")", ".", "toString", "(", ")", ";", "}", "RequestContext", ".", "put", "(", "CORRELATION_ID", ",", "correlationId", ")", ";", "request", ".", "addHeader", "(", "CORRELATION_ID", ",", "correlationId", ")", ";", "}" ]
Preprocessor method to pull the Correlation-Id header or assign one as well as placing it in the RequestContext. @param request the incoming Request.
[ "Preprocessor", "method", "to", "pull", "the", "Correlation", "-", "Id", "header", "or", "assign", "one", "as", "well", "as", "placing", "it", "in", "the", "RequestContext", "." ]
aeb13907c23bf31ef2b2b17ae4c0ca4a6f5bee69
https://github.com/RestExpress/PluginExpress/blob/aeb13907c23bf31ef2b2b17ae4c0ca4a6f5bee69/correlation-id/src/main/java/org/restexpress/plugin/correlationid/CorrelationIdPlugin.java#L64-L80
144,040
RestExpress/PluginExpress
correlation-id/src/main/java/org/restexpress/plugin/correlationid/CorrelationIdPlugin.java
CorrelationIdPlugin.process
@Override public void process(Request request, Response response) { if (!response.hasHeader(CORRELATION_ID)) { response.addHeader(CORRELATION_ID, request.getHeader(CORRELATION_ID)); } }
java
@Override public void process(Request request, Response response) { if (!response.hasHeader(CORRELATION_ID)) { response.addHeader(CORRELATION_ID, request.getHeader(CORRELATION_ID)); } }
[ "@", "Override", "public", "void", "process", "(", "Request", "request", ",", "Response", "response", ")", "{", "if", "(", "!", "response", ".", "hasHeader", "(", "CORRELATION_ID", ")", ")", "{", "response", ".", "addHeader", "(", "CORRELATION_ID", ",", "request", ".", "getHeader", "(", "CORRELATION_ID", ")", ")", ";", "}", "}" ]
Postprocessor method that assigns the Correlation-Id from the request to a header on the Response. @param request the incoming Request. @param response the outgoing Response.
[ "Postprocessor", "method", "that", "assigns", "the", "Correlation", "-", "Id", "from", "the", "request", "to", "a", "header", "on", "the", "Response", "." ]
aeb13907c23bf31ef2b2b17ae4c0ca4a6f5bee69
https://github.com/RestExpress/PluginExpress/blob/aeb13907c23bf31ef2b2b17ae4c0ca4a6f5bee69/correlation-id/src/main/java/org/restexpress/plugin/correlationid/CorrelationIdPlugin.java#L89-L96
144,041
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/osgi/AbstractActivator.java
AbstractActivator.extractBundleContent
protected void extractBundleContent(String bundleRootPath, String toDirRoot) throws IOException { File toDir = new File(toDirRoot); if (!toDir.isDirectory()) { throw new RuntimeException("[" + toDir.getAbsolutePath() + "] is not a valid directory or does not exist!"); } toDir = new File(toDir, bundle.getSymbolicName()); toDir = new File(toDir, bundle.getVersion().toString()); FileUtils.forceMkdir(toDir); bundleExtractDir = toDir; Enumeration<String> entryPaths = bundle.getEntryPaths(bundleRootPath); if (entryPaths != null) { while (entryPaths.hasMoreElements()) { extractContent(bundleRootPath, entryPaths.nextElement(), bundleExtractDir); } } }
java
protected void extractBundleContent(String bundleRootPath, String toDirRoot) throws IOException { File toDir = new File(toDirRoot); if (!toDir.isDirectory()) { throw new RuntimeException("[" + toDir.getAbsolutePath() + "] is not a valid directory or does not exist!"); } toDir = new File(toDir, bundle.getSymbolicName()); toDir = new File(toDir, bundle.getVersion().toString()); FileUtils.forceMkdir(toDir); bundleExtractDir = toDir; Enumeration<String> entryPaths = bundle.getEntryPaths(bundleRootPath); if (entryPaths != null) { while (entryPaths.hasMoreElements()) { extractContent(bundleRootPath, entryPaths.nextElement(), bundleExtractDir); } } }
[ "protected", "void", "extractBundleContent", "(", "String", "bundleRootPath", ",", "String", "toDirRoot", ")", "throws", "IOException", "{", "File", "toDir", "=", "new", "File", "(", "toDirRoot", ")", ";", "if", "(", "!", "toDir", ".", "isDirectory", "(", ")", ")", "{", "throw", "new", "RuntimeException", "(", "\"[\"", "+", "toDir", ".", "getAbsolutePath", "(", ")", "+", "\"] is not a valid directory or does not exist!\"", ")", ";", "}", "toDir", "=", "new", "File", "(", "toDir", ",", "bundle", ".", "getSymbolicName", "(", ")", ")", ";", "toDir", "=", "new", "File", "(", "toDir", ",", "bundle", ".", "getVersion", "(", ")", ".", "toString", "(", ")", ")", ";", "FileUtils", ".", "forceMkdir", "(", "toDir", ")", ";", "bundleExtractDir", "=", "toDir", ";", "Enumeration", "<", "String", ">", "entryPaths", "=", "bundle", ".", "getEntryPaths", "(", "bundleRootPath", ")", ";", "if", "(", "entryPaths", "!=", "null", ")", "{", "while", "(", "entryPaths", ".", "hasMoreElements", "(", ")", ")", "{", "extractContent", "(", "bundleRootPath", ",", "entryPaths", ".", "nextElement", "(", ")", ",", "bundleExtractDir", ")", ";", "}", "}", "}" ]
Extracts content from the bundle to a directory. <p> Sub-class calls this method to extract all or part of bundle's content to a directory on disk. </p> <p> Note: bundle's content will be extracted to a sub-directory <code>toDirRoot/bundle_symbolic_name/bundle_version/</code> </p> @param bundleRootPath bundle's content under this path will be extracted @param toDirRoot bundle's content will be extracted to this directory @throws IOException
[ "Extracts", "content", "from", "the", "bundle", "to", "a", "directory", "." ]
734f0e77321d41eeca78a557be9884df9874e46e
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/osgi/AbstractActivator.java#L105-L122
144,042
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/osgi/AbstractActivator.java
AbstractActivator.handleAnotherVersionAtStartup
protected void handleAnotherVersionAtStartup(Bundle bundle) throws BundleException { Version myVersion = this.bundle.getVersion(); Version otherVersion = bundle.getVersion(); if (myVersion.compareTo(otherVersion) > 0) { handleNewerVersionAtStartup(bundle); } else { handleOlderVersionAtStartup(bundle); } }
java
protected void handleAnotherVersionAtStartup(Bundle bundle) throws BundleException { Version myVersion = this.bundle.getVersion(); Version otherVersion = bundle.getVersion(); if (myVersion.compareTo(otherVersion) > 0) { handleNewerVersionAtStartup(bundle); } else { handleOlderVersionAtStartup(bundle); } }
[ "protected", "void", "handleAnotherVersionAtStartup", "(", "Bundle", "bundle", ")", "throws", "BundleException", "{", "Version", "myVersion", "=", "this", ".", "bundle", ".", "getVersion", "(", ")", ";", "Version", "otherVersion", "=", "bundle", ".", "getVersion", "(", ")", ";", "if", "(", "myVersion", ".", "compareTo", "(", "otherVersion", ")", ">", "0", ")", "{", "handleNewerVersionAtStartup", "(", "bundle", ")", ";", "}", "else", "{", "handleOlderVersionAtStartup", "(", "bundle", ")", ";", "}", "}" ]
Called when another version of this bundle is found in the bundle context. <p> This method compares this bundle's version to the other bundle's version. If this bundle is newer, calls {@link #handleNewerVersionAtStartup(Bundle)}; otherwise calls {@link #handleOlderVersionAtStartup(Bundle)}. </p> @param bundle @since 0.1.2 @throws BundleException
[ "Called", "when", "another", "version", "of", "this", "bundle", "is", "found", "in", "the", "bundle", "context", "." ]
734f0e77321d41eeca78a557be9884df9874e46e
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/osgi/AbstractActivator.java#L242-L250
144,043
GeneralElectric/snowizard
snowizard-application/src/main/java/com/ge/snowizard/application/resources/IdResource.java
IdResource.getId
public long getId(final String agent) { try { return worker.getId(agent); } catch (final InvalidUserAgentError e) { LOGGER.error("Invalid user agent ({})", agent); throw new SnowizardException(Response.Status.BAD_REQUEST, "Invalid User-Agent header", e); } catch (final InvalidSystemClock e) { LOGGER.error("Invalid system clock", e); throw new SnowizardException(Response.Status.INTERNAL_SERVER_ERROR, e.getMessage(), e); } }
java
public long getId(final String agent) { try { return worker.getId(agent); } catch (final InvalidUserAgentError e) { LOGGER.error("Invalid user agent ({})", agent); throw new SnowizardException(Response.Status.BAD_REQUEST, "Invalid User-Agent header", e); } catch (final InvalidSystemClock e) { LOGGER.error("Invalid system clock", e); throw new SnowizardException(Response.Status.INTERNAL_SERVER_ERROR, e.getMessage(), e); } }
[ "public", "long", "getId", "(", "final", "String", "agent", ")", "{", "try", "{", "return", "worker", ".", "getId", "(", "agent", ")", ";", "}", "catch", "(", "final", "InvalidUserAgentError", "e", ")", "{", "LOGGER", ".", "error", "(", "\"Invalid user agent ({})\"", ",", "agent", ")", ";", "throw", "new", "SnowizardException", "(", "Response", ".", "Status", ".", "BAD_REQUEST", ",", "\"Invalid User-Agent header\"", ",", "e", ")", ";", "}", "catch", "(", "final", "InvalidSystemClock", "e", ")", "{", "LOGGER", ".", "error", "(", "\"Invalid system clock\"", ",", "e", ")", ";", "throw", "new", "SnowizardException", "(", "Response", ".", "Status", ".", "INTERNAL_SERVER_ERROR", ",", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "}", "}" ]
Get a new ID and handle any thrown exceptions @param agent User Agent @return generated ID @throws SnowizardException
[ "Get", "a", "new", "ID", "and", "handle", "any", "thrown", "exceptions" ]
307fdf17892275a56bb666aa1f577ca7cab327c6
https://github.com/GeneralElectric/snowizard/blob/307fdf17892275a56bb666aa1f577ca7cab327c6/snowizard-application/src/main/java/com/ge/snowizard/application/resources/IdResource.java#L54-L66
144,044
GeneralElectric/snowizard
snowizard-application/src/main/java/com/ge/snowizard/application/resources/IdResource.java
IdResource.getIdAsString
@GET @Timed @Produces(MediaType.TEXT_PLAIN) @CacheControl(mustRevalidate = true, noCache = true, noStore = true) public String getIdAsString( @HeaderParam(HttpHeaders.USER_AGENT) final String agent) { return String.valueOf(getId(agent)); }
java
@GET @Timed @Produces(MediaType.TEXT_PLAIN) @CacheControl(mustRevalidate = true, noCache = true, noStore = true) public String getIdAsString( @HeaderParam(HttpHeaders.USER_AGENT) final String agent) { return String.valueOf(getId(agent)); }
[ "@", "GET", "@", "Timed", "@", "Produces", "(", "MediaType", ".", "TEXT_PLAIN", ")", "@", "CacheControl", "(", "mustRevalidate", "=", "true", ",", "noCache", "=", "true", ",", "noStore", "=", "true", ")", "public", "String", "getIdAsString", "(", "@", "HeaderParam", "(", "HttpHeaders", ".", "USER_AGENT", ")", "final", "String", "agent", ")", "{", "return", "String", ".", "valueOf", "(", "getId", "(", "agent", ")", ")", ";", "}" ]
Get a new ID as plain text @param agent User Agent @return generated ID
[ "Get", "a", "new", "ID", "as", "plain", "text" ]
307fdf17892275a56bb666aa1f577ca7cab327c6
https://github.com/GeneralElectric/snowizard/blob/307fdf17892275a56bb666aa1f577ca7cab327c6/snowizard-application/src/main/java/com/ge/snowizard/application/resources/IdResource.java#L75-L82
144,045
GeneralElectric/snowizard
snowizard-application/src/main/java/com/ge/snowizard/application/resources/IdResource.java
IdResource.getIdAsJSON
@GET @Timed @JSONP(callback = "callback", queryParam = "callback") @Produces({ MediaType.APPLICATION_JSON, MediaTypeAdditional.APPLICATION_JAVASCRIPT }) @CacheControl(mustRevalidate = true, noCache = true, noStore = true) public Id getIdAsJSON( @HeaderParam(HttpHeaders.USER_AGENT) final String agent) { return new Id(getId(agent)); }
java
@GET @Timed @JSONP(callback = "callback", queryParam = "callback") @Produces({ MediaType.APPLICATION_JSON, MediaTypeAdditional.APPLICATION_JAVASCRIPT }) @CacheControl(mustRevalidate = true, noCache = true, noStore = true) public Id getIdAsJSON( @HeaderParam(HttpHeaders.USER_AGENT) final String agent) { return new Id(getId(agent)); }
[ "@", "GET", "@", "Timed", "@", "JSONP", "(", "callback", "=", "\"callback\"", ",", "queryParam", "=", "\"callback\"", ")", "@", "Produces", "(", "{", "MediaType", ".", "APPLICATION_JSON", ",", "MediaTypeAdditional", ".", "APPLICATION_JAVASCRIPT", "}", ")", "@", "CacheControl", "(", "mustRevalidate", "=", "true", ",", "noCache", "=", "true", ",", "noStore", "=", "true", ")", "public", "Id", "getIdAsJSON", "(", "@", "HeaderParam", "(", "HttpHeaders", ".", "USER_AGENT", ")", "final", "String", "agent", ")", "{", "return", "new", "Id", "(", "getId", "(", "agent", ")", ")", ";", "}" ]
Get a new ID as JSON @param agent User Agent @return generated ID
[ "Get", "a", "new", "ID", "as", "JSON" ]
307fdf17892275a56bb666aa1f577ca7cab327c6
https://github.com/GeneralElectric/snowizard/blob/307fdf17892275a56bb666aa1f577ca7cab327c6/snowizard-application/src/main/java/com/ge/snowizard/application/resources/IdResource.java#L91-L100
144,046
GeneralElectric/snowizard
snowizard-application/src/main/java/com/ge/snowizard/application/resources/IdResource.java
IdResource.getIdAsProtobuf
@GET @Timed @Produces(ProtocolBufferMediaType.APPLICATION_PROTOBUF) @CacheControl(mustRevalidate = true, noCache = true, noStore = true) public SnowizardResponse getIdAsProtobuf( @HeaderParam(HttpHeaders.USER_AGENT) final String agent, @QueryParam("count") final Optional<IntParam> count) { final List<Long> ids = Lists.newArrayList(); if (count.isPresent()) { for (int i = 0; i < count.get().get(); i++) { ids.add(getId(agent)); } } else { ids.add(getId(agent)); } return SnowizardResponse.newBuilder().addAllId(ids).build(); }
java
@GET @Timed @Produces(ProtocolBufferMediaType.APPLICATION_PROTOBUF) @CacheControl(mustRevalidate = true, noCache = true, noStore = true) public SnowizardResponse getIdAsProtobuf( @HeaderParam(HttpHeaders.USER_AGENT) final String agent, @QueryParam("count") final Optional<IntParam> count) { final List<Long> ids = Lists.newArrayList(); if (count.isPresent()) { for (int i = 0; i < count.get().get(); i++) { ids.add(getId(agent)); } } else { ids.add(getId(agent)); } return SnowizardResponse.newBuilder().addAllId(ids).build(); }
[ "@", "GET", "@", "Timed", "@", "Produces", "(", "ProtocolBufferMediaType", ".", "APPLICATION_PROTOBUF", ")", "@", "CacheControl", "(", "mustRevalidate", "=", "true", ",", "noCache", "=", "true", ",", "noStore", "=", "true", ")", "public", "SnowizardResponse", "getIdAsProtobuf", "(", "@", "HeaderParam", "(", "HttpHeaders", ".", "USER_AGENT", ")", "final", "String", "agent", ",", "@", "QueryParam", "(", "\"count\"", ")", "final", "Optional", "<", "IntParam", ">", "count", ")", "{", "final", "List", "<", "Long", ">", "ids", "=", "Lists", ".", "newArrayList", "(", ")", ";", "if", "(", "count", ".", "isPresent", "(", ")", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "count", ".", "get", "(", ")", ".", "get", "(", ")", ";", "i", "++", ")", "{", "ids", ".", "add", "(", "getId", "(", "agent", ")", ")", ";", "}", "}", "else", "{", "ids", ".", "add", "(", "getId", "(", "agent", ")", ")", ";", "}", "return", "SnowizardResponse", ".", "newBuilder", "(", ")", ".", "addAllId", "(", "ids", ")", ".", "build", "(", ")", ";", "}" ]
Get one or more IDs as a Google Protocol Buffer response @param agent User Agent @param count Number of IDs to return @return generated IDs
[ "Get", "one", "or", "more", "IDs", "as", "a", "Google", "Protocol", "Buffer", "response" ]
307fdf17892275a56bb666aa1f577ca7cab327c6
https://github.com/GeneralElectric/snowizard/blob/307fdf17892275a56bb666aa1f577ca7cab327c6/snowizard-application/src/main/java/com/ge/snowizard/application/resources/IdResource.java#L111-L128
144,047
RestExpress/PluginExpress
routes/src/main/java/com/strategicgains/restexpress/plugin/route/RoutesMetadataPlugin.java
RoutesMetadataPlugin.flag
public RoutesMetadataPlugin flag(String flagValue) { for (RouteBuilder routeBuilder : routeBuilders) { routeBuilder.flag(flagValue); } return this; }
java
public RoutesMetadataPlugin flag(String flagValue) { for (RouteBuilder routeBuilder : routeBuilders) { routeBuilder.flag(flagValue); } return this; }
[ "public", "RoutesMetadataPlugin", "flag", "(", "String", "flagValue", ")", "{", "for", "(", "RouteBuilder", "routeBuilder", ":", "routeBuilders", ")", "{", "routeBuilder", ".", "flag", "(", "flagValue", ")", ";", "}", "return", "this", ";", "}" ]
RouteBuilder route augmentation delegates.
[ "RouteBuilder", "route", "augmentation", "delegates", "." ]
aeb13907c23bf31ef2b2b17ae4c0ca4a6f5bee69
https://github.com/RestExpress/PluginExpress/blob/aeb13907c23bf31ef2b2b17ae4c0ca4a6f5bee69/routes/src/main/java/com/strategicgains/restexpress/plugin/route/RoutesMetadataPlugin.java#L84-L92
144,048
MGunlogson/CuckooFilter4J
src/main/java/com/github/mgunlogson/cuckoofilter4j/Utils.java
Utils.getBitsPerItemForFpRate
static int getBitsPerItemForFpRate(double fpProb,double loadFactor) { /* * equation from Cuckoo Filter: Practically Better Than Bloom Bin Fan, * David G. Andersen, Michael Kaminsky , Michael D. Mitzenmacher */ return DoubleMath.roundToInt(DoubleMath.log2((1 / fpProb) + 3) / loadFactor, RoundingMode.UP); }
java
static int getBitsPerItemForFpRate(double fpProb,double loadFactor) { /* * equation from Cuckoo Filter: Practically Better Than Bloom Bin Fan, * David G. Andersen, Michael Kaminsky , Michael D. Mitzenmacher */ return DoubleMath.roundToInt(DoubleMath.log2((1 / fpProb) + 3) / loadFactor, RoundingMode.UP); }
[ "static", "int", "getBitsPerItemForFpRate", "(", "double", "fpProb", ",", "double", "loadFactor", ")", "{", "/*\r\n\t\t * equation from Cuckoo Filter: Practically Better Than Bloom Bin Fan,\r\n\t\t * David G. Andersen, Michael Kaminsky , Michael D. Mitzenmacher\r\n\t\t */", "return", "DoubleMath", ".", "roundToInt", "(", "DoubleMath", ".", "log2", "(", "(", "1", "/", "fpProb", ")", "+", "3", ")", "/", "loadFactor", ",", "RoundingMode", ".", "UP", ")", ";", "}" ]
Calculates how many bits are needed to reach a given false positive rate. @param fpProb the false positive probability. @return the length of the tag needed (in bits) to reach the false positive rate.
[ "Calculates", "how", "many", "bits", "are", "needed", "to", "reach", "a", "given", "false", "positive", "rate", "." ]
e8472aa150b201f05046d1c81cac5a5ca4348db8
https://github.com/MGunlogson/CuckooFilter4J/blob/e8472aa150b201f05046d1c81cac5a5ca4348db8/src/main/java/com/github/mgunlogson/cuckoofilter4j/Utils.java#L148-L154
144,049
MGunlogson/CuckooFilter4J
src/main/java/com/github/mgunlogson/cuckoofilter4j/Utils.java
Utils.getBucketsNeeded
static long getBucketsNeeded(long maxKeys,double loadFactor,int bucketSize) { /* * force a power-of-two bucket count so hash functions for bucket index * can hashBits%numBuckets and get randomly distributed index. See wiki * "Modulo Bias". Only time we can get perfectly distributed index is * when numBuckets is a power of 2. */ long bucketsNeeded = DoubleMath.roundToLong((1.0 / loadFactor) * maxKeys / bucketSize, RoundingMode.UP); // get next biggest power of 2 long bitPos = Long.highestOneBit(bucketsNeeded); if (bucketsNeeded > bitPos) bitPos = bitPos << 1; return bitPos; }
java
static long getBucketsNeeded(long maxKeys,double loadFactor,int bucketSize) { /* * force a power-of-two bucket count so hash functions for bucket index * can hashBits%numBuckets and get randomly distributed index. See wiki * "Modulo Bias". Only time we can get perfectly distributed index is * when numBuckets is a power of 2. */ long bucketsNeeded = DoubleMath.roundToLong((1.0 / loadFactor) * maxKeys / bucketSize, RoundingMode.UP); // get next biggest power of 2 long bitPos = Long.highestOneBit(bucketsNeeded); if (bucketsNeeded > bitPos) bitPos = bitPos << 1; return bitPos; }
[ "static", "long", "getBucketsNeeded", "(", "long", "maxKeys", ",", "double", "loadFactor", ",", "int", "bucketSize", ")", "{", "/*\r\n\t\t * force a power-of-two bucket count so hash functions for bucket index\r\n\t\t * can hashBits%numBuckets and get randomly distributed index. See wiki\r\n\t\t * \"Modulo Bias\". Only time we can get perfectly distributed index is\r\n\t\t * when numBuckets is a power of 2.\r\n\t\t */", "long", "bucketsNeeded", "=", "DoubleMath", ".", "roundToLong", "(", "(", "1.0", "/", "loadFactor", ")", "*", "maxKeys", "/", "bucketSize", ",", "RoundingMode", ".", "UP", ")", ";", "// get next biggest power of 2\r", "long", "bitPos", "=", "Long", ".", "highestOneBit", "(", "bucketsNeeded", ")", ";", "if", "(", "bucketsNeeded", ">", "bitPos", ")", "bitPos", "=", "bitPos", "<<", "1", ";", "return", "bitPos", ";", "}" ]
Calculates how many buckets are needed to hold the chosen number of keys, taking the standard load factor into account. @param maxKeys the number of keys the filter is expected to hold before insertion failure. @return The number of buckets needed
[ "Calculates", "how", "many", "buckets", "are", "needed", "to", "hold", "the", "chosen", "number", "of", "keys", "taking", "the", "standard", "load", "factor", "into", "account", "." ]
e8472aa150b201f05046d1c81cac5a5ca4348db8
https://github.com/MGunlogson/CuckooFilter4J/blob/e8472aa150b201f05046d1c81cac5a5ca4348db8/src/main/java/com/github/mgunlogson/cuckoofilter4j/Utils.java#L165-L178
144,050
MGunlogson/CuckooFilter4J
src/main/java/com/github/mgunlogson/cuckoofilter4j/CuckooFilter.java
CuckooFilter.trySwapVictimIntoEmptySpot
private boolean trySwapVictimIntoEmptySpot() { long curIndex = victim.getI2(); // lock bucket. We always use I2 since victim tag is from bucket I1 bucketLocker.lockSingleBucketWrite(curIndex); long curTag = table.swapRandomTagInBucket(curIndex, victim.getTag()); bucketLocker.unlockSingleBucketWrite(curIndex); // new victim's I2 is different as long as tag isn't the same long altIndex = hasher.altIndex(curIndex, curTag); // try to insert the new victim tag in it's alternate bucket bucketLocker.lockSingleBucketWrite(altIndex); try { if (table.insertToBucket(altIndex, curTag)) { hasVictim = false; return true; } else { // still have a victim, but a different one... victim.setTag(curTag); // new victim always shares I1 with previous victims' I2 victim.setI1(curIndex); victim.setI2(altIndex); } } finally { bucketLocker.unlockSingleBucketWrite(altIndex); } return false; }
java
private boolean trySwapVictimIntoEmptySpot() { long curIndex = victim.getI2(); // lock bucket. We always use I2 since victim tag is from bucket I1 bucketLocker.lockSingleBucketWrite(curIndex); long curTag = table.swapRandomTagInBucket(curIndex, victim.getTag()); bucketLocker.unlockSingleBucketWrite(curIndex); // new victim's I2 is different as long as tag isn't the same long altIndex = hasher.altIndex(curIndex, curTag); // try to insert the new victim tag in it's alternate bucket bucketLocker.lockSingleBucketWrite(altIndex); try { if (table.insertToBucket(altIndex, curTag)) { hasVictim = false; return true; } else { // still have a victim, but a different one... victim.setTag(curTag); // new victim always shares I1 with previous victims' I2 victim.setI1(curIndex); victim.setI2(altIndex); } } finally { bucketLocker.unlockSingleBucketWrite(altIndex); } return false; }
[ "private", "boolean", "trySwapVictimIntoEmptySpot", "(", ")", "{", "long", "curIndex", "=", "victim", ".", "getI2", "(", ")", ";", "// lock bucket. We always use I2 since victim tag is from bucket I1\r", "bucketLocker", ".", "lockSingleBucketWrite", "(", "curIndex", ")", ";", "long", "curTag", "=", "table", ".", "swapRandomTagInBucket", "(", "curIndex", ",", "victim", ".", "getTag", "(", ")", ")", ";", "bucketLocker", ".", "unlockSingleBucketWrite", "(", "curIndex", ")", ";", "// new victim's I2 is different as long as tag isn't the same\r", "long", "altIndex", "=", "hasher", ".", "altIndex", "(", "curIndex", ",", "curTag", ")", ";", "// try to insert the new victim tag in it's alternate bucket\r", "bucketLocker", ".", "lockSingleBucketWrite", "(", "altIndex", ")", ";", "try", "{", "if", "(", "table", ".", "insertToBucket", "(", "altIndex", ",", "curTag", ")", ")", "{", "hasVictim", "=", "false", ";", "return", "true", ";", "}", "else", "{", "// still have a victim, but a different one...\r", "victim", ".", "setTag", "(", "curTag", ")", ";", "// new victim always shares I1 with previous victims' I2\r", "victim", ".", "setI1", "(", "curIndex", ")", ";", "victim", ".", "setI2", "(", "altIndex", ")", ";", "}", "}", "finally", "{", "bucketLocker", ".", "unlockSingleBucketWrite", "(", "altIndex", ")", ";", "}", "return", "false", ";", "}" ]
if we kicked a tag we need to move it to alternate position, possibly kicking another tag there, repeating the process until we succeed or run out of chances The basic flow below is to insert our current tag into a position in an already full bucket, then move the tag that we overwrote to it's alternate index. We repeat this until we move a tag into a non-full bucket or run out of attempts. This tag shuffling process is what gives the Cuckoo filter such a high load factor. When we run out of attempts, we leave the orphaned tag in the victim slot. We need to be extremely careful here to avoid deadlocks and thread stalls during this process. The most nefarious deadlock is that two or more threads run out of tries simultaneously and all need a place to store a victim even though we only have one slot
[ "if", "we", "kicked", "a", "tag", "we", "need", "to", "move", "it", "to", "alternate", "position", "possibly", "kicking", "another", "tag", "there", "repeating", "the", "process", "until", "we", "succeed", "or", "run", "out", "of", "chances" ]
e8472aa150b201f05046d1c81cac5a5ca4348db8
https://github.com/MGunlogson/CuckooFilter4J/blob/e8472aa150b201f05046d1c81cac5a5ca4348db8/src/main/java/com/github/mgunlogson/cuckoofilter4j/CuckooFilter.java#L476-L503
144,051
MGunlogson/CuckooFilter4J
src/main/java/com/github/mgunlogson/cuckoofilter4j/CuckooFilter.java
CuckooFilter.insertIfVictim
private void insertIfVictim() { long victimLockstamp = writeLockVictimIfSet(); if (victimLockstamp == 0L) return; try { // when we get here we definitely have a victim and a write lock bucketLocker.lockBucketsWrite(victim.getI1(), victim.getI2()); try { if (table.insertToBucket(victim.getI1(), victim.getTag()) || table.insertToBucket(victim.getI2(), victim.getTag())) { // set this here because we already have lock hasVictim = false; } } finally { bucketLocker.unlockBucketsWrite(victim.getI1(), victim.getI2()); } } finally { victimLock.unlock(victimLockstamp); } }
java
private void insertIfVictim() { long victimLockstamp = writeLockVictimIfSet(); if (victimLockstamp == 0L) return; try { // when we get here we definitely have a victim and a write lock bucketLocker.lockBucketsWrite(victim.getI1(), victim.getI2()); try { if (table.insertToBucket(victim.getI1(), victim.getTag()) || table.insertToBucket(victim.getI2(), victim.getTag())) { // set this here because we already have lock hasVictim = false; } } finally { bucketLocker.unlockBucketsWrite(victim.getI1(), victim.getI2()); } } finally { victimLock.unlock(victimLockstamp); } }
[ "private", "void", "insertIfVictim", "(", ")", "{", "long", "victimLockstamp", "=", "writeLockVictimIfSet", "(", ")", ";", "if", "(", "victimLockstamp", "==", "0L", ")", "return", ";", "try", "{", "// when we get here we definitely have a victim and a write lock\r", "bucketLocker", ".", "lockBucketsWrite", "(", "victim", ".", "getI1", "(", ")", ",", "victim", ".", "getI2", "(", ")", ")", ";", "try", "{", "if", "(", "table", ".", "insertToBucket", "(", "victim", ".", "getI1", "(", ")", ",", "victim", ".", "getTag", "(", ")", ")", "||", "table", ".", "insertToBucket", "(", "victim", ".", "getI2", "(", ")", ",", "victim", ".", "getTag", "(", ")", ")", ")", "{", "// set this here because we already have lock\r", "hasVictim", "=", "false", ";", "}", "}", "finally", "{", "bucketLocker", ".", "unlockBucketsWrite", "(", "victim", ".", "getI1", "(", ")", ",", "victim", ".", "getI2", "(", ")", ")", ";", "}", "}", "finally", "{", "victimLock", ".", "unlock", "(", "victimLockstamp", ")", ";", "}", "}" ]
Attempts to insert the victim item if it exists. Remember that inserting from the victim cache to the main table DOES NOT affect the count since items in the victim cache are technically still in the table
[ "Attempts", "to", "insert", "the", "victim", "item", "if", "it", "exists", ".", "Remember", "that", "inserting", "from", "the", "victim", "cache", "to", "the", "main", "table", "DOES", "NOT", "affect", "the", "count", "since", "items", "in", "the", "victim", "cache", "are", "technically", "still", "in", "the", "table" ]
e8472aa150b201f05046d1c81cac5a5ca4348db8
https://github.com/MGunlogson/CuckooFilter4J/blob/e8472aa150b201f05046d1c81cac5a5ca4348db8/src/main/java/com/github/mgunlogson/cuckoofilter4j/CuckooFilter.java#L511-L532
144,052
MGunlogson/CuckooFilter4J
src/main/java/com/github/mgunlogson/cuckoofilter4j/IndexTagCalc.java
IndexTagCalc.isHashConfigurationIsSupported
private static boolean isHashConfigurationIsSupported(long numBuckets, int tagBits, int hashSize) { int hashBitsNeeded = getTotalBitsNeeded(numBuckets, tagBits); switch (hashSize) { case 32: case 64: return hashBitsNeeded <= hashSize; default: } if (hashSize >= 128) return tagBits <= 64 && getIndexBitsUsed(numBuckets) <= 64; return false; }
java
private static boolean isHashConfigurationIsSupported(long numBuckets, int tagBits, int hashSize) { int hashBitsNeeded = getTotalBitsNeeded(numBuckets, tagBits); switch (hashSize) { case 32: case 64: return hashBitsNeeded <= hashSize; default: } if (hashSize >= 128) return tagBits <= 64 && getIndexBitsUsed(numBuckets) <= 64; return false; }
[ "private", "static", "boolean", "isHashConfigurationIsSupported", "(", "long", "numBuckets", ",", "int", "tagBits", ",", "int", "hashSize", ")", "{", "int", "hashBitsNeeded", "=", "getTotalBitsNeeded", "(", "numBuckets", ",", "tagBits", ")", ";", "switch", "(", "hashSize", ")", "{", "case", "32", ":", "case", "64", ":", "return", "hashBitsNeeded", "<=", "hashSize", ";", "default", ":", "}", "if", "(", "hashSize", ">=", "128", ")", "return", "tagBits", "<=", "64", "&&", "getIndexBitsUsed", "(", "numBuckets", ")", "<=", "64", ";", "return", "false", ";", "}" ]
Determines if the chosen hash function is long enough for the table configuration used.
[ "Determines", "if", "the", "chosen", "hash", "function", "is", "long", "enough", "for", "the", "table", "configuration", "used", "." ]
e8472aa150b201f05046d1c81cac5a5ca4348db8
https://github.com/MGunlogson/CuckooFilter4J/blob/e8472aa150b201f05046d1c81cac5a5ca4348db8/src/main/java/com/github/mgunlogson/cuckoofilter4j/IndexTagCalc.java#L111-L122
144,053
MGunlogson/CuckooFilter4J
src/main/java/com/github/mgunlogson/cuckoofilter4j/SerializableSaltedHasher.java
SerializableSaltedHasher.hashObjWithSalt
HashCode hashObjWithSalt(T object, int moreSalt) { Hasher hashInst = hasher.newHasher(); hashInst.putObject(object, funnel); hashInst.putLong(seedNSalt); hashInst.putInt(moreSalt); return hashInst.hash(); }
java
HashCode hashObjWithSalt(T object, int moreSalt) { Hasher hashInst = hasher.newHasher(); hashInst.putObject(object, funnel); hashInst.putLong(seedNSalt); hashInst.putInt(moreSalt); return hashInst.hash(); }
[ "HashCode", "hashObjWithSalt", "(", "T", "object", ",", "int", "moreSalt", ")", "{", "Hasher", "hashInst", "=", "hasher", ".", "newHasher", "(", ")", ";", "hashInst", ".", "putObject", "(", "object", ",", "funnel", ")", ";", "hashInst", ".", "putLong", "(", "seedNSalt", ")", ";", "hashInst", ".", "putInt", "(", "moreSalt", ")", ";", "return", "hashInst", ".", "hash", "(", ")", ";", "}" ]
hashes the object with an additional salt. For purpose of the cuckoo filter, this is used when the hash generated for an item is all zeros. All zeros is the same as an empty bucket, so obviously it's not a valid tag.
[ "hashes", "the", "object", "with", "an", "additional", "salt", ".", "For", "purpose", "of", "the", "cuckoo", "filter", "this", "is", "used", "when", "the", "hash", "generated", "for", "an", "item", "is", "all", "zeros", ".", "All", "zeros", "is", "the", "same", "as", "an", "empty", "bucket", "so", "obviously", "it", "s", "not", "a", "valid", "tag", "." ]
e8472aa150b201f05046d1c81cac5a5ca4348db8
https://github.com/MGunlogson/CuckooFilter4J/blob/e8472aa150b201f05046d1c81cac5a5ca4348db8/src/main/java/com/github/mgunlogson/cuckoofilter4j/SerializableSaltedHasher.java#L121-L127
144,054
MGunlogson/CuckooFilter4J
src/main/java/com/github/mgunlogson/cuckoofilter4j/ArrayUtil.java
ArrayUtil.oversize
static int oversize(int minTargetSize, int bytesPerElement) { if (minTargetSize < 0) { // catch usage that accidentally overflows int throw new IllegalArgumentException("invalid array size " + minTargetSize); } if (minTargetSize == 0) { // wait until at least one element is requested return 0; } if (minTargetSize > MAX_ARRAY_LENGTH) { throw new IllegalArgumentException("requested array size " + minTargetSize + " exceeds maximum array in java (" + MAX_ARRAY_LENGTH + ")"); } // asymptotic exponential growth by 1/8th, favors // spending a bit more CPU to not tie up too much wasted // RAM: int extra = minTargetSize >> 3; if (extra < 3) { // for very small arrays, where constant overhead of // realloc is presumably relatively high, we grow // faster extra = 3; } int newSize = minTargetSize + extra; // add 7 to allow for worst case byte alignment addition below: if (newSize+7 < 0 || newSize+7 > MAX_ARRAY_LENGTH) { // int overflowed, or we exceeded the maximum array length return MAX_ARRAY_LENGTH; } if (Constants.JRE_IS_64BIT) { // round up to 8 byte alignment in 64bit env switch(bytesPerElement) { case 4: // round up to multiple of 2 return (newSize + 1) & 0x7ffffffe; case 2: // round up to multiple of 4 return (newSize + 3) & 0x7ffffffc; case 1: // round up to multiple of 8 return (newSize + 7) & 0x7ffffff8; case 8: // no rounding default: // odd (invalid?) size return newSize; } } else { // round up to 4 byte alignment in 64bit env switch(bytesPerElement) { case 2: // round up to multiple of 2 return (newSize + 1) & 0x7ffffffe; case 1: // round up to multiple of 4 return (newSize + 3) & 0x7ffffffc; case 4: case 8: // no rounding default: // odd (invalid?) size return newSize; } } }
java
static int oversize(int minTargetSize, int bytesPerElement) { if (minTargetSize < 0) { // catch usage that accidentally overflows int throw new IllegalArgumentException("invalid array size " + minTargetSize); } if (minTargetSize == 0) { // wait until at least one element is requested return 0; } if (minTargetSize > MAX_ARRAY_LENGTH) { throw new IllegalArgumentException("requested array size " + minTargetSize + " exceeds maximum array in java (" + MAX_ARRAY_LENGTH + ")"); } // asymptotic exponential growth by 1/8th, favors // spending a bit more CPU to not tie up too much wasted // RAM: int extra = minTargetSize >> 3; if (extra < 3) { // for very small arrays, where constant overhead of // realloc is presumably relatively high, we grow // faster extra = 3; } int newSize = minTargetSize + extra; // add 7 to allow for worst case byte alignment addition below: if (newSize+7 < 0 || newSize+7 > MAX_ARRAY_LENGTH) { // int overflowed, or we exceeded the maximum array length return MAX_ARRAY_LENGTH; } if (Constants.JRE_IS_64BIT) { // round up to 8 byte alignment in 64bit env switch(bytesPerElement) { case 4: // round up to multiple of 2 return (newSize + 1) & 0x7ffffffe; case 2: // round up to multiple of 4 return (newSize + 3) & 0x7ffffffc; case 1: // round up to multiple of 8 return (newSize + 7) & 0x7ffffff8; case 8: // no rounding default: // odd (invalid?) size return newSize; } } else { // round up to 4 byte alignment in 64bit env switch(bytesPerElement) { case 2: // round up to multiple of 2 return (newSize + 1) & 0x7ffffffe; case 1: // round up to multiple of 4 return (newSize + 3) & 0x7ffffffc; case 4: case 8: // no rounding default: // odd (invalid?) size return newSize; } } }
[ "static", "int", "oversize", "(", "int", "minTargetSize", ",", "int", "bytesPerElement", ")", "{", "if", "(", "minTargetSize", "<", "0", ")", "{", "// catch usage that accidentally overflows int\r", "throw", "new", "IllegalArgumentException", "(", "\"invalid array size \"", "+", "minTargetSize", ")", ";", "}", "if", "(", "minTargetSize", "==", "0", ")", "{", "// wait until at least one element is requested\r", "return", "0", ";", "}", "if", "(", "minTargetSize", ">", "MAX_ARRAY_LENGTH", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"requested array size \"", "+", "minTargetSize", "+", "\" exceeds maximum array in java (\"", "+", "MAX_ARRAY_LENGTH", "+", "\")\"", ")", ";", "}", "// asymptotic exponential growth by 1/8th, favors\r", "// spending a bit more CPU to not tie up too much wasted\r", "// RAM:\r", "int", "extra", "=", "minTargetSize", ">>", "3", ";", "if", "(", "extra", "<", "3", ")", "{", "// for very small arrays, where constant overhead of\r", "// realloc is presumably relatively high, we grow\r", "// faster\r", "extra", "=", "3", ";", "}", "int", "newSize", "=", "minTargetSize", "+", "extra", ";", "// add 7 to allow for worst case byte alignment addition below:\r", "if", "(", "newSize", "+", "7", "<", "0", "||", "newSize", "+", "7", ">", "MAX_ARRAY_LENGTH", ")", "{", "// int overflowed, or we exceeded the maximum array length\r", "return", "MAX_ARRAY_LENGTH", ";", "}", "if", "(", "Constants", ".", "JRE_IS_64BIT", ")", "{", "// round up to 8 byte alignment in 64bit env\r", "switch", "(", "bytesPerElement", ")", "{", "case", "4", ":", "// round up to multiple of 2\r", "return", "(", "newSize", "+", "1", ")", "&", "0x7ffffffe", ";", "case", "2", ":", "// round up to multiple of 4\r", "return", "(", "newSize", "+", "3", ")", "&", "0x7ffffffc", ";", "case", "1", ":", "// round up to multiple of 8\r", "return", "(", "newSize", "+", "7", ")", "&", "0x7ffffff8", ";", "case", "8", ":", "// no rounding\r", "default", ":", "// odd (invalid?) size\r", "return", "newSize", ";", "}", "}", "else", "{", "// round up to 4 byte alignment in 64bit env\r", "switch", "(", "bytesPerElement", ")", "{", "case", "2", ":", "// round up to multiple of 2\r", "return", "(", "newSize", "+", "1", ")", "&", "0x7ffffffe", ";", "case", "1", ":", "// round up to multiple of 4\r", "return", "(", "newSize", "+", "3", ")", "&", "0x7ffffffc", ";", "case", "4", ":", "case", "8", ":", "// no rounding\r", "default", ":", "// odd (invalid?) size\r", "return", "newSize", ";", "}", "}", "}" ]
Returns an array size &gt;= minTargetSize, generally over-allocating exponentially to achieve amortized linear-time cost as the array grows. NOTE: this was originally borrowed from Python 2.4.2 listobject.c sources (attribution in LICENSE.txt), but has now been substantially changed based on discussions from java-dev thread with subject "Dynamic array reallocation algorithms", started on Jan 12 2010. @param minTargetSize Minimum required value to be returned. @param bytesPerElement Bytes used by each element of the array. See constants in {@link RamUsageEstimator}. @lucene.internal
[ "Returns", "an", "array", "size", "&gt", ";", "=", "minTargetSize", "generally", "over", "-", "allocating", "exponentially", "to", "achieve", "amortized", "linear", "-", "time", "cost", "as", "the", "array", "grows", "." ]
e8472aa150b201f05046d1c81cac5a5ca4348db8
https://github.com/MGunlogson/CuckooFilter4J/blob/e8472aa150b201f05046d1c81cac5a5ca4348db8/src/main/java/com/github/mgunlogson/cuckoofilter4j/ArrayUtil.java#L55-L126
144,055
MGunlogson/CuckooFilter4J
src/main/java/com/github/mgunlogson/cuckoofilter4j/LongBitSet.java
LongBitSet.prevSetBit
long prevSetBit(long index) { assert index >= 0 && index < numBits : "index=" + index + " numBits=" + numBits; int i = (int) (index >> 6); final int subIndex = (int) (index & 0x3f); // index within the word long word = (bits[i] << (63 - subIndex)); // skip all the bits to the // left of index if (word != 0) { return (i << 6) + subIndex - Long.numberOfLeadingZeros(word); // See // LUCENE-3197 } while (--i >= 0) { word = bits[i]; if (word != 0) { return (i << 6) + 63 - Long.numberOfLeadingZeros(word); } } return -1; }
java
long prevSetBit(long index) { assert index >= 0 && index < numBits : "index=" + index + " numBits=" + numBits; int i = (int) (index >> 6); final int subIndex = (int) (index & 0x3f); // index within the word long word = (bits[i] << (63 - subIndex)); // skip all the bits to the // left of index if (word != 0) { return (i << 6) + subIndex - Long.numberOfLeadingZeros(word); // See // LUCENE-3197 } while (--i >= 0) { word = bits[i]; if (word != 0) { return (i << 6) + 63 - Long.numberOfLeadingZeros(word); } } return -1; }
[ "long", "prevSetBit", "(", "long", "index", ")", "{", "assert", "index", ">=", "0", "&&", "index", "<", "numBits", ":", "\"index=\"", "+", "index", "+", "\" numBits=\"", "+", "numBits", ";", "int", "i", "=", "(", "int", ")", "(", "index", ">>", "6", ")", ";", "final", "int", "subIndex", "=", "(", "int", ")", "(", "index", "&", "0x3f", ")", ";", "// index within the word\r", "long", "word", "=", "(", "bits", "[", "i", "]", "<<", "(", "63", "-", "subIndex", ")", ")", ";", "// skip all the bits to the\r", "// left of index\r", "if", "(", "word", "!=", "0", ")", "{", "return", "(", "i", "<<", "6", ")", "+", "subIndex", "-", "Long", ".", "numberOfLeadingZeros", "(", "word", ")", ";", "// See\r", "// LUCENE-3197\r", "}", "while", "(", "--", "i", ">=", "0", ")", "{", "word", "=", "bits", "[", "i", "]", ";", "if", "(", "word", "!=", "0", ")", "{", "return", "(", "i", "<<", "6", ")", "+", "63", "-", "Long", ".", "numberOfLeadingZeros", "(", "word", ")", ";", "}", "}", "return", "-", "1", ";", "}" ]
Returns the index of the last set bit before or on the index specified. -1 is returned if there are no more set bits.
[ "Returns", "the", "index", "of", "the", "last", "set", "bit", "before", "or", "on", "the", "index", "specified", ".", "-", "1", "is", "returned", "if", "there", "are", "no", "more", "set", "bits", "." ]
e8472aa150b201f05046d1c81cac5a5ca4348db8
https://github.com/MGunlogson/CuckooFilter4J/blob/e8472aa150b201f05046d1c81cac5a5ca4348db8/src/main/java/com/github/mgunlogson/cuckoofilter4j/LongBitSet.java#L208-L228
144,056
MGunlogson/CuckooFilter4J
src/main/java/com/github/mgunlogson/cuckoofilter4j/LongBitSet.java
LongBitSet.or
void or(LongBitSet other) { assert other.numWords <= numWords : "numWords=" + numWords + ", other.numWords=" + other.numWords; int pos = Math.min(numWords, other.numWords); while (--pos >= 0) { bits[pos] |= other.bits[pos]; } }
java
void or(LongBitSet other) { assert other.numWords <= numWords : "numWords=" + numWords + ", other.numWords=" + other.numWords; int pos = Math.min(numWords, other.numWords); while (--pos >= 0) { bits[pos] |= other.bits[pos]; } }
[ "void", "or", "(", "LongBitSet", "other", ")", "{", "assert", "other", ".", "numWords", "<=", "numWords", ":", "\"numWords=\"", "+", "numWords", "+", "\", other.numWords=\"", "+", "other", ".", "numWords", ";", "int", "pos", "=", "Math", ".", "min", "(", "numWords", ",", "other", ".", "numWords", ")", ";", "while", "(", "--", "pos", ">=", "0", ")", "{", "bits", "[", "pos", "]", "|=", "other", ".", "bits", "[", "pos", "]", ";", "}", "}" ]
this = this OR other
[ "this", "=", "this", "OR", "other" ]
e8472aa150b201f05046d1c81cac5a5ca4348db8
https://github.com/MGunlogson/CuckooFilter4J/blob/e8472aa150b201f05046d1c81cac5a5ca4348db8/src/main/java/com/github/mgunlogson/cuckoofilter4j/LongBitSet.java#L231-L237
144,057
MGunlogson/CuckooFilter4J
src/main/java/com/github/mgunlogson/cuckoofilter4j/LongBitSet.java
LongBitSet.intersects
boolean intersects(LongBitSet other) { // Depends on the ghost bits being clear! int pos = Math.min(numWords, other.numWords); while (--pos >= 0) { if ((bits[pos] & other.bits[pos]) != 0) return true; } return false; }
java
boolean intersects(LongBitSet other) { // Depends on the ghost bits being clear! int pos = Math.min(numWords, other.numWords); while (--pos >= 0) { if ((bits[pos] & other.bits[pos]) != 0) return true; } return false; }
[ "boolean", "intersects", "(", "LongBitSet", "other", ")", "{", "// Depends on the ghost bits being clear!\r", "int", "pos", "=", "Math", ".", "min", "(", "numWords", ",", "other", ".", "numWords", ")", ";", "while", "(", "--", "pos", ">=", "0", ")", "{", "if", "(", "(", "bits", "[", "pos", "]", "&", "other", ".", "bits", "[", "pos", "]", ")", "!=", "0", ")", "return", "true", ";", "}", "return", "false", ";", "}" ]
returns true if the sets have any elements in common
[ "returns", "true", "if", "the", "sets", "have", "any", "elements", "in", "common" ]
e8472aa150b201f05046d1c81cac5a5ca4348db8
https://github.com/MGunlogson/CuckooFilter4J/blob/e8472aa150b201f05046d1c81cac5a5ca4348db8/src/main/java/com/github/mgunlogson/cuckoofilter4j/LongBitSet.java#L249-L257
144,058
MGunlogson/CuckooFilter4J
src/main/java/com/github/mgunlogson/cuckoofilter4j/LongBitSet.java
LongBitSet.andNot
void andNot(LongBitSet other) { int pos = Math.min(numWords, other.numWords); while (--pos >= 0) { bits[pos] &= ~other.bits[pos]; } }
java
void andNot(LongBitSet other) { int pos = Math.min(numWords, other.numWords); while (--pos >= 0) { bits[pos] &= ~other.bits[pos]; } }
[ "void", "andNot", "(", "LongBitSet", "other", ")", "{", "int", "pos", "=", "Math", ".", "min", "(", "numWords", ",", "other", ".", "numWords", ")", ";", "while", "(", "--", "pos", ">=", "0", ")", "{", "bits", "[", "pos", "]", "&=", "~", "other", ".", "bits", "[", "pos", "]", ";", "}", "}" ]
this = this AND NOT other
[ "this", "=", "this", "AND", "NOT", "other" ]
e8472aa150b201f05046d1c81cac5a5ca4348db8
https://github.com/MGunlogson/CuckooFilter4J/blob/e8472aa150b201f05046d1c81cac5a5ca4348db8/src/main/java/com/github/mgunlogson/cuckoofilter4j/LongBitSet.java#L271-L276
144,059
MGunlogson/CuckooFilter4J
src/main/java/com/github/mgunlogson/cuckoofilter4j/LongBitSet.java
LongBitSet.flip
void flip(long index) { assert index >= 0 && index < numBits : "index=" + index + " numBits=" + numBits; int wordNum = (int) (index >> 6); // div 64 long bitmask = 1L << index; // mod 64 is implicit bits[wordNum] ^= bitmask; }
java
void flip(long index) { assert index >= 0 && index < numBits : "index=" + index + " numBits=" + numBits; int wordNum = (int) (index >> 6); // div 64 long bitmask = 1L << index; // mod 64 is implicit bits[wordNum] ^= bitmask; }
[ "void", "flip", "(", "long", "index", ")", "{", "assert", "index", ">=", "0", "&&", "index", "<", "numBits", ":", "\"index=\"", "+", "index", "+", "\" numBits=\"", "+", "numBits", ";", "int", "wordNum", "=", "(", "int", ")", "(", "index", ">>", "6", ")", ";", "// div 64\r", "long", "bitmask", "=", "1L", "<<", "index", ";", "// mod 64 is implicit\r", "bits", "[", "wordNum", "]", "^=", "bitmask", ";", "}" ]
Flip the bit at the provided index.
[ "Flip", "the", "bit", "at", "the", "provided", "index", "." ]
e8472aa150b201f05046d1c81cac5a5ca4348db8
https://github.com/MGunlogson/CuckooFilter4J/blob/e8472aa150b201f05046d1c81cac5a5ca4348db8/src/main/java/com/github/mgunlogson/cuckoofilter4j/LongBitSet.java#L348-L353
144,060
MGunlogson/CuckooFilter4J
src/main/java/com/github/mgunlogson/cuckoofilter4j/FilterTable.java
FilterTable.create
static FilterTable create(int bitsPerTag, long numBuckets) { // why would this ever happen? checkArgument(bitsPerTag < 48, "tagBits (%s) should be less than 48 bits", bitsPerTag); // shorter fingerprints don't give us a good fill capacity checkArgument(bitsPerTag > 4, "tagBits (%s) must be > 4", bitsPerTag); checkArgument(numBuckets > 1, "numBuckets (%s) must be > 1", numBuckets); // checked so our implementors don't get too.... "enthusiastic" with // table size long bitsPerBucket = IntMath.checkedMultiply(CuckooFilter.BUCKET_SIZE, bitsPerTag); long bitSetSize = LongMath.checkedMultiply(bitsPerBucket, numBuckets); LongBitSet memBlock = new LongBitSet(bitSetSize); return new FilterTable(memBlock, bitsPerTag, numBuckets); }
java
static FilterTable create(int bitsPerTag, long numBuckets) { // why would this ever happen? checkArgument(bitsPerTag < 48, "tagBits (%s) should be less than 48 bits", bitsPerTag); // shorter fingerprints don't give us a good fill capacity checkArgument(bitsPerTag > 4, "tagBits (%s) must be > 4", bitsPerTag); checkArgument(numBuckets > 1, "numBuckets (%s) must be > 1", numBuckets); // checked so our implementors don't get too.... "enthusiastic" with // table size long bitsPerBucket = IntMath.checkedMultiply(CuckooFilter.BUCKET_SIZE, bitsPerTag); long bitSetSize = LongMath.checkedMultiply(bitsPerBucket, numBuckets); LongBitSet memBlock = new LongBitSet(bitSetSize); return new FilterTable(memBlock, bitsPerTag, numBuckets); }
[ "static", "FilterTable", "create", "(", "int", "bitsPerTag", ",", "long", "numBuckets", ")", "{", "// why would this ever happen?\r", "checkArgument", "(", "bitsPerTag", "<", "48", ",", "\"tagBits (%s) should be less than 48 bits\"", ",", "bitsPerTag", ")", ";", "// shorter fingerprints don't give us a good fill capacity\r", "checkArgument", "(", "bitsPerTag", ">", "4", ",", "\"tagBits (%s) must be > 4\"", ",", "bitsPerTag", ")", ";", "checkArgument", "(", "numBuckets", ">", "1", ",", "\"numBuckets (%s) must be > 1\"", ",", "numBuckets", ")", ";", "// checked so our implementors don't get too.... \"enthusiastic\" with\r", "// table size\r", "long", "bitsPerBucket", "=", "IntMath", ".", "checkedMultiply", "(", "CuckooFilter", ".", "BUCKET_SIZE", ",", "bitsPerTag", ")", ";", "long", "bitSetSize", "=", "LongMath", ".", "checkedMultiply", "(", "bitsPerBucket", ",", "numBuckets", ")", ";", "LongBitSet", "memBlock", "=", "new", "LongBitSet", "(", "bitSetSize", ")", ";", "return", "new", "FilterTable", "(", "memBlock", ",", "bitsPerTag", ",", "numBuckets", ")", ";", "}" ]
Creates a FilterTable @param bitsPerTag number of bits needed for each tag @param numBuckets number of buckets in filter @return
[ "Creates", "a", "FilterTable" ]
e8472aa150b201f05046d1c81cac5a5ca4348db8
https://github.com/MGunlogson/CuckooFilter4J/blob/e8472aa150b201f05046d1c81cac5a5ca4348db8/src/main/java/com/github/mgunlogson/cuckoofilter4j/FilterTable.java#L70-L82
144,061
MGunlogson/CuckooFilter4J
src/main/java/com/github/mgunlogson/cuckoofilter4j/FilterTable.java
FilterTable.insertToBucket
boolean insertToBucket(long bucketIndex, long tag) { for (int i = 0; i < CuckooFilter.BUCKET_SIZE; i++) { if (checkTag(bucketIndex, i, 0)) { writeTagNoClear(bucketIndex, i, tag); return true; } } return false; }
java
boolean insertToBucket(long bucketIndex, long tag) { for (int i = 0; i < CuckooFilter.BUCKET_SIZE; i++) { if (checkTag(bucketIndex, i, 0)) { writeTagNoClear(bucketIndex, i, tag); return true; } } return false; }
[ "boolean", "insertToBucket", "(", "long", "bucketIndex", ",", "long", "tag", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "CuckooFilter", ".", "BUCKET_SIZE", ";", "i", "++", ")", "{", "if", "(", "checkTag", "(", "bucketIndex", ",", "i", ",", "0", ")", ")", "{", "writeTagNoClear", "(", "bucketIndex", ",", "i", ",", "tag", ")", ";", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
inserts a tag into an empty position in the chosen bucket. @param bucketIndex index @param tag tag @return true if insert succeeded(bucket not full)
[ "inserts", "a", "tag", "into", "an", "empty", "position", "in", "the", "chosen", "bucket", "." ]
e8472aa150b201f05046d1c81cac5a5ca4348db8
https://github.com/MGunlogson/CuckooFilter4J/blob/e8472aa150b201f05046d1c81cac5a5ca4348db8/src/main/java/com/github/mgunlogson/cuckoofilter4j/FilterTable.java#L93-L102
144,062
MGunlogson/CuckooFilter4J
src/main/java/com/github/mgunlogson/cuckoofilter4j/FilterTable.java
FilterTable.swapRandomTagInBucket
long swapRandomTagInBucket(long curIndex, long tag) { int randomBucketPosition = ThreadLocalRandom.current().nextInt(CuckooFilter.BUCKET_SIZE); return readTagAndSet(curIndex, randomBucketPosition, tag); }
java
long swapRandomTagInBucket(long curIndex, long tag) { int randomBucketPosition = ThreadLocalRandom.current().nextInt(CuckooFilter.BUCKET_SIZE); return readTagAndSet(curIndex, randomBucketPosition, tag); }
[ "long", "swapRandomTagInBucket", "(", "long", "curIndex", ",", "long", "tag", ")", "{", "int", "randomBucketPosition", "=", "ThreadLocalRandom", ".", "current", "(", ")", ".", "nextInt", "(", "CuckooFilter", ".", "BUCKET_SIZE", ")", ";", "return", "readTagAndSet", "(", "curIndex", ",", "randomBucketPosition", ",", "tag", ")", ";", "}" ]
Replaces a tag in a random position in the given bucket and returns the tag that was replaced. @param curIndex bucket index @param tag tag @return the replaced tag
[ "Replaces", "a", "tag", "in", "a", "random", "position", "in", "the", "given", "bucket", "and", "returns", "the", "tag", "that", "was", "replaced", "." ]
e8472aa150b201f05046d1c81cac5a5ca4348db8
https://github.com/MGunlogson/CuckooFilter4J/blob/e8472aa150b201f05046d1c81cac5a5ca4348db8/src/main/java/com/github/mgunlogson/cuckoofilter4j/FilterTable.java#L114-L117
144,063
MGunlogson/CuckooFilter4J
src/main/java/com/github/mgunlogson/cuckoofilter4j/FilterTable.java
FilterTable.findTag
boolean findTag(long i1, long i2, long tag) { for (int i = 0; i < CuckooFilter.BUCKET_SIZE; i++) { if (checkTag(i1, i, tag) || checkTag(i2, i, tag)) return true; } return false; }
java
boolean findTag(long i1, long i2, long tag) { for (int i = 0; i < CuckooFilter.BUCKET_SIZE; i++) { if (checkTag(i1, i, tag) || checkTag(i2, i, tag)) return true; } return false; }
[ "boolean", "findTag", "(", "long", "i1", ",", "long", "i2", ",", "long", "tag", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "CuckooFilter", ".", "BUCKET_SIZE", ";", "i", "++", ")", "{", "if", "(", "checkTag", "(", "i1", ",", "i", ",", "tag", ")", "||", "checkTag", "(", "i2", ",", "i", ",", "tag", ")", ")", "return", "true", ";", "}", "return", "false", ";", "}" ]
Finds a tag if present in two buckets. @param i1 first bucket index @param i2 second bucket index (alternate) @param tag tag @return true if tag found in one of the buckets
[ "Finds", "a", "tag", "if", "present", "in", "two", "buckets", "." ]
e8472aa150b201f05046d1c81cac5a5ca4348db8
https://github.com/MGunlogson/CuckooFilter4J/blob/e8472aa150b201f05046d1c81cac5a5ca4348db8/src/main/java/com/github/mgunlogson/cuckoofilter4j/FilterTable.java#L130-L136
144,064
MGunlogson/CuckooFilter4J
src/main/java/com/github/mgunlogson/cuckoofilter4j/FilterTable.java
FilterTable.deleteFromBucket
boolean deleteFromBucket(long i1, long tag) { for (int i = 0; i < CuckooFilter.BUCKET_SIZE; i++) { if (checkTag(i1, i, tag)) { deleteTag(i1, i); return true; } } return false; }
java
boolean deleteFromBucket(long i1, long tag) { for (int i = 0; i < CuckooFilter.BUCKET_SIZE; i++) { if (checkTag(i1, i, tag)) { deleteTag(i1, i); return true; } } return false; }
[ "boolean", "deleteFromBucket", "(", "long", "i1", ",", "long", "tag", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "CuckooFilter", ".", "BUCKET_SIZE", ";", "i", "++", ")", "{", "if", "(", "checkTag", "(", "i1", ",", "i", ",", "tag", ")", ")", "{", "deleteTag", "(", "i1", ",", "i", ")", ";", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Deletes an item from the table if it is found in the bucket @param i1 bucket index @param tag tag @return true if item was deleted
[ "Deletes", "an", "item", "from", "the", "table", "if", "it", "is", "found", "in", "the", "bucket" ]
e8472aa150b201f05046d1c81cac5a5ca4348db8
https://github.com/MGunlogson/CuckooFilter4J/blob/e8472aa150b201f05046d1c81cac5a5ca4348db8/src/main/java/com/github/mgunlogson/cuckoofilter4j/FilterTable.java#L153-L161
144,065
MGunlogson/CuckooFilter4J
src/main/java/com/github/mgunlogson/cuckoofilter4j/FilterTable.java
FilterTable.readTag
long readTag(long bucketIndex, int posInBucket) { long tagStartIdx = getTagOffset(bucketIndex, posInBucket); long tag = 0; long tagEndIdx = tagStartIdx + bitsPerTag; // looping over true bits per nextBitSet javadocs for (long i = memBlock.nextSetBit(tagStartIdx); i >= 0 && i < tagEndIdx; i = memBlock.nextSetBit(i + 1L)) { // set corresponding bit in tag tag |= 1 << (i - tagStartIdx); } return tag; }
java
long readTag(long bucketIndex, int posInBucket) { long tagStartIdx = getTagOffset(bucketIndex, posInBucket); long tag = 0; long tagEndIdx = tagStartIdx + bitsPerTag; // looping over true bits per nextBitSet javadocs for (long i = memBlock.nextSetBit(tagStartIdx); i >= 0 && i < tagEndIdx; i = memBlock.nextSetBit(i + 1L)) { // set corresponding bit in tag tag |= 1 << (i - tagStartIdx); } return tag; }
[ "long", "readTag", "(", "long", "bucketIndex", ",", "int", "posInBucket", ")", "{", "long", "tagStartIdx", "=", "getTagOffset", "(", "bucketIndex", ",", "posInBucket", ")", ";", "long", "tag", "=", "0", ";", "long", "tagEndIdx", "=", "tagStartIdx", "+", "bitsPerTag", ";", "// looping over true bits per nextBitSet javadocs\r", "for", "(", "long", "i", "=", "memBlock", ".", "nextSetBit", "(", "tagStartIdx", ")", ";", "i", ">=", "0", "&&", "i", "<", "tagEndIdx", ";", "i", "=", "memBlock", ".", "nextSetBit", "(", "i", "+", "1L", ")", ")", "{", "// set corresponding bit in tag\r", "tag", "|=", "1", "<<", "(", "i", "-", "tagStartIdx", ")", ";", "}", "return", "tag", ";", "}" ]
Works but currently only used for testing
[ "Works", "but", "currently", "only", "used", "for", "testing" ]
e8472aa150b201f05046d1c81cac5a5ca4348db8
https://github.com/MGunlogson/CuckooFilter4J/blob/e8472aa150b201f05046d1c81cac5a5ca4348db8/src/main/java/com/github/mgunlogson/cuckoofilter4j/FilterTable.java#L166-L176
144,066
MGunlogson/CuckooFilter4J
src/main/java/com/github/mgunlogson/cuckoofilter4j/FilterTable.java
FilterTable.readTagAndSet
long readTagAndSet(long bucketIndex, int posInBucket, long newTag) { long tagStartIdx = getTagOffset(bucketIndex, posInBucket); long tag = 0; long tagEndIdx = tagStartIdx + bitsPerTag; int tagPos = 0; for (long i = tagStartIdx; i < tagEndIdx; i++) { if ((newTag & (1L << tagPos)) != 0) { if (memBlock.getAndSet(i)) { tag |= 1 << tagPos; } } else { if (memBlock.getAndClear(i)) { tag |= 1 << tagPos; } } tagPos++; } return tag; }
java
long readTagAndSet(long bucketIndex, int posInBucket, long newTag) { long tagStartIdx = getTagOffset(bucketIndex, posInBucket); long tag = 0; long tagEndIdx = tagStartIdx + bitsPerTag; int tagPos = 0; for (long i = tagStartIdx; i < tagEndIdx; i++) { if ((newTag & (1L << tagPos)) != 0) { if (memBlock.getAndSet(i)) { tag |= 1 << tagPos; } } else { if (memBlock.getAndClear(i)) { tag |= 1 << tagPos; } } tagPos++; } return tag; }
[ "long", "readTagAndSet", "(", "long", "bucketIndex", ",", "int", "posInBucket", ",", "long", "newTag", ")", "{", "long", "tagStartIdx", "=", "getTagOffset", "(", "bucketIndex", ",", "posInBucket", ")", ";", "long", "tag", "=", "0", ";", "long", "tagEndIdx", "=", "tagStartIdx", "+", "bitsPerTag", ";", "int", "tagPos", "=", "0", ";", "for", "(", "long", "i", "=", "tagStartIdx", ";", "i", "<", "tagEndIdx", ";", "i", "++", ")", "{", "if", "(", "(", "newTag", "&", "(", "1L", "<<", "tagPos", ")", ")", "!=", "0", ")", "{", "if", "(", "memBlock", ".", "getAndSet", "(", "i", ")", ")", "{", "tag", "|=", "1", "<<", "tagPos", ";", "}", "}", "else", "{", "if", "(", "memBlock", ".", "getAndClear", "(", "i", ")", ")", "{", "tag", "|=", "1", "<<", "tagPos", ";", "}", "}", "tagPos", "++", ";", "}", "return", "tag", ";", "}" ]
Reads a tag and sets the bits to a new tag at same time for max speedification
[ "Reads", "a", "tag", "and", "sets", "the", "bits", "to", "a", "new", "tag", "at", "same", "time", "for", "max", "speedification" ]
e8472aa150b201f05046d1c81cac5a5ca4348db8
https://github.com/MGunlogson/CuckooFilter4J/blob/e8472aa150b201f05046d1c81cac5a5ca4348db8/src/main/java/com/github/mgunlogson/cuckoofilter4j/FilterTable.java#L182-L200
144,067
MGunlogson/CuckooFilter4J
src/main/java/com/github/mgunlogson/cuckoofilter4j/FilterTable.java
FilterTable.checkTag
boolean checkTag(long bucketIndex, int posInBucket, long tag) { long tagStartIdx = getTagOffset(bucketIndex, posInBucket); final int bityPerTag = bitsPerTag; for (long i = 0; i < bityPerTag; i++) { if (memBlock.get(i + tagStartIdx) != ((tag & (1L << i)) != 0)) return false; } return true; }
java
boolean checkTag(long bucketIndex, int posInBucket, long tag) { long tagStartIdx = getTagOffset(bucketIndex, posInBucket); final int bityPerTag = bitsPerTag; for (long i = 0; i < bityPerTag; i++) { if (memBlock.get(i + tagStartIdx) != ((tag & (1L << i)) != 0)) return false; } return true; }
[ "boolean", "checkTag", "(", "long", "bucketIndex", ",", "int", "posInBucket", ",", "long", "tag", ")", "{", "long", "tagStartIdx", "=", "getTagOffset", "(", "bucketIndex", ",", "posInBucket", ")", ";", "final", "int", "bityPerTag", "=", "bitsPerTag", ";", "for", "(", "long", "i", "=", "0", ";", "i", "<", "bityPerTag", ";", "i", "++", ")", "{", "if", "(", "memBlock", ".", "get", "(", "i", "+", "tagStartIdx", ")", "!=", "(", "(", "tag", "&", "(", "1L", "<<", "i", ")", ")", "!=", "0", ")", ")", "return", "false", ";", "}", "return", "true", ";", "}" ]
Check if a tag in a given position in a bucket matches the tag you passed it. Faster than regular read because it stops checking if it finds a non-matching bit.
[ "Check", "if", "a", "tag", "in", "a", "given", "position", "in", "a", "bucket", "matches", "the", "tag", "you", "passed", "it", ".", "Faster", "than", "regular", "read", "because", "it", "stops", "checking", "if", "it", "finds", "a", "non", "-", "matching", "bit", "." ]
e8472aa150b201f05046d1c81cac5a5ca4348db8
https://github.com/MGunlogson/CuckooFilter4J/blob/e8472aa150b201f05046d1c81cac5a5ca4348db8/src/main/java/com/github/mgunlogson/cuckoofilter4j/FilterTable.java#L207-L215
144,068
MGunlogson/CuckooFilter4J
src/main/java/com/github/mgunlogson/cuckoofilter4j/FilterTable.java
FilterTable.writeTagNoClear
void writeTagNoClear(long bucketIndex, int posInBucket, long tag) { long tagStartIdx = getTagOffset(bucketIndex, posInBucket); // BIT BANGIN YEAAAARRHHHGGGHHH for (int i = 0; i < bitsPerTag; i++) { // second arg just does bit test in tag if ((tag & (1L << i)) != 0) { memBlock.set(tagStartIdx + i); } } }
java
void writeTagNoClear(long bucketIndex, int posInBucket, long tag) { long tagStartIdx = getTagOffset(bucketIndex, posInBucket); // BIT BANGIN YEAAAARRHHHGGGHHH for (int i = 0; i < bitsPerTag; i++) { // second arg just does bit test in tag if ((tag & (1L << i)) != 0) { memBlock.set(tagStartIdx + i); } } }
[ "void", "writeTagNoClear", "(", "long", "bucketIndex", ",", "int", "posInBucket", ",", "long", "tag", ")", "{", "long", "tagStartIdx", "=", "getTagOffset", "(", "bucketIndex", ",", "posInBucket", ")", ";", "// BIT BANGIN YEAAAARRHHHGGGHHH\r", "for", "(", "int", "i", "=", "0", ";", "i", "<", "bitsPerTag", ";", "i", "++", ")", "{", "// second arg just does bit test in tag\r", "if", "(", "(", "tag", "&", "(", "1L", "<<", "i", ")", ")", "!=", "0", ")", "{", "memBlock", ".", "set", "(", "tagStartIdx", "+", "i", ")", ";", "}", "}", "}" ]
Writes a tag to a bucket position. Faster than regular write because it assumes tag starts with all zeros, but doesn't work properly if the position wasn't empty.
[ "Writes", "a", "tag", "to", "a", "bucket", "position", ".", "Faster", "than", "regular", "write", "because", "it", "assumes", "tag", "starts", "with", "all", "zeros", "but", "doesn", "t", "work", "properly", "if", "the", "position", "wasn", "t", "empty", "." ]
e8472aa150b201f05046d1c81cac5a5ca4348db8
https://github.com/MGunlogson/CuckooFilter4J/blob/e8472aa150b201f05046d1c81cac5a5ca4348db8/src/main/java/com/github/mgunlogson/cuckoofilter4j/FilterTable.java#L237-L246
144,069
x2on/gradle-hockeyapp-plugin
src/main/java/de/felixschulze/gradle/internal/ProgressLoggerWrapper.java
ProgressLoggerWrapper.invoke
private static Object invoke(Object obj, String method, Object... args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { Class<?>[] argumentTypes = new Class[args.length]; for (int i = 0; i < args.length; ++i) { argumentTypes[i] = args[i].getClass(); } Method m = obj.getClass().getMethod(method, argumentTypes); m.setAccessible(true); return m.invoke(obj, args); }
java
private static Object invoke(Object obj, String method, Object... args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { Class<?>[] argumentTypes = new Class[args.length]; for (int i = 0; i < args.length; ++i) { argumentTypes[i] = args[i].getClass(); } Method m = obj.getClass().getMethod(method, argumentTypes); m.setAccessible(true); return m.invoke(obj, args); }
[ "private", "static", "Object", "invoke", "(", "Object", "obj", ",", "String", "method", ",", "Object", "...", "args", ")", "throws", "NoSuchMethodException", ",", "InvocationTargetException", ",", "IllegalAccessException", "{", "Class", "<", "?", ">", "[", "]", "argumentTypes", "=", "new", "Class", "[", "args", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "args", ".", "length", ";", "++", "i", ")", "{", "argumentTypes", "[", "i", "]", "=", "args", "[", "i", "]", ".", "getClass", "(", ")", ";", "}", "Method", "m", "=", "obj", ".", "getClass", "(", ")", ".", "getMethod", "(", "method", ",", "argumentTypes", ")", ";", "m", ".", "setAccessible", "(", "true", ")", ";", "return", "m", ".", "invoke", "(", "obj", ",", "args", ")", ";", "}" ]
Invoke a method using reflection @param obj the object whose method should be invoked @param method the name of the method to invoke @param args the arguments to pass to the method @return the method's return value @throws NoSuchMethodException if the method was not found @throws InvocationTargetException if the method could not be invoked @throws IllegalAccessException if the method could not be accessed
[ "Invoke", "a", "method", "using", "reflection" ]
03354bf4c78eb6de905e138e6d77af41cb0e25fb
https://github.com/x2on/gradle-hockeyapp-plugin/blob/03354bf4c78eb6de905e138e6d77af41cb0e25fb/src/main/java/de/felixschulze/gradle/internal/ProgressLoggerWrapper.java#L90-L100
144,070
x2on/gradle-hockeyapp-plugin
src/main/java/de/felixschulze/gradle/internal/ProgressLoggerWrapper.java
ProgressLoggerWrapper.invokeIgnoreExceptions
private void invokeIgnoreExceptions(Object obj, String method, Object... args) { try { invoke(obj, method, args); } catch (NoSuchMethodException e) { logger.trace("Unable to log progress", e); } catch (InvocationTargetException e) { logger.trace("Unable to log progress", e); } catch (IllegalAccessException e) { logger.trace("Unable to log progress", e); } }
java
private void invokeIgnoreExceptions(Object obj, String method, Object... args) { try { invoke(obj, method, args); } catch (NoSuchMethodException e) { logger.trace("Unable to log progress", e); } catch (InvocationTargetException e) { logger.trace("Unable to log progress", e); } catch (IllegalAccessException e) { logger.trace("Unable to log progress", e); } }
[ "private", "void", "invokeIgnoreExceptions", "(", "Object", "obj", ",", "String", "method", ",", "Object", "...", "args", ")", "{", "try", "{", "invoke", "(", "obj", ",", "method", ",", "args", ")", ";", "}", "catch", "(", "NoSuchMethodException", "e", ")", "{", "logger", ".", "trace", "(", "\"Unable to log progress\"", ",", "e", ")", ";", "}", "catch", "(", "InvocationTargetException", "e", ")", "{", "logger", ".", "trace", "(", "\"Unable to log progress\"", ",", "e", ")", ";", "}", "catch", "(", "IllegalAccessException", "e", ")", "{", "logger", ".", "trace", "(", "\"Unable to log progress\"", ",", "e", ")", ";", "}", "}" ]
Invoke a method using reflection but don't throw any exceptions. Just log errors instead. @param obj the object whose method should be invoked @param method the name of the method to invoke @param args the arguments to pass to the method
[ "Invoke", "a", "method", "using", "reflection", "but", "don", "t", "throw", "any", "exceptions", ".", "Just", "log", "errors", "instead", "." ]
03354bf4c78eb6de905e138e6d77af41cb0e25fb
https://github.com/x2on/gradle-hockeyapp-plugin/blob/03354bf4c78eb6de905e138e6d77af41cb0e25fb/src/main/java/de/felixschulze/gradle/internal/ProgressLoggerWrapper.java#L109-L120
144,071
apache/fluo-recipes
modules/accumulo/src/main/java/org/apache/fluo/recipes/accumulo/ops/TableOperations.java
TableOperations.optimizeTable
public static void optimizeTable(FluoConfiguration fluoConfig, TableOptimizations tableOptim) throws Exception { Connector conn = getConnector(fluoConfig); TreeSet<Text> splits = new TreeSet<>(); for (Bytes split : tableOptim.getSplits()) { splits.add(new Text(split.toArray())); } String table = fluoConfig.getAccumuloTable(); conn.tableOperations().addSplits(table, splits); if (tableOptim.getTabletGroupingRegex() != null && !tableOptim.getTabletGroupingRegex().isEmpty()) { // was going to call : // conn.instanceOperations().testClassLoad(RGB_CLASS, TABLET_BALANCER_CLASS) // but that failed. See ACCUMULO-4068 try { // setting this prop first intentionally because it should fail in 1.6 conn.tableOperations().setProperty(table, RGB_PATTERN_PROP, tableOptim.getTabletGroupingRegex()); conn.tableOperations().setProperty(table, RGB_DEFAULT_PROP, "none"); conn.tableOperations().setProperty(table, TABLE_BALANCER_PROP, RGB_CLASS); } catch (AccumuloException e) { logger.warn("Unable to setup regex balancer (this is expected to fail in Accumulo 1.6.X) : " + e.getMessage()); logger.debug("Unable to setup regex balancer (this is expected to fail in Accumulo 1.6.X)", e); } } }
java
public static void optimizeTable(FluoConfiguration fluoConfig, TableOptimizations tableOptim) throws Exception { Connector conn = getConnector(fluoConfig); TreeSet<Text> splits = new TreeSet<>(); for (Bytes split : tableOptim.getSplits()) { splits.add(new Text(split.toArray())); } String table = fluoConfig.getAccumuloTable(); conn.tableOperations().addSplits(table, splits); if (tableOptim.getTabletGroupingRegex() != null && !tableOptim.getTabletGroupingRegex().isEmpty()) { // was going to call : // conn.instanceOperations().testClassLoad(RGB_CLASS, TABLET_BALANCER_CLASS) // but that failed. See ACCUMULO-4068 try { // setting this prop first intentionally because it should fail in 1.6 conn.tableOperations().setProperty(table, RGB_PATTERN_PROP, tableOptim.getTabletGroupingRegex()); conn.tableOperations().setProperty(table, RGB_DEFAULT_PROP, "none"); conn.tableOperations().setProperty(table, TABLE_BALANCER_PROP, RGB_CLASS); } catch (AccumuloException e) { logger.warn("Unable to setup regex balancer (this is expected to fail in Accumulo 1.6.X) : " + e.getMessage()); logger.debug("Unable to setup regex balancer (this is expected to fail in Accumulo 1.6.X)", e); } } }
[ "public", "static", "void", "optimizeTable", "(", "FluoConfiguration", "fluoConfig", ",", "TableOptimizations", "tableOptim", ")", "throws", "Exception", "{", "Connector", "conn", "=", "getConnector", "(", "fluoConfig", ")", ";", "TreeSet", "<", "Text", ">", "splits", "=", "new", "TreeSet", "<>", "(", ")", ";", "for", "(", "Bytes", "split", ":", "tableOptim", ".", "getSplits", "(", ")", ")", "{", "splits", ".", "add", "(", "new", "Text", "(", "split", ".", "toArray", "(", ")", ")", ")", ";", "}", "String", "table", "=", "fluoConfig", ".", "getAccumuloTable", "(", ")", ";", "conn", ".", "tableOperations", "(", ")", ".", "addSplits", "(", "table", ",", "splits", ")", ";", "if", "(", "tableOptim", ".", "getTabletGroupingRegex", "(", ")", "!=", "null", "&&", "!", "tableOptim", ".", "getTabletGroupingRegex", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "// was going to call :", "// conn.instanceOperations().testClassLoad(RGB_CLASS, TABLET_BALANCER_CLASS)", "// but that failed. See ACCUMULO-4068", "try", "{", "// setting this prop first intentionally because it should fail in 1.6", "conn", ".", "tableOperations", "(", ")", ".", "setProperty", "(", "table", ",", "RGB_PATTERN_PROP", ",", "tableOptim", ".", "getTabletGroupingRegex", "(", ")", ")", ";", "conn", ".", "tableOperations", "(", ")", ".", "setProperty", "(", "table", ",", "RGB_DEFAULT_PROP", ",", "\"none\"", ")", ";", "conn", ".", "tableOperations", "(", ")", ".", "setProperty", "(", "table", ",", "TABLE_BALANCER_PROP", ",", "RGB_CLASS", ")", ";", "}", "catch", "(", "AccumuloException", "e", ")", "{", "logger", ".", "warn", "(", "\"Unable to setup regex balancer (this is expected to fail in Accumulo 1.6.X) : \"", "+", "e", ".", "getMessage", "(", ")", ")", ";", "logger", ".", "debug", "(", "\"Unable to setup regex balancer (this is expected to fail in Accumulo 1.6.X)\"", ",", "e", ")", ";", "}", "}", "}" ]
Make the requested table optimizations. @param fluoConfig should contain information need to connect to Accumulo and name of Fluo table @param tableOptim Will perform these optimizations on Fluo table in Accumulo.
[ "Make", "the", "requested", "table", "optimizations", "." ]
24c11234c9654b16d999437ff49ddc3db86665f8
https://github.com/apache/fluo-recipes/blob/24c11234c9654b16d999437ff49ddc3db86665f8/modules/accumulo/src/main/java/org/apache/fluo/recipes/accumulo/ops/TableOperations.java#L70-L102
144,072
apache/fluo-recipes
modules/core/src/main/java/org/apache/fluo/recipes/core/transaction/TxLog.java
TxLog.filteredAdd
public void filteredAdd(LogEntry entry, Predicate<LogEntry> filter) { if (filter.test(entry)) { add(entry); } }
java
public void filteredAdd(LogEntry entry, Predicate<LogEntry> filter) { if (filter.test(entry)) { add(entry); } }
[ "public", "void", "filteredAdd", "(", "LogEntry", "entry", ",", "Predicate", "<", "LogEntry", ">", "filter", ")", "{", "if", "(", "filter", ".", "test", "(", "entry", ")", ")", "{", "add", "(", "entry", ")", ";", "}", "}" ]
Adds LogEntry to TxLog if it passes filter
[ "Adds", "LogEntry", "to", "TxLog", "if", "it", "passes", "filter" ]
24c11234c9654b16d999437ff49ddc3db86665f8
https://github.com/apache/fluo-recipes/blob/24c11234c9654b16d999437ff49ddc3db86665f8/modules/core/src/main/java/org/apache/fluo/recipes/core/transaction/TxLog.java#L49-L53
144,073
apache/fluo-recipes
modules/core/src/main/java/org/apache/fluo/recipes/core/transaction/TxLog.java
TxLog.getOperationMap
public Map<RowColumn, Bytes> getOperationMap(LogEntry.Operation op) { Map<RowColumn, Bytes> opMap = new HashMap<>(); for (LogEntry entry : logEntries) { if (entry.getOp().equals(op)) { opMap.put(new RowColumn(entry.getRow(), entry.getColumn()), entry.getValue()); } } return opMap; }
java
public Map<RowColumn, Bytes> getOperationMap(LogEntry.Operation op) { Map<RowColumn, Bytes> opMap = new HashMap<>(); for (LogEntry entry : logEntries) { if (entry.getOp().equals(op)) { opMap.put(new RowColumn(entry.getRow(), entry.getColumn()), entry.getValue()); } } return opMap; }
[ "public", "Map", "<", "RowColumn", ",", "Bytes", ">", "getOperationMap", "(", "LogEntry", ".", "Operation", "op", ")", "{", "Map", "<", "RowColumn", ",", "Bytes", ">", "opMap", "=", "new", "HashMap", "<>", "(", ")", ";", "for", "(", "LogEntry", "entry", ":", "logEntries", ")", "{", "if", "(", "entry", ".", "getOp", "(", ")", ".", "equals", "(", "op", ")", ")", "{", "opMap", ".", "put", "(", "new", "RowColumn", "(", "entry", ".", "getRow", "(", ")", ",", "entry", ".", "getColumn", "(", ")", ")", ",", "entry", ".", "getValue", "(", ")", ")", ";", "}", "}", "return", "opMap", ";", "}" ]
Returns a map of RowColumn changes given an operation
[ "Returns", "a", "map", "of", "RowColumn", "changes", "given", "an", "operation" ]
24c11234c9654b16d999437ff49ddc3db86665f8
https://github.com/apache/fluo-recipes/blob/24c11234c9654b16d999437ff49ddc3db86665f8/modules/core/src/main/java/org/apache/fluo/recipes/core/transaction/TxLog.java#L72-L80
144,074
seam/faces
impl/src/main/java/org/jboss/seam/faces/projectstage/JNDIProjectStageDetector.java
JNDIProjectStageDetector.getProjectStageNameFromJNDI
private String getProjectStageNameFromJNDI() { try { InitialContext context = new InitialContext(); Object obj = context.lookup(ProjectStage.PROJECT_STAGE_JNDI_NAME); if (obj != null) { return obj.toString().trim(); } } catch (NamingException e) { // ignore } return null; }
java
private String getProjectStageNameFromJNDI() { try { InitialContext context = new InitialContext(); Object obj = context.lookup(ProjectStage.PROJECT_STAGE_JNDI_NAME); if (obj != null) { return obj.toString().trim(); } } catch (NamingException e) { // ignore } return null; }
[ "private", "String", "getProjectStageNameFromJNDI", "(", ")", "{", "try", "{", "InitialContext", "context", "=", "new", "InitialContext", "(", ")", ";", "Object", "obj", "=", "context", ".", "lookup", "(", "ProjectStage", ".", "PROJECT_STAGE_JNDI_NAME", ")", ";", "if", "(", "obj", "!=", "null", ")", "{", "return", "obj", ".", "toString", "(", ")", ".", "trim", "(", ")", ";", "}", "}", "catch", "(", "NamingException", "e", ")", "{", "// ignore", "}", "return", "null", ";", "}" ]
Performs a JNDI lookup to obtain the current project stage. The method use the standard JNDI name for the JSF project stage for the lookup @return name bound to JNDI or <code>null</code>
[ "Performs", "a", "JNDI", "lookup", "to", "obtain", "the", "current", "project", "stage", ".", "The", "method", "use", "the", "standard", "JNDI", "name", "for", "the", "JSF", "project", "stage", "for", "the", "lookup" ]
2fdedbc7070318c2c58bfffb8a26f1ea1d0ee1e3
https://github.com/seam/faces/blob/2fdedbc7070318c2c58bfffb8a26f1ea1d0ee1e3/impl/src/main/java/org/jboss/seam/faces/projectstage/JNDIProjectStageDetector.java#L62-L77
144,075
apache/fluo-recipes
modules/core/src/main/java/org/apache/fluo/recipes/core/transaction/RecordingTransactionBase.java
RecordingTransactionBase.wrap
public static RecordingTransactionBase wrap(TransactionBase txb, Predicate<LogEntry> filter) { return new RecordingTransactionBase(txb, filter); }
java
public static RecordingTransactionBase wrap(TransactionBase txb, Predicate<LogEntry> filter) { return new RecordingTransactionBase(txb, filter); }
[ "public", "static", "RecordingTransactionBase", "wrap", "(", "TransactionBase", "txb", ",", "Predicate", "<", "LogEntry", ">", "filter", ")", "{", "return", "new", "RecordingTransactionBase", "(", "txb", ",", "filter", ")", ";", "}" ]
Creates a RecordingTransactionBase using the provided LogEntry filter function and existing TransactionBase
[ "Creates", "a", "RecordingTransactionBase", "using", "the", "provided", "LogEntry", "filter", "function", "and", "existing", "TransactionBase" ]
24c11234c9654b16d999437ff49ddc3db86665f8
https://github.com/apache/fluo-recipes/blob/24c11234c9654b16d999437ff49ddc3db86665f8/modules/core/src/main/java/org/apache/fluo/recipes/core/transaction/RecordingTransactionBase.java#L310-L312
144,076
olivergondza/dumpling
core/src/main/java/com/github/olivergondza/dumpling/factory/PidRuntimeFactory.java
PidRuntimeFactory.fromCurrentProcess
public @Nonnull ThreadDumpRuntime fromCurrentProcess() throws IOException, InterruptedException { final String jvmName = ManagementFactory.getRuntimeMXBean().getName(); final int index = jvmName.indexOf('@'); if (index < 1) throw new IOException("Unable to extract PID from " + jvmName); long pid; try { pid = Long.parseLong(jvmName.substring(0, index)); } catch (NumberFormatException e) { throw new IOException("Unable to extract PID from " + jvmName); } return fromProcess(pid); }
java
public @Nonnull ThreadDumpRuntime fromCurrentProcess() throws IOException, InterruptedException { final String jvmName = ManagementFactory.getRuntimeMXBean().getName(); final int index = jvmName.indexOf('@'); if (index < 1) throw new IOException("Unable to extract PID from " + jvmName); long pid; try { pid = Long.parseLong(jvmName.substring(0, index)); } catch (NumberFormatException e) { throw new IOException("Unable to extract PID from " + jvmName); } return fromProcess(pid); }
[ "public", "@", "Nonnull", "ThreadDumpRuntime", "fromCurrentProcess", "(", ")", "throws", "IOException", ",", "InterruptedException", "{", "final", "String", "jvmName", "=", "ManagementFactory", ".", "getRuntimeMXBean", "(", ")", ".", "getName", "(", ")", ";", "final", "int", "index", "=", "jvmName", ".", "indexOf", "(", "'", "'", ")", ";", "if", "(", "index", "<", "1", ")", "throw", "new", "IOException", "(", "\"Unable to extract PID from \"", "+", "jvmName", ")", ";", "long", "pid", ";", "try", "{", "pid", "=", "Long", ".", "parseLong", "(", "jvmName", ".", "substring", "(", "0", ",", "index", ")", ")", ";", "}", "catch", "(", "NumberFormatException", "e", ")", "{", "throw", "new", "IOException", "(", "\"Unable to extract PID from \"", "+", "jvmName", ")", ";", "}", "return", "fromProcess", "(", "pid", ")", ";", "}" ]
Extract runtime from current process. This approach is somewhat external and {@link JvmRuntimeFactory} should be preferred.
[ "Extract", "runtime", "from", "current", "process", "." ]
ac698735fcc7c023db0c1637cc1f522cb3576c7f
https://github.com/olivergondza/dumpling/blob/ac698735fcc7c023db0c1637cc1f522cb3576c7f/core/src/main/java/com/github/olivergondza/dumpling/factory/PidRuntimeFactory.java#L171-L185
144,077
seam/faces
impl/src/main/java/org/jboss/seam/faces/context/RenderScopedContext.java
RenderScopedContext.afterPhase
@SuppressWarnings({"unchecked", "rawtypes", "unused"}) public void afterPhase(final PhaseEvent event) { if (PhaseId.RENDER_RESPONSE.equals(event.getPhaseId())) { RenderContext contextInstance = getContextInstance(); if (contextInstance != null) { Integer id = contextInstance.getId(); RenderContext removed = getRenderContextMap().remove(id); Map<Contextual<?>, Object> componentInstanceMap = getComponentInstanceMap(); Map<Contextual<?>, CreationalContext<?>> creationalContextMap = getCreationalContextMap(); if ((componentInstanceMap != null) && (creationalContextMap != null)) { for (Entry<Contextual<?>, Object> componentEntry : componentInstanceMap.entrySet()) { Contextual contextual = componentEntry.getKey(); Object instance = componentEntry.getValue(); CreationalContext creational = creationalContextMap.get(contextual); contextual.destroy(instance, creational); } } } } }
java
@SuppressWarnings({"unchecked", "rawtypes", "unused"}) public void afterPhase(final PhaseEvent event) { if (PhaseId.RENDER_RESPONSE.equals(event.getPhaseId())) { RenderContext contextInstance = getContextInstance(); if (contextInstance != null) { Integer id = contextInstance.getId(); RenderContext removed = getRenderContextMap().remove(id); Map<Contextual<?>, Object> componentInstanceMap = getComponentInstanceMap(); Map<Contextual<?>, CreationalContext<?>> creationalContextMap = getCreationalContextMap(); if ((componentInstanceMap != null) && (creationalContextMap != null)) { for (Entry<Contextual<?>, Object> componentEntry : componentInstanceMap.entrySet()) { Contextual contextual = componentEntry.getKey(); Object instance = componentEntry.getValue(); CreationalContext creational = creationalContextMap.get(contextual); contextual.destroy(instance, creational); } } } } }
[ "@", "SuppressWarnings", "(", "{", "\"unchecked\"", ",", "\"rawtypes\"", ",", "\"unused\"", "}", ")", "public", "void", "afterPhase", "(", "final", "PhaseEvent", "event", ")", "{", "if", "(", "PhaseId", ".", "RENDER_RESPONSE", ".", "equals", "(", "event", ".", "getPhaseId", "(", ")", ")", ")", "{", "RenderContext", "contextInstance", "=", "getContextInstance", "(", ")", ";", "if", "(", "contextInstance", "!=", "null", ")", "{", "Integer", "id", "=", "contextInstance", ".", "getId", "(", ")", ";", "RenderContext", "removed", "=", "getRenderContextMap", "(", ")", ".", "remove", "(", "id", ")", ";", "Map", "<", "Contextual", "<", "?", ">", ",", "Object", ">", "componentInstanceMap", "=", "getComponentInstanceMap", "(", ")", ";", "Map", "<", "Contextual", "<", "?", ">", ",", "CreationalContext", "<", "?", ">", ">", "creationalContextMap", "=", "getCreationalContextMap", "(", ")", ";", "if", "(", "(", "componentInstanceMap", "!=", "null", ")", "&&", "(", "creationalContextMap", "!=", "null", ")", ")", "{", "for", "(", "Entry", "<", "Contextual", "<", "?", ">", ",", "Object", ">", "componentEntry", ":", "componentInstanceMap", ".", "entrySet", "(", ")", ")", "{", "Contextual", "contextual", "=", "componentEntry", ".", "getKey", "(", ")", ";", "Object", "instance", "=", "componentEntry", ".", "getValue", "(", ")", ";", "CreationalContext", "creational", "=", "creationalContextMap", ".", "get", "(", "contextual", ")", ";", "contextual", ".", "destroy", "(", "instance", ",", "creational", ")", ";", "}", "}", "}", "}", "}" ]
Destroy the current context since Render Response has completed.
[ "Destroy", "the", "current", "context", "since", "Render", "Response", "has", "completed", "." ]
2fdedbc7070318c2c58bfffb8a26f1ea1d0ee1e3
https://github.com/seam/faces/blob/2fdedbc7070318c2c58bfffb8a26f1ea1d0ee1e3/impl/src/main/java/org/jboss/seam/faces/context/RenderScopedContext.java#L139-L161
144,078
seam/faces
impl/src/main/java/org/jboss/seam/faces/projectstage/WebXmlContextParameterParser.java
WebXmlContextParameterParser.elements
protected boolean elements(String... name) { if (name == null || name.length != stack.size()) { return false; } for (int i = 0; i < name.length; i++) { if (!name[i].equals(stack.get(i))) { return false; } } return true; }
java
protected boolean elements(String... name) { if (name == null || name.length != stack.size()) { return false; } for (int i = 0; i < name.length; i++) { if (!name[i].equals(stack.get(i))) { return false; } } return true; }
[ "protected", "boolean", "elements", "(", "String", "...", "name", ")", "{", "if", "(", "name", "==", "null", "||", "name", ".", "length", "!=", "stack", ".", "size", "(", ")", ")", "{", "return", "false", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "name", ".", "length", ";", "i", "++", ")", "{", "if", "(", "!", "name", "[", "i", "]", ".", "equals", "(", "stack", ".", "get", "(", "i", ")", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Checks whether the element stack currently contains exactly the elements supplied by the caller. This method can be used to find the current position in the document. The first argument is always the root element of the document, the second is a child of the root element, and so on. The method uses the local names of the elements only. Namespaces are ignored. @param name The names of the parent elements @return <code>true</code> if the parent element stack contains exactly these elements
[ "Checks", "whether", "the", "element", "stack", "currently", "contains", "exactly", "the", "elements", "supplied", "by", "the", "caller", ".", "This", "method", "can", "be", "used", "to", "find", "the", "current", "position", "in", "the", "document", ".", "The", "first", "argument", "is", "always", "the", "root", "element", "of", "the", "document", "the", "second", "is", "a", "child", "of", "the", "root", "element", "and", "so", "on", ".", "The", "method", "uses", "the", "local", "names", "of", "the", "elements", "only", ".", "Namespaces", "are", "ignored", "." ]
2fdedbc7070318c2c58bfffb8a26f1ea1d0ee1e3
https://github.com/seam/faces/blob/2fdedbc7070318c2c58bfffb8a26f1ea1d0ee1e3/impl/src/main/java/org/jboss/seam/faces/projectstage/WebXmlContextParameterParser.java#L162-L172
144,079
apache/fluo-recipes
modules/accumulo/src/main/java/org/apache/fluo/recipes/accumulo/export/AccumuloReplicator.java
AccumuloReplicator.getFilter
public static Predicate<LogEntry> getFilter() { return le -> le.getOp().equals(LogEntry.Operation.DELETE) || le.getOp().equals(LogEntry.Operation.SET); }
java
public static Predicate<LogEntry> getFilter() { return le -> le.getOp().equals(LogEntry.Operation.DELETE) || le.getOp().equals(LogEntry.Operation.SET); }
[ "public", "static", "Predicate", "<", "LogEntry", ">", "getFilter", "(", ")", "{", "return", "le", "->", "le", ".", "getOp", "(", ")", ".", "equals", "(", "LogEntry", ".", "Operation", ".", "DELETE", ")", "||", "le", ".", "getOp", "(", ")", ".", "equals", "(", "LogEntry", ".", "Operation", ".", "SET", ")", ";", "}" ]
Returns LogEntry filter for Accumulo replication. @see RecordingTransaction#wrap(org.apache.fluo.api.client.TransactionBase, Predicate)
[ "Returns", "LogEntry", "filter", "for", "Accumulo", "replication", "." ]
24c11234c9654b16d999437ff49ddc3db86665f8
https://github.com/apache/fluo-recipes/blob/24c11234c9654b16d999437ff49ddc3db86665f8/modules/accumulo/src/main/java/org/apache/fluo/recipes/accumulo/export/AccumuloReplicator.java#L57-L60
144,080
apache/fluo-recipes
modules/accumulo/src/main/java/org/apache/fluo/recipes/accumulo/export/AccumuloReplicator.java
AccumuloReplicator.generateMutations
public static void generateMutations(long seq, TxLog txLog, Consumer<Mutation> consumer) { Map<Bytes, Mutation> mutationMap = new HashMap<>(); for (LogEntry le : txLog.getLogEntries()) { LogEntry.Operation op = le.getOp(); Column col = le.getColumn(); byte[] cf = col.getFamily().toArray(); byte[] cq = col.getQualifier().toArray(); byte[] cv = col.getVisibility().toArray(); if (op.equals(LogEntry.Operation.DELETE) || op.equals(LogEntry.Operation.SET)) { Mutation m = mutationMap.computeIfAbsent(le.getRow(), k -> new Mutation(k.toArray())); if (op.equals(LogEntry.Operation.DELETE)) { if (col.isVisibilitySet()) { m.putDelete(cf, cq, new ColumnVisibility(cv), seq); } else { m.putDelete(cf, cq, seq); } } else { if (col.isVisibilitySet()) { m.put(cf, cq, new ColumnVisibility(cv), seq, le.getValue().toArray()); } else { m.put(cf, cq, seq, le.getValue().toArray()); } } } } mutationMap.values().forEach(consumer); }
java
public static void generateMutations(long seq, TxLog txLog, Consumer<Mutation> consumer) { Map<Bytes, Mutation> mutationMap = new HashMap<>(); for (LogEntry le : txLog.getLogEntries()) { LogEntry.Operation op = le.getOp(); Column col = le.getColumn(); byte[] cf = col.getFamily().toArray(); byte[] cq = col.getQualifier().toArray(); byte[] cv = col.getVisibility().toArray(); if (op.equals(LogEntry.Operation.DELETE) || op.equals(LogEntry.Operation.SET)) { Mutation m = mutationMap.computeIfAbsent(le.getRow(), k -> new Mutation(k.toArray())); if (op.equals(LogEntry.Operation.DELETE)) { if (col.isVisibilitySet()) { m.putDelete(cf, cq, new ColumnVisibility(cv), seq); } else { m.putDelete(cf, cq, seq); } } else { if (col.isVisibilitySet()) { m.put(cf, cq, new ColumnVisibility(cv), seq, le.getValue().toArray()); } else { m.put(cf, cq, seq, le.getValue().toArray()); } } } } mutationMap.values().forEach(consumer); }
[ "public", "static", "void", "generateMutations", "(", "long", "seq", ",", "TxLog", "txLog", ",", "Consumer", "<", "Mutation", ">", "consumer", ")", "{", "Map", "<", "Bytes", ",", "Mutation", ">", "mutationMap", "=", "new", "HashMap", "<>", "(", ")", ";", "for", "(", "LogEntry", "le", ":", "txLog", ".", "getLogEntries", "(", ")", ")", "{", "LogEntry", ".", "Operation", "op", "=", "le", ".", "getOp", "(", ")", ";", "Column", "col", "=", "le", ".", "getColumn", "(", ")", ";", "byte", "[", "]", "cf", "=", "col", ".", "getFamily", "(", ")", ".", "toArray", "(", ")", ";", "byte", "[", "]", "cq", "=", "col", ".", "getQualifier", "(", ")", ".", "toArray", "(", ")", ";", "byte", "[", "]", "cv", "=", "col", ".", "getVisibility", "(", ")", ".", "toArray", "(", ")", ";", "if", "(", "op", ".", "equals", "(", "LogEntry", ".", "Operation", ".", "DELETE", ")", "||", "op", ".", "equals", "(", "LogEntry", ".", "Operation", ".", "SET", ")", ")", "{", "Mutation", "m", "=", "mutationMap", ".", "computeIfAbsent", "(", "le", ".", "getRow", "(", ")", ",", "k", "->", "new", "Mutation", "(", "k", ".", "toArray", "(", ")", ")", ")", ";", "if", "(", "op", ".", "equals", "(", "LogEntry", ".", "Operation", ".", "DELETE", ")", ")", "{", "if", "(", "col", ".", "isVisibilitySet", "(", ")", ")", "{", "m", ".", "putDelete", "(", "cf", ",", "cq", ",", "new", "ColumnVisibility", "(", "cv", ")", ",", "seq", ")", ";", "}", "else", "{", "m", ".", "putDelete", "(", "cf", ",", "cq", ",", "seq", ")", ";", "}", "}", "else", "{", "if", "(", "col", ".", "isVisibilitySet", "(", ")", ")", "{", "m", ".", "put", "(", "cf", ",", "cq", ",", "new", "ColumnVisibility", "(", "cv", ")", ",", "seq", ",", "le", ".", "getValue", "(", ")", ".", "toArray", "(", ")", ")", ";", "}", "else", "{", "m", ".", "put", "(", "cf", ",", "cq", ",", "seq", ",", "le", ".", "getValue", "(", ")", ".", "toArray", "(", ")", ")", ";", "}", "}", "}", "}", "mutationMap", ".", "values", "(", ")", ".", "forEach", "(", "consumer", ")", ";", "}" ]
Generates Accumulo mutations from a Transaction log. Used to Replicate Fluo table to Accumulo. @param txLog Transaction log @param seq Export sequence number @param consumer generated mutations will be output to this consumer
[ "Generates", "Accumulo", "mutations", "from", "a", "Transaction", "log", ".", "Used", "to", "Replicate", "Fluo", "table", "to", "Accumulo", "." ]
24c11234c9654b16d999437ff49ddc3db86665f8
https://github.com/apache/fluo-recipes/blob/24c11234c9654b16d999437ff49ddc3db86665f8/modules/accumulo/src/main/java/org/apache/fluo/recipes/accumulo/export/AccumuloReplicator.java#L78-L104
144,081
seam/faces
api/src/main/java/org/jboss/seam/faces/component/UIValidateForm.java
UIValidateForm.locateForm
public UIForm locateForm() { UIComponent parent = this.getParent(); while (!(parent instanceof UIForm)) { if ((parent == null) || (parent instanceof UIViewRoot)) { throw new IllegalStateException( "The UIValidateForm (<s:validateForm />) component must be placed within a UIForm (<h:form>)"); } parent = parent.getParent(); } return (UIForm) parent; }
java
public UIForm locateForm() { UIComponent parent = this.getParent(); while (!(parent instanceof UIForm)) { if ((parent == null) || (parent instanceof UIViewRoot)) { throw new IllegalStateException( "The UIValidateForm (<s:validateForm />) component must be placed within a UIForm (<h:form>)"); } parent = parent.getParent(); } return (UIForm) parent; }
[ "public", "UIForm", "locateForm", "(", ")", "{", "UIComponent", "parent", "=", "this", ".", "getParent", "(", ")", ";", "while", "(", "!", "(", "parent", "instanceof", "UIForm", ")", ")", "{", "if", "(", "(", "parent", "==", "null", ")", "||", "(", "parent", "instanceof", "UIViewRoot", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"The UIValidateForm (<s:validateForm />) component must be placed within a UIForm (<h:form>)\"", ")", ";", "}", "parent", "=", "parent", ".", "getParent", "(", ")", ";", "}", "return", "(", "UIForm", ")", "parent", ";", "}" ]
Attempt to locate the form in which this component resides. If the component is not within a UIForm tag, throw an exception.
[ "Attempt", "to", "locate", "the", "form", "in", "which", "this", "component", "resides", ".", "If", "the", "component", "is", "not", "within", "a", "UIForm", "tag", "throw", "an", "exception", "." ]
2fdedbc7070318c2c58bfffb8a26f1ea1d0ee1e3
https://github.com/seam/faces/blob/2fdedbc7070318c2c58bfffb8a26f1ea1d0ee1e3/api/src/main/java/org/jboss/seam/faces/component/UIValidateForm.java#L122-L132
144,082
apache/fluo-recipes
modules/core/src/main/java/org/apache/fluo/recipes/core/export/ExportBucket.java
ExportBucket.getMinimalRow
private Bytes getMinimalRow() { return Bytes.builder(bucketRow.length() + 1).append(bucketRow).append(':').toBytes(); }
java
private Bytes getMinimalRow() { return Bytes.builder(bucketRow.length() + 1).append(bucketRow).append(':').toBytes(); }
[ "private", "Bytes", "getMinimalRow", "(", ")", "{", "return", "Bytes", ".", "builder", "(", "bucketRow", ".", "length", "(", ")", "+", "1", ")", ".", "append", "(", "bucketRow", ")", ".", "append", "(", "'", "'", ")", ".", "toBytes", "(", ")", ";", "}" ]
Computes the minimal row for a bucket
[ "Computes", "the", "minimal", "row", "for", "a", "bucket" ]
24c11234c9654b16d999437ff49ddc3db86665f8
https://github.com/apache/fluo-recipes/blob/24c11234c9654b16d999437ff49ddc3db86665f8/modules/core/src/main/java/org/apache/fluo/recipes/core/export/ExportBucket.java#L123-L125
144,083
olivergondza/dumpling
core/src/main/java/com/github/olivergondza/dumpling/model/ThreadSet.java
ThreadSet.onlyThread
public @Nonnull ThreadType onlyThread() throws IllegalStateException { if (size() != 1) throw new IllegalStateException( "Exactly one thread expected in the set. Found " + size() ); return threads.iterator().next(); }
java
public @Nonnull ThreadType onlyThread() throws IllegalStateException { if (size() != 1) throw new IllegalStateException( "Exactly one thread expected in the set. Found " + size() ); return threads.iterator().next(); }
[ "public", "@", "Nonnull", "ThreadType", "onlyThread", "(", ")", "throws", "IllegalStateException", "{", "if", "(", "size", "(", ")", "!=", "1", ")", "throw", "new", "IllegalStateException", "(", "\"Exactly one thread expected in the set. Found \"", "+", "size", "(", ")", ")", ";", "return", "threads", ".", "iterator", "(", ")", ".", "next", "(", ")", ";", "}" ]
Extract the only thread from set. @throws IllegalStateException if not exactly one thread present.
[ "Extract", "the", "only", "thread", "from", "set", "." ]
ac698735fcc7c023db0c1637cc1f522cb3576c7f
https://github.com/olivergondza/dumpling/blob/ac698735fcc7c023db0c1637cc1f522cb3576c7f/core/src/main/java/com/github/olivergondza/dumpling/model/ThreadSet.java#L75-L81
144,084
olivergondza/dumpling
core/src/main/java/com/github/olivergondza/dumpling/model/ThreadSet.java
ThreadSet.getBlockedThreads
public @Nonnull SetType getBlockedThreads() { Set<ThreadLock> acquired = new HashSet<ThreadLock>(); for (ThreadType thread: threads) { acquired.addAll(thread.getAcquiredLocks()); } Set<ThreadType> blocked = new HashSet<ThreadType>(); for (ThreadType thread: runtime.getThreads()) { if (acquired.contains(thread.getWaitingToLock())) { blocked.add(thread); } } return runtime.getThreadSet(blocked); }
java
public @Nonnull SetType getBlockedThreads() { Set<ThreadLock> acquired = new HashSet<ThreadLock>(); for (ThreadType thread: threads) { acquired.addAll(thread.getAcquiredLocks()); } Set<ThreadType> blocked = new HashSet<ThreadType>(); for (ThreadType thread: runtime.getThreads()) { if (acquired.contains(thread.getWaitingToLock())) { blocked.add(thread); } } return runtime.getThreadSet(blocked); }
[ "public", "@", "Nonnull", "SetType", "getBlockedThreads", "(", ")", "{", "Set", "<", "ThreadLock", ">", "acquired", "=", "new", "HashSet", "<", "ThreadLock", ">", "(", ")", ";", "for", "(", "ThreadType", "thread", ":", "threads", ")", "{", "acquired", ".", "addAll", "(", "thread", ".", "getAcquiredLocks", "(", ")", ")", ";", "}", "Set", "<", "ThreadType", ">", "blocked", "=", "new", "HashSet", "<", "ThreadType", ">", "(", ")", ";", "for", "(", "ThreadType", "thread", ":", "runtime", ".", "getThreads", "(", ")", ")", "{", "if", "(", "acquired", ".", "contains", "(", "thread", ".", "getWaitingToLock", "(", ")", ")", ")", "{", "blocked", ".", "add", "(", "thread", ")", ";", "}", "}", "return", "runtime", ".", "getThreadSet", "(", "blocked", ")", ";", "}" ]
Get threads blocked by any of current threads.
[ "Get", "threads", "blocked", "by", "any", "of", "current", "threads", "." ]
ac698735fcc7c023db0c1637cc1f522cb3576c7f
https://github.com/olivergondza/dumpling/blob/ac698735fcc7c023db0c1637cc1f522cb3576c7f/core/src/main/java/com/github/olivergondza/dumpling/model/ThreadSet.java#L86-L100
144,085
olivergondza/dumpling
core/src/main/java/com/github/olivergondza/dumpling/model/ThreadSet.java
ThreadSet.getBlockingThreads
public @Nonnull SetType getBlockingThreads() { Set<ThreadLock> waitingTo = new HashSet<ThreadLock>(); for (ThreadType thread: threads) { if (thread.getWaitingToLock() != null) { waitingTo.add(thread.getWaitingToLock()); } } Set<ThreadType> blocking = new HashSet<ThreadType>(); for (ThreadType thread: runtime.getThreads()) { Set<ThreadLock> threadHolding = thread.getAcquiredLocks(); threadHolding.retainAll(waitingTo); if (!threadHolding.isEmpty()) { blocking.add(thread); } } return runtime.getThreadSet(blocking); }
java
public @Nonnull SetType getBlockingThreads() { Set<ThreadLock> waitingTo = new HashSet<ThreadLock>(); for (ThreadType thread: threads) { if (thread.getWaitingToLock() != null) { waitingTo.add(thread.getWaitingToLock()); } } Set<ThreadType> blocking = new HashSet<ThreadType>(); for (ThreadType thread: runtime.getThreads()) { Set<ThreadLock> threadHolding = thread.getAcquiredLocks(); threadHolding.retainAll(waitingTo); if (!threadHolding.isEmpty()) { blocking.add(thread); } } return runtime.getThreadSet(blocking); }
[ "public", "@", "Nonnull", "SetType", "getBlockingThreads", "(", ")", "{", "Set", "<", "ThreadLock", ">", "waitingTo", "=", "new", "HashSet", "<", "ThreadLock", ">", "(", ")", ";", "for", "(", "ThreadType", "thread", ":", "threads", ")", "{", "if", "(", "thread", ".", "getWaitingToLock", "(", ")", "!=", "null", ")", "{", "waitingTo", ".", "add", "(", "thread", ".", "getWaitingToLock", "(", ")", ")", ";", "}", "}", "Set", "<", "ThreadType", ">", "blocking", "=", "new", "HashSet", "<", "ThreadType", ">", "(", ")", ";", "for", "(", "ThreadType", "thread", ":", "runtime", ".", "getThreads", "(", ")", ")", "{", "Set", "<", "ThreadLock", ">", "threadHolding", "=", "thread", ".", "getAcquiredLocks", "(", ")", ";", "threadHolding", ".", "retainAll", "(", "waitingTo", ")", ";", "if", "(", "!", "threadHolding", ".", "isEmpty", "(", ")", ")", "{", "blocking", ".", "add", "(", "thread", ")", ";", "}", "}", "return", "runtime", ".", "getThreadSet", "(", "blocking", ")", ";", "}" ]
Get threads blocking any of current threads.
[ "Get", "threads", "blocking", "any", "of", "current", "threads", "." ]
ac698735fcc7c023db0c1637cc1f522cb3576c7f
https://github.com/olivergondza/dumpling/blob/ac698735fcc7c023db0c1637cc1f522cb3576c7f/core/src/main/java/com/github/olivergondza/dumpling/model/ThreadSet.java#L105-L123
144,086
olivergondza/dumpling
core/src/main/java/com/github/olivergondza/dumpling/model/ThreadSet.java
ThreadSet.where
public @Nonnull SetType where(ProcessThread.Predicate pred) { HashSet<ThreadType> subset = new HashSet<ThreadType>(size() / 2); for (ThreadType thread: threads) { if (pred.isValid(thread)) subset.add(thread); } return runtime.getThreadSet(subset); }
java
public @Nonnull SetType where(ProcessThread.Predicate pred) { HashSet<ThreadType> subset = new HashSet<ThreadType>(size() / 2); for (ThreadType thread: threads) { if (pred.isValid(thread)) subset.add(thread); } return runtime.getThreadSet(subset); }
[ "public", "@", "Nonnull", "SetType", "where", "(", "ProcessThread", ".", "Predicate", "pred", ")", "{", "HashSet", "<", "ThreadType", ">", "subset", "=", "new", "HashSet", "<", "ThreadType", ">", "(", "size", "(", ")", "/", "2", ")", ";", "for", "(", "ThreadType", "thread", ":", "threads", ")", "{", "if", "(", "pred", ".", "isValid", "(", "thread", ")", ")", "subset", ".", "add", "(", "thread", ")", ";", "}", "return", "runtime", ".", "getThreadSet", "(", "subset", ")", ";", "}" ]
Get subset of current threads. @param pred Predicate to match. @return {@link ThreadSet} scoped to current runtime containing subset of threads that match the predicate.
[ "Get", "subset", "of", "current", "threads", "." ]
ac698735fcc7c023db0c1637cc1f522cb3576c7f
https://github.com/olivergondza/dumpling/blob/ac698735fcc7c023db0c1637cc1f522cb3576c7f/core/src/main/java/com/github/olivergondza/dumpling/model/ThreadSet.java#L139-L146
144,087
olivergondza/dumpling
core/src/main/java/com/github/olivergondza/dumpling/model/ThreadSet.java
ThreadSet.query
public <T extends SingleThreadSetQuery.Result<SetType, RuntimeType, ThreadType>> T query(SingleThreadSetQuery<T> query) { return query.<SetType, RuntimeType, ThreadType>query((SetType) this); }
java
public <T extends SingleThreadSetQuery.Result<SetType, RuntimeType, ThreadType>> T query(SingleThreadSetQuery<T> query) { return query.<SetType, RuntimeType, ThreadType>query((SetType) this); }
[ "public", "<", "T", "extends", "SingleThreadSetQuery", ".", "Result", "<", "SetType", ",", "RuntimeType", ",", "ThreadType", ">", ">", "T", "query", "(", "SingleThreadSetQuery", "<", "T", ">", "query", ")", "{", "return", "query", ".", "<", "SetType", ",", "RuntimeType", ",", "ThreadType", ">", "query", "(", "(", "SetType", ")", "this", ")", ";", "}" ]
Run query using this as an initial thread set.
[ "Run", "query", "using", "this", "as", "an", "initial", "thread", "set", "." ]
ac698735fcc7c023db0c1637cc1f522cb3576c7f
https://github.com/olivergondza/dumpling/blob/ac698735fcc7c023db0c1637cc1f522cb3576c7f/core/src/main/java/com/github/olivergondza/dumpling/model/ThreadSet.java#L151-L153
144,088
olivergondza/dumpling
core/src/main/java/com/github/olivergondza/dumpling/factory/jmx/JmxLocalProcessConnector.java
JmxLocalProcessConnector.getServerConnection
@SuppressWarnings("unused") private static MBeanServerConnection getServerConnection(int pid) { try { JMXServiceURL serviceURL = new JMXServiceURL(connectorAddress(pid)); return JMXConnectorFactory.connect(serviceURL).getMBeanServerConnection(); } catch (MalformedURLException ex) { throw failed("JMX connection failed", ex); } catch (IOException ex) { throw failed("JMX connection failed", ex); } }
java
@SuppressWarnings("unused") private static MBeanServerConnection getServerConnection(int pid) { try { JMXServiceURL serviceURL = new JMXServiceURL(connectorAddress(pid)); return JMXConnectorFactory.connect(serviceURL).getMBeanServerConnection(); } catch (MalformedURLException ex) { throw failed("JMX connection failed", ex); } catch (IOException ex) { throw failed("JMX connection failed", ex); } }
[ "@", "SuppressWarnings", "(", "\"unused\"", ")", "private", "static", "MBeanServerConnection", "getServerConnection", "(", "int", "pid", ")", "{", "try", "{", "JMXServiceURL", "serviceURL", "=", "new", "JMXServiceURL", "(", "connectorAddress", "(", "pid", ")", ")", ";", "return", "JMXConnectorFactory", ".", "connect", "(", "serviceURL", ")", ".", "getMBeanServerConnection", "(", ")", ";", "}", "catch", "(", "MalformedURLException", "ex", ")", "{", "throw", "failed", "(", "\"JMX connection failed\"", ",", "ex", ")", ";", "}", "catch", "(", "IOException", "ex", ")", "{", "throw", "failed", "(", "\"JMX connection failed\"", ",", "ex", ")", ";", "}", "}" ]
This has to be called by reflection so it can as well be private to stress this is not an API
[ "This", "has", "to", "be", "called", "by", "reflection", "so", "it", "can", "as", "well", "be", "private", "to", "stress", "this", "is", "not", "an", "API" ]
ac698735fcc7c023db0c1637cc1f522cb3576c7f
https://github.com/olivergondza/dumpling/blob/ac698735fcc7c023db0c1637cc1f522cb3576c7f/core/src/main/java/com/github/olivergondza/dumpling/factory/jmx/JmxLocalProcessConnector.java#L61-L73
144,089
olivergondza/dumpling
core/src/main/java/com/github/olivergondza/dumpling/factory/ThreadDumpFactory.java
ThreadDumpFactory.getMonitorJustAcquired
private Monitor getMonitorJustAcquired(List<ThreadLock.Monitor> monitors) { if (monitors.isEmpty()) return null; Monitor monitor = monitors.get(0); if (monitor.getDepth() != 0) return null; for (Monitor duplicateCandidate: monitors) { if (monitor.equals(duplicateCandidate)) continue; // skip first - equality includes monitor depth if (monitor.getLock().equals(duplicateCandidate.getLock())) return null; // Acquired earlier } return monitor; }
java
private Monitor getMonitorJustAcquired(List<ThreadLock.Monitor> monitors) { if (monitors.isEmpty()) return null; Monitor monitor = monitors.get(0); if (monitor.getDepth() != 0) return null; for (Monitor duplicateCandidate: monitors) { if (monitor.equals(duplicateCandidate)) continue; // skip first - equality includes monitor depth if (monitor.getLock().equals(duplicateCandidate.getLock())) return null; // Acquired earlier } return monitor; }
[ "private", "Monitor", "getMonitorJustAcquired", "(", "List", "<", "ThreadLock", ".", "Monitor", ">", "monitors", ")", "{", "if", "(", "monitors", ".", "isEmpty", "(", ")", ")", "return", "null", ";", "Monitor", "monitor", "=", "monitors", ".", "get", "(", "0", ")", ";", "if", "(", "monitor", ".", "getDepth", "(", ")", "!=", "0", ")", "return", "null", ";", "for", "(", "Monitor", "duplicateCandidate", ":", "monitors", ")", "{", "if", "(", "monitor", ".", "equals", "(", "duplicateCandidate", ")", ")", "continue", ";", "// skip first - equality includes monitor depth", "if", "(", "monitor", ".", "getLock", "(", ")", ".", "equals", "(", "duplicateCandidate", ".", "getLock", "(", ")", ")", ")", "return", "null", ";", "// Acquired earlier", "}", "return", "monitor", ";", "}" ]
get monitor acquired on current stackframe, null when it was acquired earlier or not monitor is held
[ "get", "monitor", "acquired", "on", "current", "stackframe", "null", "when", "it", "was", "acquired", "earlier", "or", "not", "monitor", "is", "held" ]
ac698735fcc7c023db0c1637cc1f522cb3576c7f
https://github.com/olivergondza/dumpling/blob/ac698735fcc7c023db0c1637cc1f522cb3576c7f/core/src/main/java/com/github/olivergondza/dumpling/factory/ThreadDumpFactory.java#L330-L342
144,090
olivergondza/dumpling
groovy-api/src/main/java/com/github/olivergondza/dumpling/groovy/GroovyInterpretterConfig.java
GroovyInterpretterConfig.setupDecorateMethods
public void setupDecorateMethods(ClassLoader cl) { synchronized (STAR_IMPORTS) { if (DECORATED) return; GroovyShell shell = new GroovyShell(cl, new Binding(), getCompilerConfiguration()); try { shell.run( new InputStreamReader(this.getClass().getResourceAsStream("extend.groovy")), "dumpling-metaclass-setup", Collections.emptyList() ); } catch (Exception ex) { AssertionError err = new AssertionError("Unable to decorate object model"); err.initCause(ex); throw err; // Java 6 } DECORATED = true; } }
java
public void setupDecorateMethods(ClassLoader cl) { synchronized (STAR_IMPORTS) { if (DECORATED) return; GroovyShell shell = new GroovyShell(cl, new Binding(), getCompilerConfiguration()); try { shell.run( new InputStreamReader(this.getClass().getResourceAsStream("extend.groovy")), "dumpling-metaclass-setup", Collections.emptyList() ); } catch (Exception ex) { AssertionError err = new AssertionError("Unable to decorate object model"); err.initCause(ex); throw err; // Java 6 } DECORATED = true; } }
[ "public", "void", "setupDecorateMethods", "(", "ClassLoader", "cl", ")", "{", "synchronized", "(", "STAR_IMPORTS", ")", "{", "if", "(", "DECORATED", ")", "return", ";", "GroovyShell", "shell", "=", "new", "GroovyShell", "(", "cl", ",", "new", "Binding", "(", ")", ",", "getCompilerConfiguration", "(", ")", ")", ";", "try", "{", "shell", ".", "run", "(", "new", "InputStreamReader", "(", "this", ".", "getClass", "(", ")", ".", "getResourceAsStream", "(", "\"extend.groovy\"", ")", ")", ",", "\"dumpling-metaclass-setup\"", ",", "Collections", ".", "emptyList", "(", ")", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "AssertionError", "err", "=", "new", "AssertionError", "(", "\"Unable to decorate object model\"", ")", ";", "err", ".", "initCause", "(", "ex", ")", ";", "throw", "err", ";", "// Java 6", "}", "DECORATED", "=", "true", ";", "}", "}" ]
Decorate Dumpling API with groovy extensions.
[ "Decorate", "Dumpling", "API", "with", "groovy", "extensions", "." ]
ac698735fcc7c023db0c1637cc1f522cb3576c7f
https://github.com/olivergondza/dumpling/blob/ac698735fcc7c023db0c1637cc1f522cb3576c7f/groovy-api/src/main/java/com/github/olivergondza/dumpling/groovy/GroovyInterpretterConfig.java#L95-L114
144,091
seam/faces
impl/src/main/java/org/jboss/seam/faces/security/SecurityPhaseListener.java
SecurityPhaseListener.performObservation
private void performObservation(PhaseEvent event, PhaseIdType phaseIdType) { UIViewRoot viewRoot = (UIViewRoot) event.getFacesContext().getViewRoot(); List<? extends Annotation> restrictionsForPhase = getRestrictionsForPhase(phaseIdType, viewRoot.getViewId()); if (restrictionsForPhase != null) { log.debugf("Enforcing on phase %s", phaseIdType); enforce(event.getFacesContext(), viewRoot, restrictionsForPhase); } }
java
private void performObservation(PhaseEvent event, PhaseIdType phaseIdType) { UIViewRoot viewRoot = (UIViewRoot) event.getFacesContext().getViewRoot(); List<? extends Annotation> restrictionsForPhase = getRestrictionsForPhase(phaseIdType, viewRoot.getViewId()); if (restrictionsForPhase != null) { log.debugf("Enforcing on phase %s", phaseIdType); enforce(event.getFacesContext(), viewRoot, restrictionsForPhase); } }
[ "private", "void", "performObservation", "(", "PhaseEvent", "event", ",", "PhaseIdType", "phaseIdType", ")", "{", "UIViewRoot", "viewRoot", "=", "(", "UIViewRoot", ")", "event", ".", "getFacesContext", "(", ")", ".", "getViewRoot", "(", ")", ";", "List", "<", "?", "extends", "Annotation", ">", "restrictionsForPhase", "=", "getRestrictionsForPhase", "(", "phaseIdType", ",", "viewRoot", ".", "getViewId", "(", ")", ")", ";", "if", "(", "restrictionsForPhase", "!=", "null", ")", "{", "log", ".", "debugf", "(", "\"Enforcing on phase %s\"", ",", "phaseIdType", ")", ";", "enforce", "(", "event", ".", "getFacesContext", "(", ")", ",", "viewRoot", ",", "restrictionsForPhase", ")", ";", "}", "}" ]
Inspect the annotations in the ViewConfigStore, enforcing any restrictions applicable to this phase @param event @param phaseIdType
[ "Inspect", "the", "annotations", "in", "the", "ViewConfigStore", "enforcing", "any", "restrictions", "applicable", "to", "this", "phase" ]
2fdedbc7070318c2c58bfffb8a26f1ea1d0ee1e3
https://github.com/seam/faces/blob/2fdedbc7070318c2c58bfffb8a26f1ea1d0ee1e3/impl/src/main/java/org/jboss/seam/faces/security/SecurityPhaseListener.java#L150-L157
144,092
seam/faces
impl/src/main/java/org/jboss/seam/faces/security/SecurityPhaseListener.java
SecurityPhaseListener.isAnnotationApplicableToPhase
public boolean isAnnotationApplicableToPhase(Annotation annotation, PhaseIdType currentPhase, PhaseIdType[] defaultPhases) { Method restrictAtViewMethod = getRestrictAtViewMethod(annotation); PhaseIdType[] phasedIds = null; if (restrictAtViewMethod != null) { log.warnf("Annotation %s is using the restrictAtViewMethod. Use a @RestrictAtPhase qualifier on the annotation instead."); phasedIds = getRestrictedPhaseIds(restrictAtViewMethod, annotation); } RestrictAtPhase restrictAtPhaseQualifier = AnnotationInspector.getAnnotation(annotation.annotationType(), RestrictAtPhase.class, beanManager); if (restrictAtPhaseQualifier != null) { log.debug("Using Phases found in @RestrictAtView qualifier on the annotation."); phasedIds = restrictAtPhaseQualifier.value(); } if (phasedIds == null) { log.debug("Falling back on default phase ids"); phasedIds = defaultPhases; } if (Arrays.binarySearch(phasedIds, currentPhase) >= 0) { return true; } return false; }
java
public boolean isAnnotationApplicableToPhase(Annotation annotation, PhaseIdType currentPhase, PhaseIdType[] defaultPhases) { Method restrictAtViewMethod = getRestrictAtViewMethod(annotation); PhaseIdType[] phasedIds = null; if (restrictAtViewMethod != null) { log.warnf("Annotation %s is using the restrictAtViewMethod. Use a @RestrictAtPhase qualifier on the annotation instead."); phasedIds = getRestrictedPhaseIds(restrictAtViewMethod, annotation); } RestrictAtPhase restrictAtPhaseQualifier = AnnotationInspector.getAnnotation(annotation.annotationType(), RestrictAtPhase.class, beanManager); if (restrictAtPhaseQualifier != null) { log.debug("Using Phases found in @RestrictAtView qualifier on the annotation."); phasedIds = restrictAtPhaseQualifier.value(); } if (phasedIds == null) { log.debug("Falling back on default phase ids"); phasedIds = defaultPhases; } if (Arrays.binarySearch(phasedIds, currentPhase) >= 0) { return true; } return false; }
[ "public", "boolean", "isAnnotationApplicableToPhase", "(", "Annotation", "annotation", ",", "PhaseIdType", "currentPhase", ",", "PhaseIdType", "[", "]", "defaultPhases", ")", "{", "Method", "restrictAtViewMethod", "=", "getRestrictAtViewMethod", "(", "annotation", ")", ";", "PhaseIdType", "[", "]", "phasedIds", "=", "null", ";", "if", "(", "restrictAtViewMethod", "!=", "null", ")", "{", "log", ".", "warnf", "(", "\"Annotation %s is using the restrictAtViewMethod. Use a @RestrictAtPhase qualifier on the annotation instead.\"", ")", ";", "phasedIds", "=", "getRestrictedPhaseIds", "(", "restrictAtViewMethod", ",", "annotation", ")", ";", "}", "RestrictAtPhase", "restrictAtPhaseQualifier", "=", "AnnotationInspector", ".", "getAnnotation", "(", "annotation", ".", "annotationType", "(", ")", ",", "RestrictAtPhase", ".", "class", ",", "beanManager", ")", ";", "if", "(", "restrictAtPhaseQualifier", "!=", "null", ")", "{", "log", ".", "debug", "(", "\"Using Phases found in @RestrictAtView qualifier on the annotation.\"", ")", ";", "phasedIds", "=", "restrictAtPhaseQualifier", ".", "value", "(", ")", ";", "}", "if", "(", "phasedIds", "==", "null", ")", "{", "log", ".", "debug", "(", "\"Falling back on default phase ids\"", ")", ";", "phasedIds", "=", "defaultPhases", ";", "}", "if", "(", "Arrays", ".", "binarySearch", "(", "phasedIds", ",", "currentPhase", ")", ">=", "0", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}" ]
Inspect an annotation to see if it specifies a view in which it should be. Fall back on default view otherwise. @param annotation @param currentPhase @param defaultPhases @return true if the annotation is applicable to this view and phase, false otherwise
[ "Inspect", "an", "annotation", "to", "see", "if", "it", "specifies", "a", "view", "in", "which", "it", "should", "be", ".", "Fall", "back", "on", "default", "view", "otherwise", "." ]
2fdedbc7070318c2c58bfffb8a26f1ea1d0ee1e3
https://github.com/seam/faces/blob/2fdedbc7070318c2c58bfffb8a26f1ea1d0ee1e3/impl/src/main/java/org/jboss/seam/faces/security/SecurityPhaseListener.java#L190-L210
144,093
seam/faces
impl/src/main/java/org/jboss/seam/faces/security/SecurityPhaseListener.java
SecurityPhaseListener.getRestrictAtViewMethod
public Method getRestrictAtViewMethod(Annotation annotation) { Method restrictAtViewMethod; try { restrictAtViewMethod = annotation.annotationType().getDeclaredMethod("restrictAtPhase"); } catch (NoSuchMethodException ex) { restrictAtViewMethod = null; } catch (SecurityException ex) { throw new IllegalArgumentException("restrictAtView method must be accessible", ex); } return restrictAtViewMethod; }
java
public Method getRestrictAtViewMethod(Annotation annotation) { Method restrictAtViewMethod; try { restrictAtViewMethod = annotation.annotationType().getDeclaredMethod("restrictAtPhase"); } catch (NoSuchMethodException ex) { restrictAtViewMethod = null; } catch (SecurityException ex) { throw new IllegalArgumentException("restrictAtView method must be accessible", ex); } return restrictAtViewMethod; }
[ "public", "Method", "getRestrictAtViewMethod", "(", "Annotation", "annotation", ")", "{", "Method", "restrictAtViewMethod", ";", "try", "{", "restrictAtViewMethod", "=", "annotation", ".", "annotationType", "(", ")", ".", "getDeclaredMethod", "(", "\"restrictAtPhase\"", ")", ";", "}", "catch", "(", "NoSuchMethodException", "ex", ")", "{", "restrictAtViewMethod", "=", "null", ";", "}", "catch", "(", "SecurityException", "ex", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"restrictAtView method must be accessible\"", ",", "ex", ")", ";", "}", "return", "restrictAtViewMethod", ";", "}" ]
Utility method to extract the "restrictAtPhase" method from an annotation @param annotation @return restrictAtViewMethod if found, null otherwise
[ "Utility", "method", "to", "extract", "the", "restrictAtPhase", "method", "from", "an", "annotation" ]
2fdedbc7070318c2c58bfffb8a26f1ea1d0ee1e3
https://github.com/seam/faces/blob/2fdedbc7070318c2c58bfffb8a26f1ea1d0ee1e3/impl/src/main/java/org/jboss/seam/faces/security/SecurityPhaseListener.java#L237-L247
144,094
seam/faces
impl/src/main/java/org/jboss/seam/faces/security/SecurityPhaseListener.java
SecurityPhaseListener.getRestrictedPhaseIds
public PhaseIdType[] getRestrictedPhaseIds(Method restrictAtViewMethod, Annotation annotation) { PhaseIdType[] phaseIds; try { phaseIds = (PhaseIdType[]) restrictAtViewMethod.invoke(annotation); } catch (IllegalAccessException ex) { throw new IllegalArgumentException("restrictAtView method must be accessible", ex); } catch (InvocationTargetException ex) { throw new RuntimeException(ex); } return phaseIds; }
java
public PhaseIdType[] getRestrictedPhaseIds(Method restrictAtViewMethod, Annotation annotation) { PhaseIdType[] phaseIds; try { phaseIds = (PhaseIdType[]) restrictAtViewMethod.invoke(annotation); } catch (IllegalAccessException ex) { throw new IllegalArgumentException("restrictAtView method must be accessible", ex); } catch (InvocationTargetException ex) { throw new RuntimeException(ex); } return phaseIds; }
[ "public", "PhaseIdType", "[", "]", "getRestrictedPhaseIds", "(", "Method", "restrictAtViewMethod", ",", "Annotation", "annotation", ")", "{", "PhaseIdType", "[", "]", "phaseIds", ";", "try", "{", "phaseIds", "=", "(", "PhaseIdType", "[", "]", ")", "restrictAtViewMethod", ".", "invoke", "(", "annotation", ")", ";", "}", "catch", "(", "IllegalAccessException", "ex", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"restrictAtView method must be accessible\"", ",", "ex", ")", ";", "}", "catch", "(", "InvocationTargetException", "ex", ")", "{", "throw", "new", "RuntimeException", "(", "ex", ")", ";", "}", "return", "phaseIds", ";", "}" ]
Retrieve the default PhaseIdTypes defined by the restrictAtViewMethod in the annotation @param restrictAtViewMethod @param annotation @return PhaseIdTypes from the restrictAtViewMethod, null if empty
[ "Retrieve", "the", "default", "PhaseIdTypes", "defined", "by", "the", "restrictAtViewMethod", "in", "the", "annotation" ]
2fdedbc7070318c2c58bfffb8a26f1ea1d0ee1e3
https://github.com/seam/faces/blob/2fdedbc7070318c2c58bfffb8a26f1ea1d0ee1e3/impl/src/main/java/org/jboss/seam/faces/security/SecurityPhaseListener.java#L256-L266
144,095
apache/fluo-recipes
modules/core/src/main/java/org/apache/fluo/recipes/core/common/TableOptimizations.java
TableOptimizations.getConfiguredOptimizations
public static TableOptimizations getConfiguredOptimizations(FluoConfiguration fluoConfig) { try (FluoClient client = FluoFactory.newClient(fluoConfig)) { SimpleConfiguration appConfig = client.getAppConfiguration(); TableOptimizations tableOptim = new TableOptimizations(); SimpleConfiguration subset = appConfig.subset(PREFIX.substring(0, PREFIX.length() - 1)); Iterator<String> keys = subset.getKeys(); while (keys.hasNext()) { String key = keys.next(); String clazz = subset.getString(key); try { TableOptimizationsFactory factory = Class.forName(clazz).asSubclass(TableOptimizationsFactory.class).newInstance(); tableOptim.merge(factory.getTableOptimizations(key, appConfig)); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { throw new RuntimeException(e); } } return tableOptim; } }
java
public static TableOptimizations getConfiguredOptimizations(FluoConfiguration fluoConfig) { try (FluoClient client = FluoFactory.newClient(fluoConfig)) { SimpleConfiguration appConfig = client.getAppConfiguration(); TableOptimizations tableOptim = new TableOptimizations(); SimpleConfiguration subset = appConfig.subset(PREFIX.substring(0, PREFIX.length() - 1)); Iterator<String> keys = subset.getKeys(); while (keys.hasNext()) { String key = keys.next(); String clazz = subset.getString(key); try { TableOptimizationsFactory factory = Class.forName(clazz).asSubclass(TableOptimizationsFactory.class).newInstance(); tableOptim.merge(factory.getTableOptimizations(key, appConfig)); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { throw new RuntimeException(e); } } return tableOptim; } }
[ "public", "static", "TableOptimizations", "getConfiguredOptimizations", "(", "FluoConfiguration", "fluoConfig", ")", "{", "try", "(", "FluoClient", "client", "=", "FluoFactory", ".", "newClient", "(", "fluoConfig", ")", ")", "{", "SimpleConfiguration", "appConfig", "=", "client", ".", "getAppConfiguration", "(", ")", ";", "TableOptimizations", "tableOptim", "=", "new", "TableOptimizations", "(", ")", ";", "SimpleConfiguration", "subset", "=", "appConfig", ".", "subset", "(", "PREFIX", ".", "substring", "(", "0", ",", "PREFIX", ".", "length", "(", ")", "-", "1", ")", ")", ";", "Iterator", "<", "String", ">", "keys", "=", "subset", ".", "getKeys", "(", ")", ";", "while", "(", "keys", ".", "hasNext", "(", ")", ")", "{", "String", "key", "=", "keys", ".", "next", "(", ")", ";", "String", "clazz", "=", "subset", ".", "getString", "(", "key", ")", ";", "try", "{", "TableOptimizationsFactory", "factory", "=", "Class", ".", "forName", "(", "clazz", ")", ".", "asSubclass", "(", "TableOptimizationsFactory", ".", "class", ")", ".", "newInstance", "(", ")", ";", "tableOptim", ".", "merge", "(", "factory", ".", "getTableOptimizations", "(", "key", ",", "appConfig", ")", ")", ";", "}", "catch", "(", "InstantiationException", "|", "IllegalAccessException", "|", "ClassNotFoundException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "}", "return", "tableOptim", ";", "}", "}" ]
A utility method to get all registered table optimizations. Many recipes will automatically register table optimizations when configured.
[ "A", "utility", "method", "to", "get", "all", "registered", "table", "optimizations", ".", "Many", "recipes", "will", "automatically", "register", "table", "optimizations", "when", "configured", "." ]
24c11234c9654b16d999437ff49ddc3db86665f8
https://github.com/apache/fluo-recipes/blob/24c11234c9654b16d999437ff49ddc3db86665f8/modules/core/src/main/java/org/apache/fluo/recipes/core/common/TableOptimizations.java#L94-L115
144,096
apache/fluo-recipes
modules/core/src/main/java/org/apache/fluo/recipes/core/common/TransientRegistry.java
TransientRegistry.addTransientRange
public void addTransientRange(String id, RowRange range) { String start = DatatypeConverter.printHexBinary(range.getStart().toArray()); String end = DatatypeConverter.printHexBinary(range.getEnd().toArray()); appConfig.setProperty(PREFIX + id, start + ":" + end); }
java
public void addTransientRange(String id, RowRange range) { String start = DatatypeConverter.printHexBinary(range.getStart().toArray()); String end = DatatypeConverter.printHexBinary(range.getEnd().toArray()); appConfig.setProperty(PREFIX + id, start + ":" + end); }
[ "public", "void", "addTransientRange", "(", "String", "id", ",", "RowRange", "range", ")", "{", "String", "start", "=", "DatatypeConverter", ".", "printHexBinary", "(", "range", ".", "getStart", "(", ")", ".", "toArray", "(", ")", ")", ";", "String", "end", "=", "DatatypeConverter", ".", "printHexBinary", "(", "range", ".", "getEnd", "(", ")", ".", "toArray", "(", ")", ")", ";", "appConfig", ".", "setProperty", "(", "PREFIX", "+", "id", ",", "start", "+", "\":\"", "+", "end", ")", ";", "}" ]
This method is expected to be called before Fluo is initialized to register transient ranges.
[ "This", "method", "is", "expected", "to", "be", "called", "before", "Fluo", "is", "initialized", "to", "register", "transient", "ranges", "." ]
24c11234c9654b16d999437ff49ddc3db86665f8
https://github.com/apache/fluo-recipes/blob/24c11234c9654b16d999437ff49ddc3db86665f8/modules/core/src/main/java/org/apache/fluo/recipes/core/common/TransientRegistry.java#L55-L60
144,097
apache/fluo-recipes
modules/core/src/main/java/org/apache/fluo/recipes/core/common/TransientRegistry.java
TransientRegistry.getTransientRanges
public List<RowRange> getTransientRanges() { List<RowRange> ranges = new ArrayList<>(); Iterator<String> keys = appConfig.getKeys(PREFIX.substring(0, PREFIX.length() - 1)); while (keys.hasNext()) { String key = keys.next(); String val = appConfig.getString(key); String[] sa = val.split(":"); RowRange rowRange = new RowRange(Bytes.of(DatatypeConverter.parseHexBinary(sa[0])), Bytes.of(DatatypeConverter.parseHexBinary(sa[1]))); ranges.add(rowRange); } return ranges; }
java
public List<RowRange> getTransientRanges() { List<RowRange> ranges = new ArrayList<>(); Iterator<String> keys = appConfig.getKeys(PREFIX.substring(0, PREFIX.length() - 1)); while (keys.hasNext()) { String key = keys.next(); String val = appConfig.getString(key); String[] sa = val.split(":"); RowRange rowRange = new RowRange(Bytes.of(DatatypeConverter.parseHexBinary(sa[0])), Bytes.of(DatatypeConverter.parseHexBinary(sa[1]))); ranges.add(rowRange); } return ranges; }
[ "public", "List", "<", "RowRange", ">", "getTransientRanges", "(", ")", "{", "List", "<", "RowRange", ">", "ranges", "=", "new", "ArrayList", "<>", "(", ")", ";", "Iterator", "<", "String", ">", "keys", "=", "appConfig", ".", "getKeys", "(", "PREFIX", ".", "substring", "(", "0", ",", "PREFIX", ".", "length", "(", ")", "-", "1", ")", ")", ";", "while", "(", "keys", ".", "hasNext", "(", ")", ")", "{", "String", "key", "=", "keys", ".", "next", "(", ")", ";", "String", "val", "=", "appConfig", ".", "getString", "(", "key", ")", ";", "String", "[", "]", "sa", "=", "val", ".", "split", "(", "\":\"", ")", ";", "RowRange", "rowRange", "=", "new", "RowRange", "(", "Bytes", ".", "of", "(", "DatatypeConverter", ".", "parseHexBinary", "(", "sa", "[", "0", "]", ")", ")", ",", "Bytes", ".", "of", "(", "DatatypeConverter", ".", "parseHexBinary", "(", "sa", "[", "1", "]", ")", ")", ")", ";", "ranges", ".", "add", "(", "rowRange", ")", ";", "}", "return", "ranges", ";", "}" ]
This method is expected to be called after Fluo is initialized to get the ranges that were registered before initialization.
[ "This", "method", "is", "expected", "to", "be", "called", "after", "Fluo", "is", "initialized", "to", "get", "the", "ranges", "that", "were", "registered", "before", "initialization", "." ]
24c11234c9654b16d999437ff49ddc3db86665f8
https://github.com/apache/fluo-recipes/blob/24c11234c9654b16d999437ff49ddc3db86665f8/modules/core/src/main/java/org/apache/fluo/recipes/core/common/TransientRegistry.java#L66-L78
144,098
seam/faces
impl/src/main/java/org/jboss/seam/faces/event/AbstractListener.java
AbstractListener.getEnabledListeners
@SuppressWarnings("unchecked") protected List<T> getEnabledListeners(Class<? extends T>... classes) { List<T> listeners = new ArrayList<T>(); for (Class<? extends T> clazz : classes) { Set<Bean<?>> beans = getBeanManager().getBeans(clazz); if (!beans.isEmpty()) { Bean<T> bean = (Bean<T>) getBeanManager().resolve(beans); CreationalContext<T> context = getBeanManager().createCreationalContext(bean); listeners.add((T) getBeanManager().getReference(bean, clazz, context)); } } return listeners; }
java
@SuppressWarnings("unchecked") protected List<T> getEnabledListeners(Class<? extends T>... classes) { List<T> listeners = new ArrayList<T>(); for (Class<? extends T> clazz : classes) { Set<Bean<?>> beans = getBeanManager().getBeans(clazz); if (!beans.isEmpty()) { Bean<T> bean = (Bean<T>) getBeanManager().resolve(beans); CreationalContext<T> context = getBeanManager().createCreationalContext(bean); listeners.add((T) getBeanManager().getReference(bean, clazz, context)); } } return listeners; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "protected", "List", "<", "T", ">", "getEnabledListeners", "(", "Class", "<", "?", "extends", "T", ">", "...", "classes", ")", "{", "List", "<", "T", ">", "listeners", "=", "new", "ArrayList", "<", "T", ">", "(", ")", ";", "for", "(", "Class", "<", "?", "extends", "T", ">", "clazz", ":", "classes", ")", "{", "Set", "<", "Bean", "<", "?", ">", ">", "beans", "=", "getBeanManager", "(", ")", ".", "getBeans", "(", "clazz", ")", ";", "if", "(", "!", "beans", ".", "isEmpty", "(", ")", ")", "{", "Bean", "<", "T", ">", "bean", "=", "(", "Bean", "<", "T", ">", ")", "getBeanManager", "(", ")", ".", "resolve", "(", "beans", ")", ";", "CreationalContext", "<", "T", ">", "context", "=", "getBeanManager", "(", ")", ".", "createCreationalContext", "(", "bean", ")", ";", "listeners", ".", "add", "(", "(", "T", ")", "getBeanManager", "(", ")", ".", "getReference", "(", "bean", ",", "clazz", ",", "context", ")", ")", ";", "}", "}", "return", "listeners", ";", "}" ]
Create contextual instances for the specified listener classes, excluding any listeners that do not correspond to an enabled bean.
[ "Create", "contextual", "instances", "for", "the", "specified", "listener", "classes", "excluding", "any", "listeners", "that", "do", "not", "correspond", "to", "an", "enabled", "bean", "." ]
2fdedbc7070318c2c58bfffb8a26f1ea1d0ee1e3
https://github.com/seam/faces/blob/2fdedbc7070318c2c58bfffb8a26f1ea1d0ee1e3/impl/src/main/java/org/jboss/seam/faces/event/AbstractListener.java#L52-L64
144,099
apache/fluo-recipes
modules/core/src/main/java/org/apache/fluo/recipes/core/map/CollisionFreeMap.java
CollisionFreeMap.update
public void update(TransactionBase tx, Map<K, V> updates) { combineQ.addAll(tx, updates); }
java
public void update(TransactionBase tx, Map<K, V> updates) { combineQ.addAll(tx, updates); }
[ "public", "void", "update", "(", "TransactionBase", "tx", ",", "Map", "<", "K", ",", "V", ">", "updates", ")", "{", "combineQ", ".", "addAll", "(", "tx", ",", "updates", ")", ";", "}" ]
Queues updates for a collision free map. These updates will be made by an Observer executing another transaction. This method will not collide with other transaction queuing updates for the same keys. @param tx This transaction will be used to make the updates. @param updates The keys in the map should correspond to keys in the collision free map being updated. The values in the map will be queued for updating.
[ "Queues", "updates", "for", "a", "collision", "free", "map", ".", "These", "updates", "will", "be", "made", "by", "an", "Observer", "executing", "another", "transaction", ".", "This", "method", "will", "not", "collide", "with", "other", "transaction", "queuing", "updates", "for", "the", "same", "keys", "." ]
24c11234c9654b16d999437ff49ddc3db86665f8
https://github.com/apache/fluo-recipes/blob/24c11234c9654b16d999437ff49ddc3db86665f8/modules/core/src/main/java/org/apache/fluo/recipes/core/map/CollisionFreeMap.java#L199-L201