repository_name
stringlengths
7
54
func_path_in_repository
stringlengths
18
196
func_name
stringlengths
7
107
whole_func_string
stringlengths
76
3.82k
language
stringclasses
1 value
func_code_string
stringlengths
76
3.82k
func_code_tokens
listlengths
22
717
func_documentation_string
stringlengths
61
1.98k
func_documentation_tokens
listlengths
1
508
split_name
stringclasses
1 value
func_code_url
stringlengths
111
310
sebastiangraf/jSCSI
bundles/target/src/main/java/org/jscsi/target/settings/NumericalValueRange.java
NumericalValueRange.parseNumericalValueRange
public static final NumericalValueRange parseNumericalValueRange (final String value) { // check formatting final Matcher rangeMatcher = NUMERICAL_RANGE_PATTERN.matcher(value); if (!rangeMatcher.matches()) { return null; } int min, max; // split parameter at '~' sign and parse boundaries individually String[] numbers = value.split("~"); final SingleNumericalValue minVal = SingleNumericalValue.parseSingleNumericValue(numbers[0]); final SingleNumericalValue maxVal = SingleNumericalValue.parseSingleNumericValue(numbers[1]); if (minVal == null || maxVal == null) return null;// not possible, format checked by rangeMatcher min = minVal.getValue(); max = maxVal.getValue(); // return with sanity check, enforce min <= max return create(min, max); }
java
public static final NumericalValueRange parseNumericalValueRange (final String value) { // check formatting final Matcher rangeMatcher = NUMERICAL_RANGE_PATTERN.matcher(value); if (!rangeMatcher.matches()) { return null; } int min, max; // split parameter at '~' sign and parse boundaries individually String[] numbers = value.split("~"); final SingleNumericalValue minVal = SingleNumericalValue.parseSingleNumericValue(numbers[0]); final SingleNumericalValue maxVal = SingleNumericalValue.parseSingleNumericValue(numbers[1]); if (minVal == null || maxVal == null) return null;// not possible, format checked by rangeMatcher min = minVal.getValue(); max = maxVal.getValue(); // return with sanity check, enforce min <= max return create(min, max); }
[ "public", "static", "final", "NumericalValueRange", "parseNumericalValueRange", "(", "final", "String", "value", ")", "{", "// check formatting\r", "final", "Matcher", "rangeMatcher", "=", "NUMERICAL_RANGE_PATTERN", ".", "matcher", "(", "value", ")", ";", "if", "(", ...
Parses a {@link NumericalValueRange} from a {@link String}. The lower and boundaries must be separated by a '~' character and the the leading integer must not be larger than the trailing one. If these format requirements are violated the method will return <code>null</code>. @param value the {@link String} to parse @return a {@link NumericalValueRange} representing the interval in the parsed {@link String} or <code>null</code>
[ "Parses", "a", "{", "@link", "NumericalValueRange", "}", "from", "a", "{", "@link", "String", "}", ".", "The", "lower", "and", "boundaries", "must", "be", "separated", "by", "a", "~", "character", "and", "the", "the", "leading", "integer", "must", "not", ...
train
https://github.com/sebastiangraf/jSCSI/blob/6169bfe73f0b15de7d6485453555389e782ae888/bundles/target/src/main/java/org/jscsi/target/settings/NumericalValueRange.java#L48-L64
liferay/com-liferay-commerce
commerce-price-list-service/src/main/java/com/liferay/commerce/price/list/service/persistence/impl/CommercePriceListAccountRelPersistenceImpl.java
CommercePriceListAccountRelPersistenceImpl.findByUUID_G
@Override public CommercePriceListAccountRel findByUUID_G(String uuid, long groupId) throws NoSuchPriceListAccountRelException { CommercePriceListAccountRel commercePriceListAccountRel = fetchByUUID_G(uuid, groupId); if (commercePriceListAccountRel == null) { StringBundler msg = new StringBundler(6); msg.append(_NO_SUCH_ENTITY_WITH_KEY); msg.append("uuid="); msg.append(uuid); msg.append(", groupId="); msg.append(groupId); msg.append("}"); if (_log.isDebugEnabled()) { _log.debug(msg.toString()); } throw new NoSuchPriceListAccountRelException(msg.toString()); } return commercePriceListAccountRel; }
java
@Override public CommercePriceListAccountRel findByUUID_G(String uuid, long groupId) throws NoSuchPriceListAccountRelException { CommercePriceListAccountRel commercePriceListAccountRel = fetchByUUID_G(uuid, groupId); if (commercePriceListAccountRel == null) { StringBundler msg = new StringBundler(6); msg.append(_NO_SUCH_ENTITY_WITH_KEY); msg.append("uuid="); msg.append(uuid); msg.append(", groupId="); msg.append(groupId); msg.append("}"); if (_log.isDebugEnabled()) { _log.debug(msg.toString()); } throw new NoSuchPriceListAccountRelException(msg.toString()); } return commercePriceListAccountRel; }
[ "@", "Override", "public", "CommercePriceListAccountRel", "findByUUID_G", "(", "String", "uuid", ",", "long", "groupId", ")", "throws", "NoSuchPriceListAccountRelException", "{", "CommercePriceListAccountRel", "commercePriceListAccountRel", "=", "fetchByUUID_G", "(", "uuid", ...
Returns the commerce price list account rel where uuid = &#63; and groupId = &#63; or throws a {@link NoSuchPriceListAccountRelException} if it could not be found. @param uuid the uuid @param groupId the group ID @return the matching commerce price list account rel @throws NoSuchPriceListAccountRelException if a matching commerce price list account rel could not be found
[ "Returns", "the", "commerce", "price", "list", "account", "rel", "where", "uuid", "=", "&#63", ";", "and", "groupId", "=", "&#63", ";", "or", "throws", "a", "{", "@link", "NoSuchPriceListAccountRelException", "}", "if", "it", "could", "not", "be", "found", ...
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-price-list-service/src/main/java/com/liferay/commerce/price/list/service/persistence/impl/CommercePriceListAccountRelPersistenceImpl.java#L677-L704
52inc/android-52Kit
library-winds/src/main/java/com/ftinc/kit/winds/Winds.java
Winds.checkChangelogDialog
public static void checkChangelogDialog(Activity ctx, @XmlRes int configId){ // Parse configuration ChangeLog changeLog = Parser.parse(ctx, configId); if(changeLog != null){ // Validate that there is a new version code if(validateVersion(ctx, changeLog)) { openChangelogDialog(ctx, configId); } }else{ throw new NullPointerException("Unable to find a 'Winds' configuration @ " + configId); } }
java
public static void checkChangelogDialog(Activity ctx, @XmlRes int configId){ // Parse configuration ChangeLog changeLog = Parser.parse(ctx, configId); if(changeLog != null){ // Validate that there is a new version code if(validateVersion(ctx, changeLog)) { openChangelogDialog(ctx, configId); } }else{ throw new NullPointerException("Unable to find a 'Winds' configuration @ " + configId); } }
[ "public", "static", "void", "checkChangelogDialog", "(", "Activity", "ctx", ",", "@", "XmlRes", "int", "configId", ")", "{", "// Parse configuration", "ChangeLog", "changeLog", "=", "Parser", ".", "parse", "(", "ctx", ",", "configId", ")", ";", "if", "(", "c...
Check to see if we should show the changelog activity if there are any new changes to the configuration file. @param ctx the context to launch the activity with @param configId the changelog configuration xml resource id
[ "Check", "to", "see", "if", "we", "should", "show", "the", "changelog", "activity", "if", "there", "are", "any", "new", "changes", "to", "the", "configuration", "file", "." ]
train
https://github.com/52inc/android-52Kit/blob/8644fab0f633477b1bb1dddd8147a9ef8bc03516/library-winds/src/main/java/com/ftinc/kit/winds/Winds.java#L153-L168
pravega/pravega
segmentstore/server/src/main/java/io/pravega/segmentstore/server/containers/StreamSegmentContainer.java
StreamSegmentContainer.processAttributeUpdaterOperation
private <T extends Operation & AttributeUpdaterOperation> CompletableFuture<Void> processAttributeUpdaterOperation(T operation, TimeoutTimer timer) { Collection<AttributeUpdate> updates = operation.getAttributeUpdates(); if (updates == null || updates.isEmpty()) { // No need for extra complicated handling. return this.durableLog.add(operation, timer.getRemaining()); } return Futures.exceptionallyCompose( this.durableLog.add(operation, timer.getRemaining()), ex -> { // We only retry BadAttributeUpdateExceptions if it has the PreviousValueMissing flag set. ex = Exceptions.unwrap(ex); if (ex instanceof BadAttributeUpdateException && ((BadAttributeUpdateException) ex).isPreviousValueMissing()) { // Get the missing attributes and load them into the cache, then retry the operation, exactly once. SegmentMetadata segmentMetadata = this.metadata.getStreamSegmentMetadata(operation.getStreamSegmentId()); Collection<UUID> attributeIds = updates.stream() .map(AttributeUpdate::getAttributeId) .filter(id -> !Attributes.isCoreAttribute(id)) .collect(Collectors.toList()); if (!attributeIds.isEmpty()) { // This only makes sense if a core attribute was missing. return getAndCacheAttributes(segmentMetadata, attributeIds, true, timer) .thenComposeAsync(attributes -> { // Final attempt - now that we should have the attributes cached. return this.durableLog.add(operation, timer.getRemaining()); }, this.executor); } } // Anything else is non-retryable; rethrow. return Futures.failedFuture(ex); }); }
java
private <T extends Operation & AttributeUpdaterOperation> CompletableFuture<Void> processAttributeUpdaterOperation(T operation, TimeoutTimer timer) { Collection<AttributeUpdate> updates = operation.getAttributeUpdates(); if (updates == null || updates.isEmpty()) { // No need for extra complicated handling. return this.durableLog.add(operation, timer.getRemaining()); } return Futures.exceptionallyCompose( this.durableLog.add(operation, timer.getRemaining()), ex -> { // We only retry BadAttributeUpdateExceptions if it has the PreviousValueMissing flag set. ex = Exceptions.unwrap(ex); if (ex instanceof BadAttributeUpdateException && ((BadAttributeUpdateException) ex).isPreviousValueMissing()) { // Get the missing attributes and load them into the cache, then retry the operation, exactly once. SegmentMetadata segmentMetadata = this.metadata.getStreamSegmentMetadata(operation.getStreamSegmentId()); Collection<UUID> attributeIds = updates.stream() .map(AttributeUpdate::getAttributeId) .filter(id -> !Attributes.isCoreAttribute(id)) .collect(Collectors.toList()); if (!attributeIds.isEmpty()) { // This only makes sense if a core attribute was missing. return getAndCacheAttributes(segmentMetadata, attributeIds, true, timer) .thenComposeAsync(attributes -> { // Final attempt - now that we should have the attributes cached. return this.durableLog.add(operation, timer.getRemaining()); }, this.executor); } } // Anything else is non-retryable; rethrow. return Futures.failedFuture(ex); }); }
[ "private", "<", "T", "extends", "Operation", "&", "AttributeUpdaterOperation", ">", "CompletableFuture", "<", "Void", ">", "processAttributeUpdaterOperation", "(", "T", "operation", ",", "TimeoutTimer", "timer", ")", "{", "Collection", "<", "AttributeUpdate", ">", "...
Processes the given AttributeUpdateOperation with exactly one retry in case it was rejected because of an attribute update failure due to the attribute value missing from the in-memory cache. @param operation The Operation to process. @param timer Timer for the operation. @param <T> Type of the operation. @return A CompletableFuture that, when completed normally, will indicate that the Operation has been successfully processed. If it failed, it will be completed with an appropriate exception.
[ "Processes", "the", "given", "AttributeUpdateOperation", "with", "exactly", "one", "retry", "in", "case", "it", "was", "rejected", "because", "of", "an", "attribute", "update", "failure", "due", "to", "the", "attribute", "value", "missing", "from", "the", "in", ...
train
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/segmentstore/server/src/main/java/io/pravega/segmentstore/server/containers/StreamSegmentContainer.java#L634-L666
lightblue-platform/lightblue-client
core/src/main/java/com/redhat/lightblue/client/Query.java
Query.withValue
public static Query withValue(String expression) { String[] parts = split(expression); if (parts != null) { String field = parts[0]; String operator = parts[1]; String value = parts[2]; BinOp binOp = BinOp.getOp(operator); if (binOp != null) { return withValue(field, binOp, value); } NaryOp naryOp = NaryOp.getOp(operator); if (naryOp != null) { Literal[] values = Literal.values(value.substring(1, value.length() - 1).split("\\s*,\\s*")); return withValues(field, naryOp, values); } } throw new IllegalArgumentException("'" + expression + "' is incorrect"); }
java
public static Query withValue(String expression) { String[] parts = split(expression); if (parts != null) { String field = parts[0]; String operator = parts[1]; String value = parts[2]; BinOp binOp = BinOp.getOp(operator); if (binOp != null) { return withValue(field, binOp, value); } NaryOp naryOp = NaryOp.getOp(operator); if (naryOp != null) { Literal[] values = Literal.values(value.substring(1, value.length() - 1).split("\\s*,\\s*")); return withValues(field, naryOp, values); } } throw new IllegalArgumentException("'" + expression + "' is incorrect"); }
[ "public", "static", "Query", "withValue", "(", "String", "expression", ")", "{", "String", "[", "]", "parts", "=", "split", "(", "expression", ")", ";", "if", "(", "parts", "!=", "null", ")", "{", "String", "field", "=", "parts", "[", "0", "]", ";", ...
<pre> { field:<field>, op:<op>, rvalue:<value> } { field:<field>, op:<op>, values:[values] } </pre>
[ "<pre", ">", "{", "field", ":", "<field", ">", "op", ":", "<op", ">", "rvalue", ":", "<value", ">", "}", "{", "field", ":", "<field", ">", "op", ":", "<op", ">", "values", ":", "[", "values", "]", "}", "<", "/", "pre", ">" ]
train
https://github.com/lightblue-platform/lightblue-client/blob/03790aff34e90d3889f60fd6c603c21a21dc1a40/core/src/main/java/com/redhat/lightblue/client/Query.java#L315-L333
rsocket/rsocket-java
rsocket-core/src/main/java/io/rsocket/util/NumberUtils.java
NumberUtils.requirePositive
public static long requirePositive(long l, String message) { Objects.requireNonNull(message, "message must not be null"); if (l <= 0) { throw new IllegalArgumentException(message); } return l; }
java
public static long requirePositive(long l, String message) { Objects.requireNonNull(message, "message must not be null"); if (l <= 0) { throw new IllegalArgumentException(message); } return l; }
[ "public", "static", "long", "requirePositive", "(", "long", "l", ",", "String", "message", ")", "{", "Objects", ".", "requireNonNull", "(", "message", ",", "\"message must not be null\"", ")", ";", "if", "(", "l", "<=", "0", ")", "{", "throw", "new", "Ille...
Requires that a {@code long} is greater than zero. @param l the {@code long} to test @param message detail message to be used in the event that a {@link IllegalArgumentException} is thrown @return the {@code long} if greater than zero @throws IllegalArgumentException if {@code l} is less than or equal to zero
[ "Requires", "that", "a", "{", "@code", "long", "}", "is", "greater", "than", "zero", "." ]
train
https://github.com/rsocket/rsocket-java/blob/5101748fbd224ec86570351cebd24d079b63fbfc/rsocket-core/src/main/java/io/rsocket/util/NumberUtils.java#L68-L76
wcm-io/wcm-io-wcm
commons/src/main/java/io/wcm/wcm/commons/util/RunMode.java
RunMode.disableIfNoRunModeActive
@Deprecated public static boolean disableIfNoRunModeActive(Set<String> runModes, String[] allowedRunModes, ComponentContext componentContext, Logger log) { final String name = (String)componentContext.getProperties().get(ComponentConstants.COMPONENT_NAME); boolean result = false; boolean isActive = false; for (String runMode : allowedRunModes) { if (runModes.contains(runMode)) { isActive = true; break; } } if (!isActive) { if (log.isDebugEnabled()) { log.debug("Component '" + name + "' " + "disabled as none of its run modes (" + StringUtils.join(allowedRunModes, ",") + ") " + "are currently active (" + StringUtils.join(runModes, ",") + ")." ); } componentContext.disableComponent(name); result = true; } else if (log.isDebugEnabled()) { log.debug("Component '" + name + "' " + "enabled as at least one of its run modes (" + StringUtils.join(allowedRunModes, ",") + ") " + "are currently active (" + StringUtils.join(runModes, ",") + ")." ); } return result; }
java
@Deprecated public static boolean disableIfNoRunModeActive(Set<String> runModes, String[] allowedRunModes, ComponentContext componentContext, Logger log) { final String name = (String)componentContext.getProperties().get(ComponentConstants.COMPONENT_NAME); boolean result = false; boolean isActive = false; for (String runMode : allowedRunModes) { if (runModes.contains(runMode)) { isActive = true; break; } } if (!isActive) { if (log.isDebugEnabled()) { log.debug("Component '" + name + "' " + "disabled as none of its run modes (" + StringUtils.join(allowedRunModes, ",") + ") " + "are currently active (" + StringUtils.join(runModes, ",") + ")." ); } componentContext.disableComponent(name); result = true; } else if (log.isDebugEnabled()) { log.debug("Component '" + name + "' " + "enabled as at least one of its run modes (" + StringUtils.join(allowedRunModes, ",") + ") " + "are currently active (" + StringUtils.join(runModes, ",") + ")." ); } return result; }
[ "@", "Deprecated", "public", "static", "boolean", "disableIfNoRunModeActive", "(", "Set", "<", "String", ">", "runModes", ",", "String", "[", "]", "allowedRunModes", ",", "ComponentContext", "componentContext", ",", "Logger", "log", ")", "{", "final", "String", ...
Use this to disable a component if none of its run modes are active. Component activation status is logged with DEBUG level. This method is a replacement for the <code>com.day.cq.commons.RunModeUtil#disableIfNoRunModeActive(RunMode, String[], ComponentContext, Logger)</code> method which is deprecated. @param runModes Run modes @param allowedRunModes Allowed run modes @param componentContext OSGI component context @param log Logger @return true if component was disabled @deprecated Instead of directly using the run modes, it is better to make the component in question require a configuration (see OSGI Declarative Services Spec: configuration policy). In this case, a component gets only active if a configuration is available. Such a configuration can be put into the repository for the specific run mode.
[ "Use", "this", "to", "disable", "a", "component", "if", "none", "of", "its", "run", "modes", "are", "active", ".", "Component", "activation", "status", "is", "logged", "with", "DEBUG", "level", ".", "This", "method", "is", "a", "replacement", "for", "the",...
train
https://github.com/wcm-io/wcm-io-wcm/blob/8eff9434f2f4b6462fdb718f8769ad793c55b8d7/commons/src/main/java/io/wcm/wcm/commons/util/RunMode.java#L116-L148
vkostyukov/la4j
src/main/java/org/la4j/Matrices.java
Matrices.asSumFunctionAccumulator
public static MatrixAccumulator asSumFunctionAccumulator(final double neutral, final MatrixFunction function) { return new MatrixAccumulator() { private final MatrixAccumulator sumAccumulator = Matrices.asSumAccumulator(neutral); @Override public void update(int i, int j, double value) { sumAccumulator.update(i, j, function.evaluate(i, j, value)); } @Override public double accumulate() { return sumAccumulator.accumulate(); } }; }
java
public static MatrixAccumulator asSumFunctionAccumulator(final double neutral, final MatrixFunction function) { return new MatrixAccumulator() { private final MatrixAccumulator sumAccumulator = Matrices.asSumAccumulator(neutral); @Override public void update(int i, int j, double value) { sumAccumulator.update(i, j, function.evaluate(i, j, value)); } @Override public double accumulate() { return sumAccumulator.accumulate(); } }; }
[ "public", "static", "MatrixAccumulator", "asSumFunctionAccumulator", "(", "final", "double", "neutral", ",", "final", "MatrixFunction", "function", ")", "{", "return", "new", "MatrixAccumulator", "(", ")", "{", "private", "final", "MatrixAccumulator", "sumAccumulator", ...
Creates a sum function accumulator, that calculates the sum of all elements in the matrix after applying given {@code function} to each of them. @param neutral the neutral value @param function the matrix function @return a sum function accumulator
[ "Creates", "a", "sum", "function", "accumulator", "that", "calculates", "the", "sum", "of", "all", "elements", "in", "the", "matrix", "after", "applying", "given", "{", "@code", "function", "}", "to", "each", "of", "them", "." ]
train
https://github.com/vkostyukov/la4j/blob/dd1b917caf9606399a49afa6b0d738934cd3a7b3/src/main/java/org/la4j/Matrices.java#L692-L706
adessoAG/wicked-charts
wicket/wicked-charts-wicket7/src/main/java/de/adesso/wickedcharts/wicket7/chartjs/features/basic/ChartBehavior.java
ChartBehavior.includeChartJavascript
protected void includeChartJavascript(final IHeaderResponse response, final ChartConfiguration options, final JsonRenderer renderer, final String markupId) { String chartVarname = this.chart.getJavaScriptVarName(); String optionsVarname = markupId + "Options"; String contextVarname = markupId + "ctx"; String jsonOptions = renderer.toJson(options); if(options.getOptionalJavascript() == null) { response.render(OnDomReadyHeaderItem.forScript(MessageFormat.format( "var {0} = {1};" + "var {3} = document.getElementById(\"{4}\").getContext(\"2d\");" + " window.{2} = new Chart({3},{0});", optionsVarname, jsonOptions,chartVarname,contextVarname,markupId))); } else { String optionalJavascript = options.getOptionalJavascript(); String replacedVariablesInOptionalJavascript = optionalJavascript.replace("{0}", contextVarname); response.render(OnDomReadyHeaderItem.forScript(MessageFormat.format( "{5} var {0} = {1};" + "var {3} = document.getElementById(\"{4}\").getContext(\"2d\");" + " window.{2} = new Chart({3},{0});", optionsVarname, jsonOptions,chartVarname,contextVarname,markupId,replacedVariablesInOptionalJavascript))); } }
java
protected void includeChartJavascript(final IHeaderResponse response, final ChartConfiguration options, final JsonRenderer renderer, final String markupId) { String chartVarname = this.chart.getJavaScriptVarName(); String optionsVarname = markupId + "Options"; String contextVarname = markupId + "ctx"; String jsonOptions = renderer.toJson(options); if(options.getOptionalJavascript() == null) { response.render(OnDomReadyHeaderItem.forScript(MessageFormat.format( "var {0} = {1};" + "var {3} = document.getElementById(\"{4}\").getContext(\"2d\");" + " window.{2} = new Chart({3},{0});", optionsVarname, jsonOptions,chartVarname,contextVarname,markupId))); } else { String optionalJavascript = options.getOptionalJavascript(); String replacedVariablesInOptionalJavascript = optionalJavascript.replace("{0}", contextVarname); response.render(OnDomReadyHeaderItem.forScript(MessageFormat.format( "{5} var {0} = {1};" + "var {3} = document.getElementById(\"{4}\").getContext(\"2d\");" + " window.{2} = new Chart({3},{0});", optionsVarname, jsonOptions,chartVarname,contextVarname,markupId,replacedVariablesInOptionalJavascript))); } }
[ "protected", "void", "includeChartJavascript", "(", "final", "IHeaderResponse", "response", ",", "final", "ChartConfiguration", "options", ",", "final", "JsonRenderer", "renderer", ",", "final", "String", "markupId", ")", "{", "String", "chartVarname", "=", "this", ...
Includes the javascript that calls the Highcharts library to visualize the chart. @param response the Wicket HeaderResponse @param options the options containing the data to display @param renderer the JsonRenderer responsible for rendering the options @param markupId the DOM ID of the chart component.
[ "Includes", "the", "javascript", "that", "calls", "the", "Highcharts", "library", "to", "visualize", "the", "chart", "." ]
train
https://github.com/adessoAG/wicked-charts/blob/498aceff025f612e22ba5135b26531afeabac03c/wicket/wicked-charts-wicket7/src/main/java/de/adesso/wickedcharts/wicket7/chartjs/features/basic/ChartBehavior.java#L62-L85
OpenLiberty/open-liberty
dev/com.ibm.ws.logging.hpel/src/com/ibm/websphere/logging/hpel/reader/HpelCBEFormatter.java
HpelCBEFormatter.createExtendedElement
private void createExtendedElement(StringBuilder sb, RepositoryLogRecord record){ sb.append(lineSeparator).append(INDENT[0]).append("<extendedDataElements name=\"CommonBaseEventLogRecord:level\" type=\"noValue\">"); sb.append(lineSeparator).append(INDENT[1]).append("<children name=\"CommonBaseEventLogRecord:name\" type=\"string\">"); sb.append(lineSeparator).append(INDENT[2]).append("<values>").append(record.getLevel().getName()).append("</values>"); sb.append(lineSeparator).append(INDENT[1]).append("</children>"); sb.append(lineSeparator).append(INDENT[1]).append("<children name=\"CommonBaseEventLogRecord:value\" type=\"int\">"); sb.append(lineSeparator).append(INDENT[2]).append("<values>").append(record.getLevel().intValue()).append("</values>"); sb.append(lineSeparator).append(INDENT[1]).append("</children>"); sb.append(lineSeparator).append(INDENT[0]).append("</extendedDataElements>"); }
java
private void createExtendedElement(StringBuilder sb, RepositoryLogRecord record){ sb.append(lineSeparator).append(INDENT[0]).append("<extendedDataElements name=\"CommonBaseEventLogRecord:level\" type=\"noValue\">"); sb.append(lineSeparator).append(INDENT[1]).append("<children name=\"CommonBaseEventLogRecord:name\" type=\"string\">"); sb.append(lineSeparator).append(INDENT[2]).append("<values>").append(record.getLevel().getName()).append("</values>"); sb.append(lineSeparator).append(INDENT[1]).append("</children>"); sb.append(lineSeparator).append(INDENT[1]).append("<children name=\"CommonBaseEventLogRecord:value\" type=\"int\">"); sb.append(lineSeparator).append(INDENT[2]).append("<values>").append(record.getLevel().intValue()).append("</values>"); sb.append(lineSeparator).append(INDENT[1]).append("</children>"); sb.append(lineSeparator).append(INDENT[0]).append("</extendedDataElements>"); }
[ "private", "void", "createExtendedElement", "(", "StringBuilder", "sb", ",", "RepositoryLogRecord", "record", ")", "{", "sb", ".", "append", "(", "lineSeparator", ")", ".", "append", "(", "INDENT", "[", "0", "]", ")", ".", "append", "(", "\"<extendedDataElemen...
Appends the CBE Extended Data Element of a record to a String buffer @param sb the string buffer the element will be added to @param record the record that represents the common base event
[ "Appends", "the", "CBE", "Extended", "Data", "Element", "of", "a", "record", "to", "a", "String", "buffer" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.logging.hpel/src/com/ibm/websphere/logging/hpel/reader/HpelCBEFormatter.java#L246-L255
wisdom-framework/wisdom-jcr
wisdom-jcr-core/src/main/java/org/wisdom/jcrom/runtime/JcrTools.java
JcrTools.registerMixinType
public static void registerMixinType(Session session, String mixin) throws RepositoryException { NodeTypeManager nodeTypeManager = session.getWorkspace().getNodeTypeManager(); if (!nodeTypeManager.hasNodeType(mixin)) { NodeTypeTemplate nodeTypeTemplate = nodeTypeManager.createNodeTypeTemplate(); nodeTypeTemplate.setMixin(true); nodeTypeTemplate.setName(mixin); NodeTypeDefinition[] nodeTypes = new NodeTypeDefinition[]{nodeTypeTemplate}; nodeTypeManager.registerNodeTypes(nodeTypes, true); } }
java
public static void registerMixinType(Session session, String mixin) throws RepositoryException { NodeTypeManager nodeTypeManager = session.getWorkspace().getNodeTypeManager(); if (!nodeTypeManager.hasNodeType(mixin)) { NodeTypeTemplate nodeTypeTemplate = nodeTypeManager.createNodeTypeTemplate(); nodeTypeTemplate.setMixin(true); nodeTypeTemplate.setName(mixin); NodeTypeDefinition[] nodeTypes = new NodeTypeDefinition[]{nodeTypeTemplate}; nodeTypeManager.registerNodeTypes(nodeTypes, true); } }
[ "public", "static", "void", "registerMixinType", "(", "Session", "session", ",", "String", "mixin", ")", "throws", "RepositoryException", "{", "NodeTypeManager", "nodeTypeManager", "=", "session", ".", "getWorkspace", "(", ")", ".", "getNodeTypeManager", "(", ")", ...
Register new mixin type if does not exists on workspace @param session the JCR session @param mixin the mixin name to register @throws RepositoryException
[ "Register", "new", "mixin", "type", "if", "does", "not", "exists", "on", "workspace" ]
train
https://github.com/wisdom-framework/wisdom-jcr/blob/2711383dde2239a19b90c226b3fd2aecab5715e4/wisdom-jcr-core/src/main/java/org/wisdom/jcrom/runtime/JcrTools.java#L988-L998
tracee/tracee
core/src/main/java/io/tracee/transport/SoapHeaderTransport.java
SoapHeaderTransport.renderSoapHeader
private <T> void renderSoapHeader(final Marshallable<T> marshallable, final Map<String, String> context, T xmlContext) { try { final Marshaller marshaller = jaxbContext.createMarshaller(); marshallable.marshal(marshaller, TpicMap.wrap(context), xmlContext); } catch (JAXBException e) { logger.warn("Unable to render TPIC header: {}", e.getMessage()); logger.debug("WithStack: Unable to render TPIC header: {}", e.getMessage(), e); } }
java
private <T> void renderSoapHeader(final Marshallable<T> marshallable, final Map<String, String> context, T xmlContext) { try { final Marshaller marshaller = jaxbContext.createMarshaller(); marshallable.marshal(marshaller, TpicMap.wrap(context), xmlContext); } catch (JAXBException e) { logger.warn("Unable to render TPIC header: {}", e.getMessage()); logger.debug("WithStack: Unable to render TPIC header: {}", e.getMessage(), e); } }
[ "private", "<", "T", ">", "void", "renderSoapHeader", "(", "final", "Marshallable", "<", "T", ">", "marshallable", ",", "final", "Map", "<", "String", ",", "String", ">", "context", ",", "T", "xmlContext", ")", "{", "try", "{", "final", "Marshaller", "ma...
Renders a given context map into a given result that should be the TPIC header node.
[ "Renders", "a", "given", "context", "map", "into", "a", "given", "result", "that", "should", "be", "the", "TPIC", "header", "node", "." ]
train
https://github.com/tracee/tracee/blob/15a68e435248f57757beb8ceac6db5b7f6035bb3/core/src/main/java/io/tracee/transport/SoapHeaderTransport.java#L119-L127
apache/incubator-druid
core/src/main/java/org/apache/druid/java/util/common/lifecycle/Lifecycle.java
Lifecycle.addStartCloseInstance
public <T> T addStartCloseInstance(T o, Stage stage) { addHandler(new StartCloseHandler(o), stage); return o; }
java
public <T> T addStartCloseInstance(T o, Stage stage) { addHandler(new StartCloseHandler(o), stage); return o; }
[ "public", "<", "T", ">", "T", "addStartCloseInstance", "(", "T", "o", ",", "Stage", "stage", ")", "{", "addHandler", "(", "new", "StartCloseHandler", "(", "o", ")", ",", "stage", ")", ";", "return", "o", ";", "}" ]
Adds an instance with a start() and/or close() method to the Lifecycle. If the lifecycle has already been started, it throws an {@link ISE} @param o The object to add to the lifecycle @param stage The stage to add the lifecycle at @throws ISE {@link Lifecycle#addHandler(Handler, Stage)}
[ "Adds", "an", "instance", "with", "a", "start", "()", "and", "/", "or", "close", "()", "method", "to", "the", "Lifecycle", ".", "If", "the", "lifecycle", "has", "already", "been", "started", "it", "throws", "an", "{", "@link", "ISE", "}" ]
train
https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/core/src/main/java/org/apache/druid/java/util/common/lifecycle/Lifecycle.java#L168-L172
jbundle/webapp
upload/src/main/java/org/jbundle/util/webapp/upload/UploadServlet.java
UploadServlet.doGet
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { this.doProcess(req, res); }
java
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { this.doProcess(req, res); }
[ "public", "void", "doGet", "(", "HttpServletRequest", "req", ",", "HttpServletResponse", "res", ")", "throws", "ServletException", ",", "IOException", "{", "this", ".", "doProcess", "(", "req", ",", "res", ")", ";", "}" ]
Process an HTML get. @exception ServletException From inherited class. @exception IOException From inherited class.
[ "Process", "an", "HTML", "get", "." ]
train
https://github.com/jbundle/webapp/blob/af2cf32bd92254073052f1f9b4bcd47c2f76ba7d/upload/src/main/java/org/jbundle/util/webapp/upload/UploadServlet.java#L85-L89
TNG/JGiven
jgiven-core/src/main/java/com/tngtech/jgiven/attachment/Attachment.java
Attachment.fromBinaryFile
public static Attachment fromBinaryFile( File file, MediaType mediaType ) throws IOException { FileInputStream stream = new FileInputStream( file ); try { return fromBinaryInputStream( stream, mediaType ); } finally { ResourceUtil.close( stream ); } }
java
public static Attachment fromBinaryFile( File file, MediaType mediaType ) throws IOException { FileInputStream stream = new FileInputStream( file ); try { return fromBinaryInputStream( stream, mediaType ); } finally { ResourceUtil.close( stream ); } }
[ "public", "static", "Attachment", "fromBinaryFile", "(", "File", "file", ",", "MediaType", "mediaType", ")", "throws", "IOException", "{", "FileInputStream", "stream", "=", "new", "FileInputStream", "(", "file", ")", ";", "try", "{", "return", "fromBinaryInputStre...
Creates an attachment from the given binary file {@code file}. The content of the file will be transformed into a Base64 encoded string. @throws IOException if an I/O error occurs @throws java.lang.IllegalArgumentException if mediaType is not binary
[ "Creates", "an", "attachment", "from", "the", "given", "binary", "file", "{" ]
train
https://github.com/TNG/JGiven/blob/1a69248fc6d7eb380cdc4542e3be273842889748/jgiven-core/src/main/java/com/tngtech/jgiven/attachment/Attachment.java#L186-L193
fhoeben/hsac-fitnesse-fixtures
src/main/java/nl/hsac/fitnesse/fixture/util/selenium/CookieConverter.java
CookieConverter.copySeleniumCookies
public void copySeleniumCookies(Set<Cookie> browserCookies, CookieStore cookieStore) { for (Cookie browserCookie : browserCookies) { ClientCookie cookie = convertCookie(browserCookie); cookieStore.addCookie(cookie); } }
java
public void copySeleniumCookies(Set<Cookie> browserCookies, CookieStore cookieStore) { for (Cookie browserCookie : browserCookies) { ClientCookie cookie = convertCookie(browserCookie); cookieStore.addCookie(cookie); } }
[ "public", "void", "copySeleniumCookies", "(", "Set", "<", "Cookie", ">", "browserCookies", ",", "CookieStore", "cookieStore", ")", "{", "for", "(", "Cookie", "browserCookie", ":", "browserCookies", ")", "{", "ClientCookie", "cookie", "=", "convertCookie", "(", "...
Converts Selenium cookies to Apache http client ones. @param browserCookies cookies in Selenium format. @param cookieStore store to place coverted cookies in.
[ "Converts", "Selenium", "cookies", "to", "Apache", "http", "client", "ones", "." ]
train
https://github.com/fhoeben/hsac-fitnesse-fixtures/blob/4e9018d7386a9aa65bfcbf07eb28ae064edd1732/src/main/java/nl/hsac/fitnesse/fixture/util/selenium/CookieConverter.java#L19-L24
alkacon/opencms-core
src/org/opencms/db/generic/CmsUserDriver.java
CmsUserDriver.internalCreateOrgUnitFromResource
protected CmsOrganizationalUnit internalCreateOrgUnitFromResource(CmsDbContext dbc, CmsResource resource) throws CmsException { if (!resource.getRootPath().startsWith(ORGUNIT_BASE_FOLDER)) { throw new CmsDataAccessException( Messages.get().container(Messages.ERR_READ_ORGUNIT_1, resource.getRootPath())); } // get the data String name = resource.getRootPath().substring(ORGUNIT_BASE_FOLDER.length()); if ((name.length() > 0) && !name.endsWith(CmsOrganizationalUnit.SEPARATOR)) { name += CmsOrganizationalUnit.SEPARATOR; } String description = m_driverManager.readPropertyObject( dbc, resource, ORGUNIT_PROPERTY_DESCRIPTION, false).getStructureValue(); int flags = (resource.getFlags() & ~CmsResource.FLAG_INTERNAL); // remove the internal flag String projectId = m_driverManager.readPropertyObject( dbc, resource, ORGUNIT_PROPERTY_PROJECTID, false).getStructureValue(); // create the object return new CmsOrganizationalUnit( resource.getStructureId(), name, description, flags, (projectId == null ? null : new CmsUUID(projectId))); }
java
protected CmsOrganizationalUnit internalCreateOrgUnitFromResource(CmsDbContext dbc, CmsResource resource) throws CmsException { if (!resource.getRootPath().startsWith(ORGUNIT_BASE_FOLDER)) { throw new CmsDataAccessException( Messages.get().container(Messages.ERR_READ_ORGUNIT_1, resource.getRootPath())); } // get the data String name = resource.getRootPath().substring(ORGUNIT_BASE_FOLDER.length()); if ((name.length() > 0) && !name.endsWith(CmsOrganizationalUnit.SEPARATOR)) { name += CmsOrganizationalUnit.SEPARATOR; } String description = m_driverManager.readPropertyObject( dbc, resource, ORGUNIT_PROPERTY_DESCRIPTION, false).getStructureValue(); int flags = (resource.getFlags() & ~CmsResource.FLAG_INTERNAL); // remove the internal flag String projectId = m_driverManager.readPropertyObject( dbc, resource, ORGUNIT_PROPERTY_PROJECTID, false).getStructureValue(); // create the object return new CmsOrganizationalUnit( resource.getStructureId(), name, description, flags, (projectId == null ? null : new CmsUUID(projectId))); }
[ "protected", "CmsOrganizationalUnit", "internalCreateOrgUnitFromResource", "(", "CmsDbContext", "dbc", ",", "CmsResource", "resource", ")", "throws", "CmsException", "{", "if", "(", "!", "resource", ".", "getRootPath", "(", ")", ".", "startsWith", "(", "ORGUNIT_BASE_F...
Returns the organizational unit represented by the given resource.<p> @param dbc the current db context @param resource the resource that represents an organizational unit @return the organizational unit represented by the given resource @throws CmsException if something goes wrong
[ "Returns", "the", "organizational", "unit", "represented", "by", "the", "given", "resource", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/generic/CmsUserDriver.java#L2406-L2436
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/file/meta/InodeTreePersistentState.java
InodeTreePersistentState.applyAndJournal
public void applyAndJournal(Supplier<JournalContext> context, DeleteFileEntry entry) { // Unlike most entries, the delete file entry must be applied *before* making the in-memory // change. This is because delete file and create file are performed with only a read lock on // the parent directory. As soon as we do the in-memory-delete, another thread could re-create a // directory with the same name, and append a journal entry for the inode creation. This would // ruin journal replay because we would see two create file entries in a row for the same file // name. The opposite order is safe. We will never append the delete entry for a file before its // creation entry because delete requires a write lock on the deleted file, but the create // operation holds that lock until after it has appended to the journal. try { context.get().append(JournalEntry.newBuilder().setDeleteFile(entry).build()); applyDelete(entry); } catch (Throwable t) { // Delete entries should always apply cleanly, but if it somehow fails, we are in a state // where we've journaled the delete, but failed to make the in-memory update. We don't yet // have a way to recover from this, so we give a fatal error. ProcessUtils.fatalError(LOG, t, "Failed to apply entry %s", entry); } }
java
public void applyAndJournal(Supplier<JournalContext> context, DeleteFileEntry entry) { // Unlike most entries, the delete file entry must be applied *before* making the in-memory // change. This is because delete file and create file are performed with only a read lock on // the parent directory. As soon as we do the in-memory-delete, another thread could re-create a // directory with the same name, and append a journal entry for the inode creation. This would // ruin journal replay because we would see two create file entries in a row for the same file // name. The opposite order is safe. We will never append the delete entry for a file before its // creation entry because delete requires a write lock on the deleted file, but the create // operation holds that lock until after it has appended to the journal. try { context.get().append(JournalEntry.newBuilder().setDeleteFile(entry).build()); applyDelete(entry); } catch (Throwable t) { // Delete entries should always apply cleanly, but if it somehow fails, we are in a state // where we've journaled the delete, but failed to make the in-memory update. We don't yet // have a way to recover from this, so we give a fatal error. ProcessUtils.fatalError(LOG, t, "Failed to apply entry %s", entry); } }
[ "public", "void", "applyAndJournal", "(", "Supplier", "<", "JournalContext", ">", "context", ",", "DeleteFileEntry", "entry", ")", "{", "// Unlike most entries, the delete file entry must be applied *before* making the in-memory", "// change. This is because delete file and create file...
Deletes an inode (may be either a file or directory). @param context journal context supplier @param entry delete file entry
[ "Deletes", "an", "inode", "(", "may", "be", "either", "a", "file", "or", "directory", ")", "." ]
train
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/file/meta/InodeTreePersistentState.java#L158-L176
advantageous/boon
reflekt/src/main/java/io/advantageous/boon/core/Str.java
Str.idx
public static String idx( String str, int index, char c ) { char[] chars = str.toCharArray(); Chr.idx( chars, index, c ); return new String( chars ); }
java
public static String idx( String str, int index, char c ) { char[] chars = str.toCharArray(); Chr.idx( chars, index, c ); return new String( chars ); }
[ "public", "static", "String", "idx", "(", "String", "str", ",", "int", "index", ",", "char", "c", ")", "{", "char", "[", "]", "chars", "=", "str", ".", "toCharArray", "(", ")", ";", "Chr", ".", "idx", "(", "chars", ",", "index", ",", "c", ")", ...
Puts character at index @param str string @param index index @param c char to put in @return new string
[ "Puts", "character", "at", "index" ]
train
https://github.com/advantageous/boon/blob/12712d376761aa3b33223a9f1716720ddb67cb5e/reflekt/src/main/java/io/advantageous/boon/core/Str.java#L201-L206
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/io/grasslegacy/utils/Window.java
Window.adaptActiveRegionToEnvelope
public static Window adaptActiveRegionToEnvelope( Envelope bounds, Window activeRegion ) { Point2D eastNorth = Window.snapToNextHigherInActiveRegionResolution(bounds.getMaxX(), bounds.getMaxY(), activeRegion); Point2D westsouth = Window.snapToNextHigherInActiveRegionResolution(bounds.getMinX() - activeRegion.getWEResolution(), bounds.getMinY() - activeRegion.getNSResolution(), activeRegion); Window tmp = new Window(westsouth.getX(), eastNorth.getX(), westsouth.getY(), eastNorth.getY(), activeRegion.getWEResolution(), activeRegion.getNSResolution()); // activeRegion.setExtent(tmp); return tmp; }
java
public static Window adaptActiveRegionToEnvelope( Envelope bounds, Window activeRegion ) { Point2D eastNorth = Window.snapToNextHigherInActiveRegionResolution(bounds.getMaxX(), bounds.getMaxY(), activeRegion); Point2D westsouth = Window.snapToNextHigherInActiveRegionResolution(bounds.getMinX() - activeRegion.getWEResolution(), bounds.getMinY() - activeRegion.getNSResolution(), activeRegion); Window tmp = new Window(westsouth.getX(), eastNorth.getX(), westsouth.getY(), eastNorth.getY(), activeRegion.getWEResolution(), activeRegion.getNSResolution()); // activeRegion.setExtent(tmp); return tmp; }
[ "public", "static", "Window", "adaptActiveRegionToEnvelope", "(", "Envelope", "bounds", ",", "Window", "activeRegion", ")", "{", "Point2D", "eastNorth", "=", "Window", ".", "snapToNextHigherInActiveRegionResolution", "(", "bounds", ".", "getMaxX", "(", ")", ",", "bo...
Takes an envelope and an active region and creates a new region to match the bounds of the envelope, but the resolutions of the active region. This is important if the region has to match some feature layer. The bounds are assured to contain completely the envelope. @param bounds @param activeRegion
[ "Takes", "an", "envelope", "and", "an", "active", "region", "and", "creates", "a", "new", "region", "to", "match", "the", "bounds", "of", "the", "envelope", "but", "the", "resolutions", "of", "the", "active", "region", ".", "This", "is", "important", "if",...
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/io/grasslegacy/utils/Window.java#L504-L512
wnameless/rubycollect4j
src/main/java/net/sf/rubycollect4j/RubyObject.java
RubyObject.send
@SuppressWarnings("unchecked") public static <E> E send(Object o, String methodName, byte arg) { try { Method method = o.getClass().getMethod(methodName, byte.class); return (E) method.invoke(o, arg); } catch (Exception e) { return send(o, methodName, (Object) arg); } }
java
@SuppressWarnings("unchecked") public static <E> E send(Object o, String methodName, byte arg) { try { Method method = o.getClass().getMethod(methodName, byte.class); return (E) method.invoke(o, arg); } catch (Exception e) { return send(o, methodName, (Object) arg); } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "<", "E", ">", "E", "send", "(", "Object", "o", ",", "String", "methodName", ",", "byte", "arg", ")", "{", "try", "{", "Method", "method", "=", "o", ".", "getClass", "(", ")", "....
Executes a method of any Object by Java reflection. @param o an Object @param methodName name of the method @param arg a byte @return the result of the method called
[ "Executes", "a", "method", "of", "any", "Object", "by", "Java", "reflection", "." ]
train
https://github.com/wnameless/rubycollect4j/blob/b8b8d8eccaca2254a3d09b91745882fb7a0d5add/src/main/java/net/sf/rubycollect4j/RubyObject.java#L126-L134
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/io/stream/StreamHelper.java
StreamHelper.readStreamLines
public static void readStreamLines (@WillClose @Nullable final InputStream aIS, @Nonnull @Nonempty final Charset aCharset, @Nonnegative final int nLinesToSkip, final int nLinesToRead, @Nonnull final Consumer <? super String> aLineCallback) { try { ValueEnforcer.notNull (aCharset, "Charset"); ValueEnforcer.isGE0 (nLinesToSkip, "LinesToSkip"); final boolean bReadAllLines = nLinesToRead == CGlobal.ILLEGAL_UINT; ValueEnforcer.isTrue (bReadAllLines || nLinesToRead >= 0, () -> "Line count may not be that negative: " + nLinesToRead); ValueEnforcer.notNull (aLineCallback, "LineCallback"); // Start the action only if there is something to read if (aIS != null) if (bReadAllLines || nLinesToRead > 0) { try (final NonBlockingBufferedReader aBR = new NonBlockingBufferedReader (createReader (aIS, aCharset))) { // read with the passed charset _readFromReader (nLinesToSkip, nLinesToRead, aLineCallback, bReadAllLines, aBR); } catch (final IOException ex) { LOGGER.error ("Failed to read from input stream", ex instanceof IMockException ? null : ex); } } } finally { // Close input stream in case something went wrong with the buffered // reader. close (aIS); } }
java
public static void readStreamLines (@WillClose @Nullable final InputStream aIS, @Nonnull @Nonempty final Charset aCharset, @Nonnegative final int nLinesToSkip, final int nLinesToRead, @Nonnull final Consumer <? super String> aLineCallback) { try { ValueEnforcer.notNull (aCharset, "Charset"); ValueEnforcer.isGE0 (nLinesToSkip, "LinesToSkip"); final boolean bReadAllLines = nLinesToRead == CGlobal.ILLEGAL_UINT; ValueEnforcer.isTrue (bReadAllLines || nLinesToRead >= 0, () -> "Line count may not be that negative: " + nLinesToRead); ValueEnforcer.notNull (aLineCallback, "LineCallback"); // Start the action only if there is something to read if (aIS != null) if (bReadAllLines || nLinesToRead > 0) { try (final NonBlockingBufferedReader aBR = new NonBlockingBufferedReader (createReader (aIS, aCharset))) { // read with the passed charset _readFromReader (nLinesToSkip, nLinesToRead, aLineCallback, bReadAllLines, aBR); } catch (final IOException ex) { LOGGER.error ("Failed to read from input stream", ex instanceof IMockException ? null : ex); } } } finally { // Close input stream in case something went wrong with the buffered // reader. close (aIS); } }
[ "public", "static", "void", "readStreamLines", "(", "@", "WillClose", "@", "Nullable", "final", "InputStream", "aIS", ",", "@", "Nonnull", "@", "Nonempty", "final", "Charset", "aCharset", ",", "@", "Nonnegative", "final", "int", "nLinesToSkip", ",", "final", "...
Read the content of the passed stream line by line and invoking a callback on all matching lines. @param aIS The input stream to read from. May be <code>null</code>. @param aCharset The character set to use. May not be <code>null</code>. @param nLinesToSkip The 0-based index of the first line to read. Pass in 0 to indicate to read everything. @param nLinesToRead The number of lines to read. Pass in {@link CGlobal#ILLEGAL_UINT} to indicate that all lines should be read. If the number passed here exceeds the number of lines in the file, nothing happens. @param aLineCallback The callback that is invoked for all read lines. Each passed line does NOT contain the line delimiter! Note: it is not invoked for skipped lines!
[ "Read", "the", "content", "of", "the", "passed", "stream", "line", "by", "line", "and", "invoking", "a", "callback", "on", "all", "matching", "lines", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/io/stream/StreamHelper.java#L1213-L1249
hyperledger/fabric-sdk-java
src/main/java/org/hyperledger/fabric/sdk/Channel.java
Channel.queryTransactionByID
public TransactionInfo queryTransactionByID(Peer peer, String txID) throws ProposalException, InvalidArgumentException { return queryTransactionByID(Collections.singleton(peer), txID, client.getUserContext()); }
java
public TransactionInfo queryTransactionByID(Peer peer, String txID) throws ProposalException, InvalidArgumentException { return queryTransactionByID(Collections.singleton(peer), txID, client.getUserContext()); }
[ "public", "TransactionInfo", "queryTransactionByID", "(", "Peer", "peer", ",", "String", "txID", ")", "throws", "ProposalException", ",", "InvalidArgumentException", "{", "return", "queryTransactionByID", "(", "Collections", ".", "singleton", "(", "peer", ")", ",", ...
Query for a Fabric Transaction given its transactionID <STRONG>This method may not be thread safe if client context is changed!</STRONG> @param txID the ID of the transaction @param peer the peer to send the request to @return a {@link TransactionInfo} @throws ProposalException @throws InvalidArgumentException
[ "Query", "for", "a", "Fabric", "Transaction", "given", "its", "transactionID" ]
train
https://github.com/hyperledger/fabric-sdk-java/blob/4a2d7b3408b8b0a1ed812aa36942c438159c37a0/src/main/java/org/hyperledger/fabric/sdk/Channel.java#L3196-L3198
jcustenborder/connect-utils
connect-utils/src/main/java/com/github/jcustenborder/kafka/connect/utils/config/recommenders/Recommenders.java
Recommenders.visibleIf
public static ConfigDef.Recommender visibleIf(String configKey, Object value) { return new VisibleIfRecommender(configKey, value, ValidValuesCallback.EMPTY); }
java
public static ConfigDef.Recommender visibleIf(String configKey, Object value) { return new VisibleIfRecommender(configKey, value, ValidValuesCallback.EMPTY); }
[ "public", "static", "ConfigDef", ".", "Recommender", "visibleIf", "(", "String", "configKey", ",", "Object", "value", ")", "{", "return", "new", "VisibleIfRecommender", "(", "configKey", ",", "value", ",", "ValidValuesCallback", ".", "EMPTY", ")", ";", "}" ]
Method is used to return a recommender that will mark a ConfigItem as visible if the configKey is set to the specified value. @param configKey The setting to retrieve the value from. @param value The expected value. @return recommender
[ "Method", "is", "used", "to", "return", "a", "recommender", "that", "will", "mark", "a", "ConfigItem", "as", "visible", "if", "the", "configKey", "is", "set", "to", "the", "specified", "value", "." ]
train
https://github.com/jcustenborder/connect-utils/blob/19add138921f59ffcc85282d7aad551eeb582370/connect-utils/src/main/java/com/github/jcustenborder/kafka/connect/utils/config/recommenders/Recommenders.java#L36-L38
bullhorn/sdk-rest
src/main/java/com/bullhornsdk/data/api/StandardBullhornData.java
StandardBullhornData.handleGetMultipleEntities
protected <L extends ListWrapper<T>, T extends BullhornEntity> L handleGetMultipleEntities(Class<T> type, Set<Integer> idList, Set<String> fieldSet, EntityParams params) { String ids = idList.stream().map(id -> String.valueOf(id)).collect(Collectors.joining(",")); Map<String, String> uriVariables = restUriVariablesFactory.getUriVariablesForGetMultiple(BullhornEntityInfo.getTypesRestEntityName(type), ids, fieldSet, params); String url = restUrlFactory.assembleEntityUrl(params); try { String response = this.performGetRequest(url, String.class, uriVariables); try { return restJsonConverter.jsonToEntityDoNotUnwrapRoot(response, BullhornEntityInfo.getTypesListWrapperType(type)); } catch(RestMappingException onlyOneEntityWasReturned) { List<T> list = new ArrayList<T>(); list.add(restJsonConverter.jsonToEntityUnwrapRoot(response, type)); return (L) new StandardListWrapper<T>(list); } } catch(RestApiException noneReturned) { List<T> list = new ArrayList<T>(); return (L) new StandardListWrapper<T>(list); } }
java
protected <L extends ListWrapper<T>, T extends BullhornEntity> L handleGetMultipleEntities(Class<T> type, Set<Integer> idList, Set<String> fieldSet, EntityParams params) { String ids = idList.stream().map(id -> String.valueOf(id)).collect(Collectors.joining(",")); Map<String, String> uriVariables = restUriVariablesFactory.getUriVariablesForGetMultiple(BullhornEntityInfo.getTypesRestEntityName(type), ids, fieldSet, params); String url = restUrlFactory.assembleEntityUrl(params); try { String response = this.performGetRequest(url, String.class, uriVariables); try { return restJsonConverter.jsonToEntityDoNotUnwrapRoot(response, BullhornEntityInfo.getTypesListWrapperType(type)); } catch(RestMappingException onlyOneEntityWasReturned) { List<T> list = new ArrayList<T>(); list.add(restJsonConverter.jsonToEntityUnwrapRoot(response, type)); return (L) new StandardListWrapper<T>(list); } } catch(RestApiException noneReturned) { List<T> list = new ArrayList<T>(); return (L) new StandardListWrapper<T>(list); } }
[ "protected", "<", "L", "extends", "ListWrapper", "<", "T", ">", ",", "T", "extends", "BullhornEntity", ">", "L", "handleGetMultipleEntities", "(", "Class", "<", "T", ">", "type", ",", "Set", "<", "Integer", ">", "idList", ",", "Set", "<", "String", ">", ...
Makes the "entity" api call for getting multiple entities. <p> <p> HTTP Method: GET @param type @param idList @param fieldSet @param params @param <L> @param <T> @return
[ "Makes", "the", "entity", "api", "call", "for", "getting", "multiple", "entities", ".", "<p", ">", "<p", ">", "HTTP", "Method", ":", "GET" ]
train
https://github.com/bullhorn/sdk-rest/blob/0c75a141c768bb31510afc3a412c11bd101eca06/src/main/java/com/bullhornsdk/data/api/StandardBullhornData.java#L881-L898
alkacon/opencms-core
src/org/opencms/publish/CmsPublishManager.java
CmsPublishManager.getRelatedResourcesToPublish
public CmsPublishList getRelatedResourcesToPublish(CmsObject cms, CmsPublishList publishList) throws CmsException { return m_securityManager.getRelatedResourcesToPublish( cms.getRequestContext(), publishList, CmsRelationFilter.TARGETS.filterStrong()); }
java
public CmsPublishList getRelatedResourcesToPublish(CmsObject cms, CmsPublishList publishList) throws CmsException { return m_securityManager.getRelatedResourcesToPublish( cms.getRequestContext(), publishList, CmsRelationFilter.TARGETS.filterStrong()); }
[ "public", "CmsPublishList", "getRelatedResourcesToPublish", "(", "CmsObject", "cms", ",", "CmsPublishList", "publishList", ")", "throws", "CmsException", "{", "return", "m_securityManager", ".", "getRelatedResourcesToPublish", "(", "cms", ".", "getRequestContext", "(", ")...
Returns a new publish list that contains the unpublished resources related to all resources in the given publish list, the related resources exclude all resources in the given publish list and also locked (by other users) resources.<p> @param cms the cms request context @param publishList the publish list to exclude from result @return a new publish list that contains the related resources @throws CmsException if something goes wrong
[ "Returns", "a", "new", "publish", "list", "that", "contains", "the", "unpublished", "resources", "related", "to", "all", "resources", "in", "the", "given", "publish", "list", "the", "related", "resources", "exclude", "all", "resources", "in", "the", "given", "...
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/publish/CmsPublishManager.java#L428-L434
Javacord/Javacord
javacord-core/src/main/java/org/javacord/core/DiscordApiImpl.java
DiscordApiImpl.forEachCachedMessageWhere
public void forEachCachedMessageWhere(Predicate<Message> filter, Consumer<Message> action) { synchronized (messages) { messages.values().stream() .map(Reference::get) .filter(Objects::nonNull) .filter(filter) .forEach(action); } }
java
public void forEachCachedMessageWhere(Predicate<Message> filter, Consumer<Message> action) { synchronized (messages) { messages.values().stream() .map(Reference::get) .filter(Objects::nonNull) .filter(filter) .forEach(action); } }
[ "public", "void", "forEachCachedMessageWhere", "(", "Predicate", "<", "Message", ">", "filter", ",", "Consumer", "<", "Message", ">", "action", ")", "{", "synchronized", "(", "messages", ")", "{", "messages", ".", "values", "(", ")", ".", "stream", "(", ")...
Execute a task for every message in cache that satisfied a given condition. @param filter The condition on which to execute the code. @param action The action to be applied to the messages.
[ "Execute", "a", "task", "for", "every", "message", "in", "cache", "that", "satisfied", "a", "given", "condition", "." ]
train
https://github.com/Javacord/Javacord/blob/915aad084dc5e863284267529d0dccd625fc6886/javacord-core/src/main/java/org/javacord/core/DiscordApiImpl.java#L1409-L1417
VoltDB/voltdb
src/frontend/org/voltdb/exportclient/ExportEncoder.java
ExportEncoder.encodeGeographyPoint
static public void encodeGeographyPoint(final FastSerializer fs, GeographyPointValue value) throws IOException { final int length = GeographyPointValue.getLengthInBytes(); ByteBuffer bb = ByteBuffer.allocate(length); bb.order(ByteOrder.nativeOrder()); value.flattenToBuffer(bb); byte[] array = bb.array(); assert(array.length == length); fs.write(array); }
java
static public void encodeGeographyPoint(final FastSerializer fs, GeographyPointValue value) throws IOException { final int length = GeographyPointValue.getLengthInBytes(); ByteBuffer bb = ByteBuffer.allocate(length); bb.order(ByteOrder.nativeOrder()); value.flattenToBuffer(bb); byte[] array = bb.array(); assert(array.length == length); fs.write(array); }
[ "static", "public", "void", "encodeGeographyPoint", "(", "final", "FastSerializer", "fs", ",", "GeographyPointValue", "value", ")", "throws", "IOException", "{", "final", "int", "length", "=", "GeographyPointValue", ".", "getLengthInBytes", "(", ")", ";", "ByteBuffe...
Encode a GEOGRAPHY_POINT according to the Export encoding specification. @param fs The serializer to serialize to @throws IOException
[ "Encode", "a", "GEOGRAPHY_POINT", "according", "to", "the", "Export", "encoding", "specification", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/exportclient/ExportEncoder.java#L315-L326
jparsec/jparsec
jparsec/src/main/java/org/jparsec/Parsers.java
Parsers.sequence
public static <T> Parser<T> sequence(Parser<?> p1, Parser<T> p2) { return sequence(p1, p2, InternalFunctors.<Object, T>lastOfTwo()); }
java
public static <T> Parser<T> sequence(Parser<?> p1, Parser<T> p2) { return sequence(p1, p2, InternalFunctors.<Object, T>lastOfTwo()); }
[ "public", "static", "<", "T", ">", "Parser", "<", "T", ">", "sequence", "(", "Parser", "<", "?", ">", "p1", ",", "Parser", "<", "T", ">", "p2", ")", "{", "return", "sequence", "(", "p1", ",", "p2", ",", "InternalFunctors", ".", "<", "Object", ","...
A {@link Parser} that runs 2 parser objects sequentially. {@code p1} is executed, if it succeeds, {@code p2} is executed.
[ "A", "{" ]
train
https://github.com/jparsec/jparsec/blob/df1280259f5da9eb5ffc537437569dddba66cb94/jparsec/src/main/java/org/jparsec/Parsers.java#L219-L221
apache/incubator-gobblin
gobblin-utility/src/main/java/org/apache/gobblin/util/HadoopUtils.java
HadoopUtils.setGroup
public static void setGroup(FileSystem fs, Path path, String group) throws IOException { fs.setOwner(path, fs.getFileStatus(path).getOwner(), group); }
java
public static void setGroup(FileSystem fs, Path path, String group) throws IOException { fs.setOwner(path, fs.getFileStatus(path).getOwner(), group); }
[ "public", "static", "void", "setGroup", "(", "FileSystem", "fs", ",", "Path", "path", ",", "String", "group", ")", "throws", "IOException", "{", "fs", ".", "setOwner", "(", "path", ",", "fs", ".", "getFileStatus", "(", "path", ")", ".", "getOwner", "(", ...
Set the group associated with a given path. @param fs the {@link FileSystem} instance used to perform the file operation @param path the given path @param group the group associated with the path @throws IOException
[ "Set", "the", "group", "associated", "with", "a", "given", "path", "." ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/HadoopUtils.java#L779-L781
carewebframework/carewebframework-core
org.carewebframework.ui-parent/org.carewebframework.ui.core/src/main/java/org/carewebframework/ui/command/CommandUtil.java
CommandUtil.getCommand
public static Command getCommand(String commandName, boolean forceCreate) { return CommandRegistry.getInstance().get(commandName, forceCreate); }
java
public static Command getCommand(String commandName, boolean forceCreate) { return CommandRegistry.getInstance().get(commandName, forceCreate); }
[ "public", "static", "Command", "getCommand", "(", "String", "commandName", ",", "boolean", "forceCreate", ")", "{", "return", "CommandRegistry", ".", "getInstance", "(", ")", ".", "get", "(", "commandName", ",", "forceCreate", ")", ";", "}" ]
Returns a command from the command registry. @param commandName Name of the command. @param forceCreate If true and the named command does not exist, one will be created and added to the command registry. @return The command object corresponding to the specified command name.
[ "Returns", "a", "command", "from", "the", "command", "registry", "." ]
train
https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.ui-parent/org.carewebframework.ui.core/src/main/java/org/carewebframework/ui/command/CommandUtil.java#L236-L238
SeleniumHQ/selenium
java/client/src/org/openqa/selenium/interactions/Actions.java
Actions.sendKeys
public Actions sendKeys(CharSequence... keys) { if (isBuildingActions()) { action.addAction(new SendKeysAction(jsonKeyboard, jsonMouse, null, keys)); } return sendKeysInTicks(keys); }
java
public Actions sendKeys(CharSequence... keys) { if (isBuildingActions()) { action.addAction(new SendKeysAction(jsonKeyboard, jsonMouse, null, keys)); } return sendKeysInTicks(keys); }
[ "public", "Actions", "sendKeys", "(", "CharSequence", "...", "keys", ")", "{", "if", "(", "isBuildingActions", "(", ")", ")", "{", "action", ".", "addAction", "(", "new", "SendKeysAction", "(", "jsonKeyboard", ",", "jsonMouse", ",", "null", ",", "keys", ")...
Sends keys to the active element. This differs from calling {@link WebElement#sendKeys(CharSequence...)} on the active element in two ways: <ul> <li>The modifier keys included in this call are not released.</li> <li>There is no attempt to re-focus the element - so sendKeys(Keys.TAB) for switching elements should work. </li> </ul> @see WebElement#sendKeys(CharSequence...) @param keys The keys. @return A self reference. @throws IllegalArgumentException if keys is null
[ "Sends", "keys", "to", "the", "active", "element", ".", "This", "differs", "from", "calling", "{", "@link", "WebElement#sendKeys", "(", "CharSequence", "...", ")", "}", "on", "the", "active", "element", "in", "two", "ways", ":", "<ul", ">", "<li", ">", "...
train
https://github.com/SeleniumHQ/selenium/blob/7af172729f17b20269c8ca4ea6f788db48616535/java/client/src/org/openqa/selenium/interactions/Actions.java#L161-L167
kotcrab/vis-ui
ui/src/main/java/com/kotcrab/vis/ui/layout/DragPane.java
DragPane.removeActor
@Override public boolean removeActor (final Actor actor, final boolean unfocus) { if (getActor().getChildren().contains(actor, true)) { // Stage input focus causes problems, as touchUp is called in Draggable. Reproducing input unfocus after stage removed. Stage stage = actor.getStage(); getActor().removeActor(actor, false); // Stage is cleared. if (unfocus && stage != null) { stage.unfocus(actor); } return true; } return false; }
java
@Override public boolean removeActor (final Actor actor, final boolean unfocus) { if (getActor().getChildren().contains(actor, true)) { // Stage input focus causes problems, as touchUp is called in Draggable. Reproducing input unfocus after stage removed. Stage stage = actor.getStage(); getActor().removeActor(actor, false); // Stage is cleared. if (unfocus && stage != null) { stage.unfocus(actor); } return true; } return false; }
[ "@", "Override", "public", "boolean", "removeActor", "(", "final", "Actor", "actor", ",", "final", "boolean", "unfocus", ")", "{", "if", "(", "getActor", "(", ")", ".", "getChildren", "(", ")", ".", "contains", "(", "actor", ",", "true", ")", ")", "{",...
Removes an actor from this group. If the actor will not be used again and has actions, they should be {@link Actor#clearActions() cleared} so the actions will be returned to their {@link Action#setPool(com.badlogic.gdx.utils.Pool) pool}, if any. This is not done automatically. <p> Note that the direct parent of {@link DragPane}'s children is the internal pane's group accessible through {@link #getGroup()} - and since this removal method is overridden and extended, pane's children should be deleted with {@code dragPane.removeActor(child, true)} rather than {@link Actor#remove()} method. @param unfocus if true, {@link Stage#unfocus(Actor)} is called. @param actor will be removed, if present in the internal {@link WidgetGroup}. @return true if the actor was removed from this group.
[ "Removes", "an", "actor", "from", "this", "group", ".", "If", "the", "actor", "will", "not", "be", "used", "again", "and", "has", "actions", "they", "should", "be", "{" ]
train
https://github.com/kotcrab/vis-ui/blob/3b68f82d94ae32bffa2a3399c63f432e0f4908e0/ui/src/main/java/com/kotcrab/vis/ui/layout/DragPane.java#L290-L302
cloudiator/sword
core/src/main/java/de/uniulm/omi/cloudiator/sword/domain/TemplateOptionsBuilder.java
TemplateOptionsBuilder.addOption
public TemplateOptionsBuilder addOption(Object field, Object value) { additionalOptions.put(field, value); return this; }
java
public TemplateOptionsBuilder addOption(Object field, Object value) { additionalOptions.put(field, value); return this; }
[ "public", "TemplateOptionsBuilder", "addOption", "(", "Object", "field", ",", "Object", "value", ")", "{", "additionalOptions", ".", "put", "(", "field", ",", "value", ")", ";", "return", "this", ";", "}" ]
Adds a generic option to the template @param field key of the option @param value value of the option @return fluid interface
[ "Adds", "a", "generic", "option", "to", "the", "template" ]
train
https://github.com/cloudiator/sword/blob/b7808ea2776c6d70d439342c403369dfc5bb26bc/core/src/main/java/de/uniulm/omi/cloudiator/sword/domain/TemplateOptionsBuilder.java#L88-L91
ngageoint/geopackage-android-map
geopackage-map/src/main/java/mil/nga/geopackage/map/features/StyleUtils.java
StyleUtils.setIcon
public static boolean setIcon(MarkerOptions markerOptions, IconRow icon, float density) { return setIcon(markerOptions, icon, density, null); }
java
public static boolean setIcon(MarkerOptions markerOptions, IconRow icon, float density) { return setIcon(markerOptions, icon, density, null); }
[ "public", "static", "boolean", "setIcon", "(", "MarkerOptions", "markerOptions", ",", "IconRow", "icon", ",", "float", "density", ")", "{", "return", "setIcon", "(", "markerOptions", ",", "icon", ",", "density", ",", "null", ")", ";", "}" ]
Set the icon into the marker options @param markerOptions marker options @param icon icon row @param density display density: {@link android.util.DisplayMetrics#density} @return true if icon was set into the marker options
[ "Set", "the", "icon", "into", "the", "marker", "options" ]
train
https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/features/StyleUtils.java#L251-L253
apereo/cas
core/cas-server-core-util-api/src/main/java/org/apereo/cas/util/serialization/SerializationUtils.java
SerializationUtils.decodeAndDeserializeObject
@SneakyThrows public static <T extends Serializable> T decodeAndDeserializeObject(final byte[] object, final CipherExecutor cipher, final Class<T> type) { return decodeAndDeserializeObject(object, cipher, type, ArrayUtils.EMPTY_OBJECT_ARRAY); }
java
@SneakyThrows public static <T extends Serializable> T decodeAndDeserializeObject(final byte[] object, final CipherExecutor cipher, final Class<T> type) { return decodeAndDeserializeObject(object, cipher, type, ArrayUtils.EMPTY_OBJECT_ARRAY); }
[ "@", "SneakyThrows", "public", "static", "<", "T", "extends", "Serializable", ">", "T", "decodeAndDeserializeObject", "(", "final", "byte", "[", "]", "object", ",", "final", "CipherExecutor", "cipher", ",", "final", "Class", "<", "T", ">", "type", ")", "{", ...
Decode and deserialize object t. @param <T> the type parameter @param object the object @param cipher the cipher @param type the type @return the t
[ "Decode", "and", "deserialize", "object", "t", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/core/cas-server-core-util-api/src/main/java/org/apereo/cas/util/serialization/SerializationUtils.java#L150-L155
hellosign/hellosign-java-sdk
src/main/java/com/hellosign/sdk/resource/TemplateDraft.java
TemplateDraft.addSignerRole
public void addSignerRole(String role, int order) throws HelloSignException { try { signerRoles.add((order - 1), role); } catch (Exception ex) { throw new HelloSignException(ex); } }
java
public void addSignerRole(String role, int order) throws HelloSignException { try { signerRoles.add((order - 1), role); } catch (Exception ex) { throw new HelloSignException(ex); } }
[ "public", "void", "addSignerRole", "(", "String", "role", ",", "int", "order", ")", "throws", "HelloSignException", "{", "try", "{", "signerRoles", ".", "add", "(", "(", "order", "-", "1", ")", ",", "role", ")", ";", "}", "catch", "(", "Exception", "ex...
Adds the signer role with the given order to the list of signers for this request. NOTE: The order refers to the 1-base index, not 0-base. This is to reflect the indexing used by the HelloSign API. This means that adding an item at order 1 will place it in the 0th index of the list (it will be the first item). @param role String @param order int @throws HelloSignException thrown if there is a problem adding the signer role.
[ "Adds", "the", "signer", "role", "with", "the", "given", "order", "to", "the", "list", "of", "signers", "for", "this", "request", ".", "NOTE", ":", "The", "order", "refers", "to", "the", "1", "-", "base", "index", "not", "0", "-", "base", ".", "This"...
train
https://github.com/hellosign/hellosign-java-sdk/blob/08fa7aeb3b0c68ddb6c7ea797d114d55d36d36b1/src/main/java/com/hellosign/sdk/resource/TemplateDraft.java#L131-L137
apereo/cas
core/cas-server-core-services-registry/src/main/java/org/apereo/cas/services/resource/DefaultRegisteredServiceResourceNamingStrategy.java
DefaultRegisteredServiceResourceNamingStrategy.build
@Override public String build(final RegisteredService service, final String extension) { return StringUtils.remove(service.getName(), ' ') + '-' + service.getId() + '.' + extension; }
java
@Override public String build(final RegisteredService service, final String extension) { return StringUtils.remove(service.getName(), ' ') + '-' + service.getId() + '.' + extension; }
[ "@", "Override", "public", "String", "build", "(", "final", "RegisteredService", "service", ",", "final", "String", "extension", ")", "{", "return", "StringUtils", ".", "remove", "(", "service", ".", "getName", "(", ")", ",", "'", "'", ")", "+", "'", "'"...
Method creates a filename to store the service. @param service - Service to be stored. @param extension - extension to use for the file. @return - String representing file name.
[ "Method", "creates", "a", "filename", "to", "store", "the", "service", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/core/cas-server-core-services-registry/src/main/java/org/apereo/cas/services/resource/DefaultRegisteredServiceResourceNamingStrategy.java#L23-L26
jhy/jsoup
src/main/java/org/jsoup/nodes/Attributes.java
Attributes.asList
public List<Attribute> asList() { ArrayList<Attribute> list = new ArrayList<>(size); for (int i = 0; i < size; i++) { Attribute attr = vals[i] == null ? new BooleanAttribute(keys[i]) : // deprecated class, but maybe someone still wants it new Attribute(keys[i], vals[i], Attributes.this); list.add(attr); } return Collections.unmodifiableList(list); }
java
public List<Attribute> asList() { ArrayList<Attribute> list = new ArrayList<>(size); for (int i = 0; i < size; i++) { Attribute attr = vals[i] == null ? new BooleanAttribute(keys[i]) : // deprecated class, but maybe someone still wants it new Attribute(keys[i], vals[i], Attributes.this); list.add(attr); } return Collections.unmodifiableList(list); }
[ "public", "List", "<", "Attribute", ">", "asList", "(", ")", "{", "ArrayList", "<", "Attribute", ">", "list", "=", "new", "ArrayList", "<>", "(", "size", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "size", ";", "i", "++", ")", "{...
Get the attributes as a List, for iteration. @return an view of the attributes as an unmodifialbe List.
[ "Get", "the", "attributes", "as", "a", "List", "for", "iteration", "." ]
train
https://github.com/jhy/jsoup/blob/68ff8cbe7ad847059737a09c567a501a7f1d251f/src/main/java/org/jsoup/nodes/Attributes.java#L276-L285
googleapis/google-http-java-client
google-http-client/src/main/java/com/google/api/client/json/JsonFactory.java
JsonFactory.toByteStream
private ByteArrayOutputStream toByteStream(Object item, boolean pretty) throws IOException { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); JsonGenerator generator = createJsonGenerator(byteStream, Charsets.UTF_8); if (pretty) { generator.enablePrettyPrint(); } generator.serialize(item); generator.flush(); return byteStream; }
java
private ByteArrayOutputStream toByteStream(Object item, boolean pretty) throws IOException { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); JsonGenerator generator = createJsonGenerator(byteStream, Charsets.UTF_8); if (pretty) { generator.enablePrettyPrint(); } generator.serialize(item); generator.flush(); return byteStream; }
[ "private", "ByteArrayOutputStream", "toByteStream", "(", "Object", "item", ",", "boolean", "pretty", ")", "throws", "IOException", "{", "ByteArrayOutputStream", "byteStream", "=", "new", "ByteArrayOutputStream", "(", ")", ";", "JsonGenerator", "generator", "=", "creat...
Returns a UTF-8 byte array output stream of the serialized JSON representation for the given item using {@link JsonGenerator#serialize(Object)}. @param item data key/value pairs @param pretty whether to return a pretty representation @return serialized JSON string representation
[ "Returns", "a", "UTF", "-", "8", "byte", "array", "output", "stream", "of", "the", "serialized", "JSON", "representation", "for", "the", "given", "item", "using", "{", "@link", "JsonGenerator#serialize", "(", "Object", ")", "}", "." ]
train
https://github.com/googleapis/google-http-java-client/blob/0988ae4e0f26a80f579b6adb2b276dd8254928de/google-http-client/src/main/java/com/google/api/client/json/JsonFactory.java#L160-L169
moparisthebest/beehive
beehive-netui-core/src/main/java/org/apache/beehive/netui/util/internal/DiscoveryUtils.java
DiscoveryUtils.loadImplementorClass
public static Class loadImplementorClass( String className, Class interfaceType ) { return loadImplementorClass( className, interfaceType, getClassLoader() ); }
java
public static Class loadImplementorClass( String className, Class interfaceType ) { return loadImplementorClass( className, interfaceType, getClassLoader() ); }
[ "public", "static", "Class", "loadImplementorClass", "(", "String", "className", ",", "Class", "interfaceType", ")", "{", "return", "loadImplementorClass", "(", "className", ",", "interfaceType", ",", "getClassLoader", "(", ")", ")", ";", "}" ]
Load an implementor class from the context classloader. @param className the name of the implementor class. @param interfaceType the interface that the given class should implement. @return the implementor Class, or <code>null</code> if an error occurred (the error will be logged).
[ "Load", "an", "implementor", "class", "from", "the", "context", "classloader", "." ]
train
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-core/src/main/java/org/apache/beehive/netui/util/internal/DiscoveryUtils.java#L155-L158
samskivert/samskivert
src/main/java/com/samskivert/util/Runnables.java
Runnables.asRunnable
public static Runnable asRunnable (Class<?> clazz, String methodName) { Method method = findMethod(clazz, methodName); if (!Modifier.isStatic(method.getModifiers())) { throw new IllegalArgumentException( clazz.getName() + "." + methodName + "() must be static"); } return new MethodRunner(method, null); }
java
public static Runnable asRunnable (Class<?> clazz, String methodName) { Method method = findMethod(clazz, methodName); if (!Modifier.isStatic(method.getModifiers())) { throw new IllegalArgumentException( clazz.getName() + "." + methodName + "() must be static"); } return new MethodRunner(method, null); }
[ "public", "static", "Runnable", "asRunnable", "(", "Class", "<", "?", ">", "clazz", ",", "String", "methodName", ")", "{", "Method", "method", "=", "findMethod", "(", "clazz", ",", "methodName", ")", ";", "if", "(", "!", "Modifier", ".", "isStatic", "(",...
Creates a runnable that invokes the specified static method via reflection. <p> NOTE: if you specify a protected or private method this method will call {@link Method#setAccessible} to make the method accessible. If you're writing secure code or need to run in a sandbox, don't use this functionality. @throws IllegalArgumentException if the supplied method name does not correspond to a static zero-argument method of the supplied class.
[ "Creates", "a", "runnable", "that", "invokes", "the", "specified", "static", "method", "via", "reflection", "." ]
train
https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/util/Runnables.java#L58-L66
Red5/red5-server-common
src/main/java/org/red5/server/net/servlet/ServletUtils.java
ServletUtils.copy
public static void copy(HttpServletRequest req, OutputStream output) throws IOException { InputStream input = req.getInputStream(); int availableBytes = req.getContentLength(); log.debug("copy - available: {}", availableBytes); if (availableBytes > 0) { byte[] buf = new byte[availableBytes]; int bytesRead = input.read(buf); while (bytesRead != -1) { output.write(buf, 0, bytesRead); bytesRead = input.read(buf); log.trace("Bytes read: {}", bytesRead); } output.flush(); } else { log.debug("Nothing to available to copy"); } }
java
public static void copy(HttpServletRequest req, OutputStream output) throws IOException { InputStream input = req.getInputStream(); int availableBytes = req.getContentLength(); log.debug("copy - available: {}", availableBytes); if (availableBytes > 0) { byte[] buf = new byte[availableBytes]; int bytesRead = input.read(buf); while (bytesRead != -1) { output.write(buf, 0, bytesRead); bytesRead = input.read(buf); log.trace("Bytes read: {}", bytesRead); } output.flush(); } else { log.debug("Nothing to available to copy"); } }
[ "public", "static", "void", "copy", "(", "HttpServletRequest", "req", ",", "OutputStream", "output", ")", "throws", "IOException", "{", "InputStream", "input", "=", "req", ".", "getInputStream", "(", ")", ";", "int", "availableBytes", "=", "req", ".", "getCont...
Copies information from the http request to the output stream using the specified content length. @param req Request @param output Output stream @throws java.io.IOException on error
[ "Copies", "information", "from", "the", "http", "request", "to", "the", "output", "stream", "using", "the", "specified", "content", "length", "." ]
train
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/servlet/ServletUtils.java#L110-L126
joniles/mpxj
src/main/java/net/sf/mpxj/json/JsonWriter.java
JsonWriter.writePriorityField
private void writePriorityField(String fieldName, Object value) throws IOException { m_writer.writeNameValuePair(fieldName, ((Priority) value).getValue()); }
java
private void writePriorityField(String fieldName, Object value) throws IOException { m_writer.writeNameValuePair(fieldName, ((Priority) value).getValue()); }
[ "private", "void", "writePriorityField", "(", "String", "fieldName", ",", "Object", "value", ")", "throws", "IOException", "{", "m_writer", ".", "writeNameValuePair", "(", "fieldName", ",", "(", "(", "Priority", ")", "value", ")", ".", "getValue", "(", ")", ...
Write a priority field to the JSON file. @param fieldName field name @param value field value
[ "Write", "a", "priority", "field", "to", "the", "JSON", "file", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/json/JsonWriter.java#L473-L476
box/box-java-sdk
src/main/java/com/box/sdk/BoxCollaboration.java
BoxCollaboration.getPendingCollaborations
public static Collection<Info> getPendingCollaborations(BoxAPIConnection api) { URL url = PENDING_COLLABORATIONS_URL.build(api.getBaseURL()); BoxAPIRequest request = new BoxAPIRequest(api, url, "GET"); BoxJSONResponse response = (BoxJSONResponse) request.send(); JsonObject responseJSON = JsonObject.readFrom(response.getJSON()); int entriesCount = responseJSON.get("total_count").asInt(); Collection<BoxCollaboration.Info> collaborations = new ArrayList<BoxCollaboration.Info>(entriesCount); JsonArray entries = responseJSON.get("entries").asArray(); for (JsonValue entry : entries) { JsonObject entryObject = entry.asObject(); BoxCollaboration collaboration = new BoxCollaboration(api, entryObject.get("id").asString()); BoxCollaboration.Info info = collaboration.new Info(entryObject); collaborations.add(info); } return collaborations; }
java
public static Collection<Info> getPendingCollaborations(BoxAPIConnection api) { URL url = PENDING_COLLABORATIONS_URL.build(api.getBaseURL()); BoxAPIRequest request = new BoxAPIRequest(api, url, "GET"); BoxJSONResponse response = (BoxJSONResponse) request.send(); JsonObject responseJSON = JsonObject.readFrom(response.getJSON()); int entriesCount = responseJSON.get("total_count").asInt(); Collection<BoxCollaboration.Info> collaborations = new ArrayList<BoxCollaboration.Info>(entriesCount); JsonArray entries = responseJSON.get("entries").asArray(); for (JsonValue entry : entries) { JsonObject entryObject = entry.asObject(); BoxCollaboration collaboration = new BoxCollaboration(api, entryObject.get("id").asString()); BoxCollaboration.Info info = collaboration.new Info(entryObject); collaborations.add(info); } return collaborations; }
[ "public", "static", "Collection", "<", "Info", ">", "getPendingCollaborations", "(", "BoxAPIConnection", "api", ")", "{", "URL", "url", "=", "PENDING_COLLABORATIONS_URL", ".", "build", "(", "api", ".", "getBaseURL", "(", ")", ")", ";", "BoxAPIRequest", "request"...
Gets all pending collaboration invites for the current user. @param api the API connection to use. @return a collection of pending collaboration infos.
[ "Gets", "all", "pending", "collaboration", "invites", "for", "the", "current", "user", "." ]
train
https://github.com/box/box-java-sdk/blob/35b4ba69417f9d6a002c19dfaab57527750ef349/src/main/java/com/box/sdk/BoxCollaboration.java#L107-L125
thelinmichael/spotify-web-api-java
src/main/java/com/wrapper/spotify/SpotifyApi.java
SpotifyApi.replacePlaylistsTracks
public ReplacePlaylistsTracksRequest.Builder replacePlaylistsTracks(String playlist_id, JsonArray uris) { return new ReplacePlaylistsTracksRequest.Builder(accessToken) .setDefaults(httpManager, scheme, host, port) .playlist_id(playlist_id) .uris(uris); }
java
public ReplacePlaylistsTracksRequest.Builder replacePlaylistsTracks(String playlist_id, JsonArray uris) { return new ReplacePlaylistsTracksRequest.Builder(accessToken) .setDefaults(httpManager, scheme, host, port) .playlist_id(playlist_id) .uris(uris); }
[ "public", "ReplacePlaylistsTracksRequest", ".", "Builder", "replacePlaylistsTracks", "(", "String", "playlist_id", ",", "JsonArray", "uris", ")", "{", "return", "new", "ReplacePlaylistsTracksRequest", ".", "Builder", "(", "accessToken", ")", ".", "setDefaults", "(", "...
Replace tracks in a playlist. @param playlist_id The playlists ID. @param uris URIs of the tracks to add. Maximum: 100 track URIs. @return A {@link ReplacePlaylistsTracksRequest.Builder}. @see <a href="https://developer.spotify.com/web-api/user-guide/#spotify-uris-and-ids">Spotify: URLs &amp; IDs</a>
[ "Replace", "tracks", "in", "a", "playlist", "." ]
train
https://github.com/thelinmichael/spotify-web-api-java/blob/c06b8512344c0310d0c1df362fa267879021da2e/src/main/java/com/wrapper/spotify/SpotifyApi.java#L1430-L1435
jroyalty/jglm
src/main/java/com/hackoeur/jglm/support/Precision.java
Precision.equalsWithRelativeTolerance
public static boolean equalsWithRelativeTolerance(double x, double y, double eps) { if (equals(x, y, 1)) { return true; } final double absoluteMax = FastMath.max(FastMath.abs(x), FastMath.abs(y)); final double relativeDifference = FastMath.abs((x - y) / absoluteMax); return relativeDifference <= eps; }
java
public static boolean equalsWithRelativeTolerance(double x, double y, double eps) { if (equals(x, y, 1)) { return true; } final double absoluteMax = FastMath.max(FastMath.abs(x), FastMath.abs(y)); final double relativeDifference = FastMath.abs((x - y) / absoluteMax); return relativeDifference <= eps; }
[ "public", "static", "boolean", "equalsWithRelativeTolerance", "(", "double", "x", ",", "double", "y", ",", "double", "eps", ")", "{", "if", "(", "equals", "(", "x", ",", "y", ",", "1", ")", ")", "{", "return", "true", ";", "}", "final", "double", "ab...
Returns {@code true} if there is no double value strictly between the arguments or the reltaive difference between them is smaller or equal to the given tolerance. @param x First value. @param y Second value. @param eps Amount of allowed relative error. @return {@code true} if the values are two adjacent floating point numbers or they are within range of each other. @since 3.1
[ "Returns", "{", "@code", "true", "}", "if", "there", "is", "no", "double", "value", "strictly", "between", "the", "arguments", "or", "the", "reltaive", "difference", "between", "them", "is", "smaller", "or", "equal", "to", "the", "given", "tolerance", "." ]
train
https://github.com/jroyalty/jglm/blob/9397c2fcf0d4d62844c64d0b14065ee7bf8cafc6/src/main/java/com/hackoeur/jglm/support/Precision.java#L283-L292
ineunetOS/knife-commons
knife-commons-utils/src/main/java/com/ineunet/knife/util/TextUtils.java
TextUtils.asterisked
public static String asterisked(String str, int keepSize, boolean keepStart) { if (StringUtils.isBlank(str)) return ""; int length = str.length(); if (length < keepSize) return str; if (keepSize < 1) return getAsterisks(length); int notKeepSize = length - keepSize; String keep; if (keepStart) { keep = str.substring(0, keepSize); return keep + getAsterisks(notKeepSize); } else { keep = str.substring(notKeepSize); return getAsterisks(notKeepSize) + keep; } }
java
public static String asterisked(String str, int keepSize, boolean keepStart) { if (StringUtils.isBlank(str)) return ""; int length = str.length(); if (length < keepSize) return str; if (keepSize < 1) return getAsterisks(length); int notKeepSize = length - keepSize; String keep; if (keepStart) { keep = str.substring(0, keepSize); return keep + getAsterisks(notKeepSize); } else { keep = str.substring(notKeepSize); return getAsterisks(notKeepSize) + keep; } }
[ "public", "static", "String", "asterisked", "(", "String", "str", ",", "int", "keepSize", ",", "boolean", "keepStart", ")", "{", "if", "(", "StringUtils", ".", "isBlank", "(", "str", ")", ")", "return", "\"\"", ";", "int", "length", "=", "str", ".", "l...
将字符串内容替换成星号.<br> Replace to asterisk. @param str e.g. 123456 @param keepSize e.g. 4 @param keepStart e.g. false @return e.g. **3456
[ "将字符串内容替换成星号", ".", "<br", ">", "Replace", "to", "asterisk", "." ]
train
https://github.com/ineunetOS/knife-commons/blob/eae9e59afa020a00ae8977c10d43ac8ae46ae236/knife-commons-utils/src/main/java/com/ineunet/knife/util/TextUtils.java#L34-L50
kite-sdk/kite
kite-tools-parent/kite-tools/src/main/java/org/kitesdk/cli/commands/InputFormatImportCommand.java
InputFormatImportCommand.runTaskWithClassLoader
private static PipelineResult runTaskWithClassLoader( final TransformTask task, final ClassLoader loader) throws IOException, InterruptedException { RunnableFuture<PipelineResult> future = new FutureTask<PipelineResult>( new Callable<PipelineResult>() { @Override public PipelineResult call() throws Exception { return task.run(); } }); Executors.newSingleThreadExecutor( new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread taskThread = new Thread(r, "transform-task"); taskThread.setContextClassLoader(loader); return taskThread; } }).execute(future); try { return future.get(); } catch (ExecutionException e) { Throwables.propagateIfInstanceOf(e.getCause(), IOException.class); throw Throwables.propagate(e.getCause()); } }
java
private static PipelineResult runTaskWithClassLoader( final TransformTask task, final ClassLoader loader) throws IOException, InterruptedException { RunnableFuture<PipelineResult> future = new FutureTask<PipelineResult>( new Callable<PipelineResult>() { @Override public PipelineResult call() throws Exception { return task.run(); } }); Executors.newSingleThreadExecutor( new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread taskThread = new Thread(r, "transform-task"); taskThread.setContextClassLoader(loader); return taskThread; } }).execute(future); try { return future.get(); } catch (ExecutionException e) { Throwables.propagateIfInstanceOf(e.getCause(), IOException.class); throw Throwables.propagate(e.getCause()); } }
[ "private", "static", "PipelineResult", "runTaskWithClassLoader", "(", "final", "TransformTask", "task", ",", "final", "ClassLoader", "loader", ")", "throws", "IOException", ",", "InterruptedException", "{", "RunnableFuture", "<", "PipelineResult", ">", "future", "=", ...
Runs a task with the given {@link ClassLoader} as the context loader. @param task a {@link TransformTask} @param loader a {@link ClassLoader} @return the result of {@link TransformTask#run} @throws IOException if the task throws an IOException @throws InterruptedException if the task execution is interrupted
[ "Runs", "a", "task", "with", "the", "given", "{", "@link", "ClassLoader", "}", "as", "the", "context", "loader", "." ]
train
https://github.com/kite-sdk/kite/blob/72bfb4b1a881af85808cd7f14bc3e15160a1e811/kite-tools-parent/kite-tools/src/main/java/org/kitesdk/cli/commands/InputFormatImportCommand.java#L235-L262
codeprimate-software/cp-elements
src/main/java/org/cp/elements/lang/StringUtils.java
StringUtils.equalsIgnoreCase
@NullSafe public static boolean equalsIgnoreCase(String stringOne, String stringTwo) { return stringOne != null && stringOne.equalsIgnoreCase(stringTwo); }
java
@NullSafe public static boolean equalsIgnoreCase(String stringOne, String stringTwo) { return stringOne != null && stringOne.equalsIgnoreCase(stringTwo); }
[ "@", "NullSafe", "public", "static", "boolean", "equalsIgnoreCase", "(", "String", "stringOne", ",", "String", "stringTwo", ")", "{", "return", "stringOne", "!=", "null", "&&", "stringOne", ".", "equalsIgnoreCase", "(", "stringTwo", ")", ";", "}" ]
Determines whether two String values are equal in value ignoring case and guarding against null values. @param stringOne the first String value in the case-insensitive equality comparison. @param stringTwo the second String value in the case-insensitive equality comparison. @return a boolean value indicating if the two String values are equal in value ignore case. @see java.lang.String#equalsIgnoreCase(String)
[ "Determines", "whether", "two", "String", "values", "are", "equal", "in", "value", "ignoring", "case", "and", "guarding", "against", "null", "values", "." ]
train
https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/lang/StringUtils.java#L226-L229
eyp/serfj
src/main/java/net/sf/serfj/UrlInspector.java
UrlInspector.getSerializerClass
protected String getSerializerClass(String resource, String urlLastElement) { String serializerClass = null; String extension = this.utils.getExtension(urlLastElement); if (extension != null) { SerializerFinder finder = new SerializerFinder(config, extension); serializerClass = finder.findResource(resource); } return serializerClass; }
java
protected String getSerializerClass(String resource, String urlLastElement) { String serializerClass = null; String extension = this.utils.getExtension(urlLastElement); if (extension != null) { SerializerFinder finder = new SerializerFinder(config, extension); serializerClass = finder.findResource(resource); } return serializerClass; }
[ "protected", "String", "getSerializerClass", "(", "String", "resource", ",", "String", "urlLastElement", ")", "{", "String", "serializerClass", "=", "null", ";", "String", "extension", "=", "this", ".", "utils", ".", "getExtension", "(", "urlLastElement", ")", "...
Gets serializer class for a resource. If the last part of the URL has an extension, then could be a Serializer class to render the result in a specific way. If the extension is .xml it hopes that a ResourceNameXmlSerializer exists to render the resource as Xml. The extension can be anything. @param resource Resource that will managed by the controller class. @param urlLastElement Last element of the URL analyzed. @return The fully qualified name of the serializer class for this resource and extension.
[ "Gets", "serializer", "class", "for", "a", "resource", ".", "If", "the", "last", "part", "of", "the", "URL", "has", "an", "extension", "then", "could", "be", "a", "Serializer", "class", "to", "render", "the", "result", "in", "a", "specific", "way", ".", ...
train
https://github.com/eyp/serfj/blob/e617592af6f24e59ea58443f2785c44aa2312189/src/main/java/net/sf/serfj/UrlInspector.java#L237-L245
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/SFTrustManager.java
SFTrustManager.encodeCacheKey
private static String encodeCacheKey(OcspResponseCacheKey ocsp_cache_key) { try { DigestCalculator digest = new SHA1DigestCalculator(); AlgorithmIdentifier algo = digest.getAlgorithmIdentifier(); ASN1OctetString nameHash = ASN1OctetString.getInstance(ocsp_cache_key.nameHash); ASN1OctetString keyHash = ASN1OctetString.getInstance(ocsp_cache_key.keyHash); ASN1Integer snumber = new ASN1Integer(ocsp_cache_key.serialNumber); CertID cid = new CertID(algo, nameHash, keyHash, snumber); return Base64.encodeBase64String(cid.toASN1Primitive().getEncoded()); } catch (Exception ex) { LOGGER.debug("Failed to encode cache key to base64 encoded cert id"); } return null; }
java
private static String encodeCacheKey(OcspResponseCacheKey ocsp_cache_key) { try { DigestCalculator digest = new SHA1DigestCalculator(); AlgorithmIdentifier algo = digest.getAlgorithmIdentifier(); ASN1OctetString nameHash = ASN1OctetString.getInstance(ocsp_cache_key.nameHash); ASN1OctetString keyHash = ASN1OctetString.getInstance(ocsp_cache_key.keyHash); ASN1Integer snumber = new ASN1Integer(ocsp_cache_key.serialNumber); CertID cid = new CertID(algo, nameHash, keyHash, snumber); return Base64.encodeBase64String(cid.toASN1Primitive().getEncoded()); } catch (Exception ex) { LOGGER.debug("Failed to encode cache key to base64 encoded cert id"); } return null; }
[ "private", "static", "String", "encodeCacheKey", "(", "OcspResponseCacheKey", "ocsp_cache_key", ")", "{", "try", "{", "DigestCalculator", "digest", "=", "new", "SHA1DigestCalculator", "(", ")", ";", "AlgorithmIdentifier", "algo", "=", "digest", ".", "getAlgorithmIdent...
Convert cache key to base64 encoded cert id @param ocsp_cache_key Cache key to encode
[ "Convert", "cache", "key", "to", "base64", "encoded", "cert", "id" ]
train
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/SFTrustManager.java#L663-L680
threerings/narya
core/src/main/java/com/threerings/presents/client/Client.java
Client.registerFlushDelay
public void registerFlushDelay (Class<?> objclass, long delay) { ClientDObjectMgr omgr = (ClientDObjectMgr)getDObjectManager(); omgr.registerFlushDelay(objclass, delay); }
java
public void registerFlushDelay (Class<?> objclass, long delay) { ClientDObjectMgr omgr = (ClientDObjectMgr)getDObjectManager(); omgr.registerFlushDelay(objclass, delay); }
[ "public", "void", "registerFlushDelay", "(", "Class", "<", "?", ">", "objclass", ",", "long", "delay", ")", "{", "ClientDObjectMgr", "omgr", "=", "(", "ClientDObjectMgr", ")", "getDObjectManager", "(", ")", ";", "omgr", ".", "registerFlushDelay", "(", "objclas...
Instructs the distributed object manager associated with this client to allow objects of the specified class to linger around the specified number of milliseconds after their last subscriber has been removed before the client finally removes its object proxy and flushes the object. Normally, objects are flushed immediately following the removal of their last subscriber. <p><em>Note:</em> the delay will be applied to derived classes as well as exact matches. <em>Note also:</em> this method cannot be called until after the client has established a connection with the server and the distributed object manager is available.
[ "Instructs", "the", "distributed", "object", "manager", "associated", "with", "this", "client", "to", "allow", "objects", "of", "the", "specified", "class", "to", "linger", "around", "the", "specified", "number", "of", "milliseconds", "after", "their", "last", "...
train
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/client/Client.java#L344-L348
nobuoka/android-lib-ZXingCaptureActivity
src/main/java/info/vividcode/android/zxing/camera/CameraManager.java
CameraManager.requestPreviewFrame
public synchronized void requestPreviewFrame(Handler handler, int message) { Camera theCamera = camera; if (theCamera != null && previewing) { previewCallback.setHandler(handler, message); theCamera.setOneShotPreviewCallback(previewCallback); } }
java
public synchronized void requestPreviewFrame(Handler handler, int message) { Camera theCamera = camera; if (theCamera != null && previewing) { previewCallback.setHandler(handler, message); theCamera.setOneShotPreviewCallback(previewCallback); } }
[ "public", "synchronized", "void", "requestPreviewFrame", "(", "Handler", "handler", ",", "int", "message", ")", "{", "Camera", "theCamera", "=", "camera", ";", "if", "(", "theCamera", "!=", "null", "&&", "previewing", ")", "{", "previewCallback", ".", "setHand...
A single preview frame will be returned to the handler supplied. The data will arrive as byte[] in the message.obj field, with width and height encoded as message.arg1 and message.arg2, respectively. @param handler The handler to send the message to. @param message The what field of the message to be sent.
[ "A", "single", "preview", "frame", "will", "be", "returned", "to", "the", "handler", "supplied", ".", "The", "data", "will", "arrive", "as", "byte", "[]", "in", "the", "message", ".", "obj", "field", "with", "width", "and", "height", "encoded", "as", "me...
train
https://github.com/nobuoka/android-lib-ZXingCaptureActivity/blob/17aaa7cf75520d3f2e03db9796b7e8c1d1f1b1e6/src/main/java/info/vividcode/android/zxing/camera/CameraManager.java#L192-L198
mapbox/mapbox-java
services-geojson/src/main/java/com/mapbox/geojson/MultiLineString.java
MultiLineString.fromLngLats
public static MultiLineString fromLngLats(@NonNull List<List<Point>> points) { return new MultiLineString(TYPE, null, points); }
java
public static MultiLineString fromLngLats(@NonNull List<List<Point>> points) { return new MultiLineString(TYPE, null, points); }
[ "public", "static", "MultiLineString", "fromLngLats", "(", "@", "NonNull", "List", "<", "List", "<", "Point", ">", ">", "points", ")", "{", "return", "new", "MultiLineString", "(", "TYPE", ",", "null", ",", "points", ")", ";", "}" ]
Create a new instance of this class by defining a list of a list of {@link Point}s which follow the correct specifications described in the Point documentation. Note that there should not be any duplicate points inside the list and the points combined should create a LineString with a distance greater than 0. @param points a list of {@link Point}s which make up the MultiLineString geometry @return a new instance of this class defined by the values passed inside this static factory method @since 3.0.0
[ "Create", "a", "new", "instance", "of", "this", "class", "by", "defining", "a", "list", "of", "a", "list", "of", "{", "@link", "Point", "}", "s", "which", "follow", "the", "correct", "specifications", "described", "in", "the", "Point", "documentation", "."...
train
https://github.com/mapbox/mapbox-java/blob/c0be138f462f91441388584c668f3760ba0e18e2/services-geojson/src/main/java/com/mapbox/geojson/MultiLineString.java#L161-L163
unbescape/unbescape
src/main/java/org/unbescape/xml/XmlEscape.java
XmlEscape.escapeXml11Attribute
public static void escapeXml11Attribute(final Reader reader, final Writer writer) throws IOException { escapeXml(reader, writer, XmlEscapeSymbols.XML11_ATTRIBUTE_SYMBOLS, XmlEscapeType.CHARACTER_ENTITY_REFERENCES_DEFAULT_TO_HEXA, XmlEscapeLevel.LEVEL_2_ALL_NON_ASCII_PLUS_MARKUP_SIGNIFICANT); }
java
public static void escapeXml11Attribute(final Reader reader, final Writer writer) throws IOException { escapeXml(reader, writer, XmlEscapeSymbols.XML11_ATTRIBUTE_SYMBOLS, XmlEscapeType.CHARACTER_ENTITY_REFERENCES_DEFAULT_TO_HEXA, XmlEscapeLevel.LEVEL_2_ALL_NON_ASCII_PLUS_MARKUP_SIGNIFICANT); }
[ "public", "static", "void", "escapeXml11Attribute", "(", "final", "Reader", "reader", ",", "final", "Writer", "writer", ")", "throws", "IOException", "{", "escapeXml", "(", "reader", ",", "writer", ",", "XmlEscapeSymbols", ".", "XML11_ATTRIBUTE_SYMBOLS", ",", "Xml...
<p> Perform an XML 1.1 level 2 (markup-significant and all non-ASCII chars) <strong>escape</strong> operation on a <tt>Reader</tt> input meant to be an XML attribute value, writing results to a <tt>Writer</tt>. </p> <p> <em>Level 2</em> means this method will escape: </p> <ul> <li>The five markup-significant characters: <tt>&lt;</tt>, <tt>&gt;</tt>, <tt>&amp;</tt>, <tt>&quot;</tt> and <tt>&#39;</tt></li> <li>All non ASCII characters.</li> </ul> <p> This escape will be performed by replacing those chars by the corresponding XML Character Entity References (e.g. <tt>'&amp;lt;'</tt>) when such CER exists for the replaced character, and replacing by a hexadecimal character reference (e.g. <tt>'&amp;#x2430;'</tt>) when there there is no CER for the replaced character. </p> <p> Besides, being an attribute value also <tt>&#92;t</tt>, <tt>&#92;n</tt> and <tt>&#92;r</tt> will be escaped to avoid white-space normalization from removing line feeds (turning them into white spaces) during future parsing operations. </p> <p> This method calls {@link #escapeXml11(Reader, Writer, XmlEscapeType, XmlEscapeLevel)} with the following preconfigured values: </p> <ul> <li><tt>type</tt>: {@link org.unbescape.xml.XmlEscapeType#CHARACTER_ENTITY_REFERENCES_DEFAULT_TO_HEXA}</li> <li><tt>level</tt>: {@link org.unbescape.xml.XmlEscapeLevel#LEVEL_2_ALL_NON_ASCII_PLUS_MARKUP_SIGNIFICANT}</li> </ul> <p> This method is <strong>thread-safe</strong>. </p> @param reader the <tt>Reader</tt> reading the text to be escaped. @param writer the <tt>java.io.Writer</tt> to which the escaped result will be written. Nothing will be written at all to this writer if input is <tt>null</tt>. @throws IOException if an input/output exception occurs @since 1.1.5
[ "<p", ">", "Perform", "an", "XML", "1", ".", "1", "level", "2", "(", "markup", "-", "significant", "and", "all", "non", "-", "ASCII", "chars", ")", "<strong", ">", "escape<", "/", "strong", ">", "operation", "on", "a", "<tt", ">", "Reader<", "/", "...
train
https://github.com/unbescape/unbescape/blob/ec5435fb3508c2eed25d8165dc27ded2602cae13/src/main/java/org/unbescape/xml/XmlEscape.java#L1554-L1559
validator/validator
src/nu/validator/gnu/xml/aelfred2/XmlParser.java
XmlParser.tryEncodingDecl
private String tryEncodingDecl(String encoding) throws SAXException, IOException { // Read the XML/text declaration. if (tryRead("<?xml")) { if (tryWhitespace()) { if (inputStack.size() > 0) { return parseTextDecl(encoding); } else { return parseXMLDecl(encoding); } } else { // <?xml-stylesheet ...?> or similar pushString(null, "<?xml"); // unread('l'); // unread('m'); // unread('x'); // unread('?'); // unread('<'); } } // 2006-02-03 hsivonen warnAboutLackOfEncodingDecl(encoding); return null; }
java
private String tryEncodingDecl(String encoding) throws SAXException, IOException { // Read the XML/text declaration. if (tryRead("<?xml")) { if (tryWhitespace()) { if (inputStack.size() > 0) { return parseTextDecl(encoding); } else { return parseXMLDecl(encoding); } } else { // <?xml-stylesheet ...?> or similar pushString(null, "<?xml"); // unread('l'); // unread('m'); // unread('x'); // unread('?'); // unread('<'); } } // 2006-02-03 hsivonen warnAboutLackOfEncodingDecl(encoding); return null; }
[ "private", "String", "tryEncodingDecl", "(", "String", "encoding", ")", "throws", "SAXException", ",", "IOException", "{", "// Read the XML/text declaration.", "if", "(", "tryRead", "(", "\"<?xml\"", ")", ")", "{", "if", "(", "tryWhitespace", "(", ")", ")", "{",...
Check for an encoding declaration. This is the second part of the XML encoding autodetection algorithm, relying on detectEncoding to get to the point that this part can read any encoding declaration in the document (using only US-ASCII characters). <p> Because this part starts to fill parser buffers with this data, it's tricky to setup a reader so that Java's built-in decoders can be used for the character encodings that aren't built in to this parser (such as EUC-JP, KOI8-R, Big5, etc). @return any encoding in the declaration, uppercased; or null @see detectEncoding
[ "Check", "for", "an", "encoding", "declaration", ".", "This", "is", "the", "second", "part", "of", "the", "XML", "encoding", "autodetection", "algorithm", "relying", "on", "detectEncoding", "to", "get", "to", "the", "point", "that", "this", "part", "can", "r...
train
https://github.com/validator/validator/blob/c7b7f85b3a364df7d9944753fb5b2cd0ce642889/src/nu/validator/gnu/xml/aelfred2/XmlParser.java#L3902-L3925
threerings/narya
core/src/main/java/com/threerings/presents/data/ClientObject.java
ClientObject.checkAccess
public String checkAccess (Permission perm, Object context) { if (_permPolicy == null) { _permPolicy = createPermissionPolicy(); } return _permPolicy.checkAccess(perm, context); }
java
public String checkAccess (Permission perm, Object context) { if (_permPolicy == null) { _permPolicy = createPermissionPolicy(); } return _permPolicy.checkAccess(perm, context); }
[ "public", "String", "checkAccess", "(", "Permission", "perm", ",", "Object", "context", ")", "{", "if", "(", "_permPolicy", "==", "null", ")", "{", "_permPolicy", "=", "createPermissionPolicy", "(", ")", ";", "}", "return", "_permPolicy", ".", "checkAccess", ...
Checks whether or not this client has the specified permission. @return null if the user has access, a fully-qualified translatable message string indicating the reason for denial of access. @see ClientObject.PermissionPolicy
[ "Checks", "whether", "or", "not", "this", "client", "has", "the", "specified", "permission", "." ]
train
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/data/ClientObject.java#L73-L79
opensourceBIM/BIMserver
PluginBase/src/org/bimserver/shared/GuidCompressor.java
GuidCompressor.cv_to_64
private static boolean cv_to_64(long number, char[] code, int len ) { long act; int iDigit, nDigits; char[] result = new char[5]; if (len > 5) return false; act = number; nDigits = len - 1; for (iDigit = 0; iDigit < nDigits; iDigit++) { result[nDigits - iDigit - 1] = cConversionTable[(int) (act % 64)]; act /= 64; } result[len - 1] = '\0'; if (act != 0) return false; for(int i = 0; i<result.length; i++) code[i] = result[i]; return true; }
java
private static boolean cv_to_64(long number, char[] code, int len ) { long act; int iDigit, nDigits; char[] result = new char[5]; if (len > 5) return false; act = number; nDigits = len - 1; for (iDigit = 0; iDigit < nDigits; iDigit++) { result[nDigits - iDigit - 1] = cConversionTable[(int) (act % 64)]; act /= 64; } result[len - 1] = '\0'; if (act != 0) return false; for(int i = 0; i<result.length; i++) code[i] = result[i]; return true; }
[ "private", "static", "boolean", "cv_to_64", "(", "long", "number", ",", "char", "[", "]", "code", ",", "int", "len", ")", "{", "long", "act", ";", "int", "iDigit", ",", "nDigits", ";", "char", "[", "]", "result", "=", "new", "char", "[", "5", "]", ...
Conversion of an integer into a number with base 64 using the table cConversionTable @param number @param code @param len @return true if no error occurred
[ "Conversion", "of", "an", "integer", "into", "a", "number", "with", "base", "64", "using", "the", "table", "cConversionTable" ]
train
https://github.com/opensourceBIM/BIMserver/blob/116803c3047d1b32217366757cee1bb3880fda63/PluginBase/src/org/bimserver/shared/GuidCompressor.java#L139-L164
unbescape/unbescape
src/main/java/org/unbescape/html/HtmlEscape.java
HtmlEscape.escapeHtml5
public static void escapeHtml5(final Reader reader, final Writer writer) throws IOException { escapeHtml(reader, writer, HtmlEscapeType.HTML5_NAMED_REFERENCES_DEFAULT_TO_DECIMAL, HtmlEscapeLevel.LEVEL_2_ALL_NON_ASCII_PLUS_MARKUP_SIGNIFICANT); }
java
public static void escapeHtml5(final Reader reader, final Writer writer) throws IOException { escapeHtml(reader, writer, HtmlEscapeType.HTML5_NAMED_REFERENCES_DEFAULT_TO_DECIMAL, HtmlEscapeLevel.LEVEL_2_ALL_NON_ASCII_PLUS_MARKUP_SIGNIFICANT); }
[ "public", "static", "void", "escapeHtml5", "(", "final", "Reader", "reader", ",", "final", "Writer", "writer", ")", "throws", "IOException", "{", "escapeHtml", "(", "reader", ",", "writer", ",", "HtmlEscapeType", ".", "HTML5_NAMED_REFERENCES_DEFAULT_TO_DECIMAL", ","...
<p> Perform an HTML5 level 2 (result is ASCII) <strong>escape</strong> operation on a <tt>Reader</tt> input, writing results to a <tt>Writer</tt>. </p> <p> <em>Level 2</em> means this method will escape: </p> <ul> <li>The five markup-significant characters: <tt>&lt;</tt>, <tt>&gt;</tt>, <tt>&amp;</tt>, <tt>&quot;</tt> and <tt>&#39;</tt></li> <li>All non ASCII characters.</li> </ul> <p> This escape will be performed by replacing those chars by the corresponding HTML5 Named Character References (e.g. <tt>'&amp;acute;'</tt>) when such NCR exists for the replaced character, and replacing by a decimal character reference (e.g. <tt>'&amp;#8345;'</tt>) when there there is no NCR for the replaced character. </p> <p> This method calls {@link #escapeHtml(Reader, Writer, HtmlEscapeType, HtmlEscapeLevel)} with the following preconfigured values: </p> <ul> <li><tt>type</tt>: {@link org.unbescape.html.HtmlEscapeType#HTML5_NAMED_REFERENCES_DEFAULT_TO_DECIMAL}</li> <li><tt>level</tt>: {@link org.unbescape.html.HtmlEscapeLevel#LEVEL_2_ALL_NON_ASCII_PLUS_MARKUP_SIGNIFICANT}</li> </ul> <p> This method is <strong>thread-safe</strong>. </p> @param reader the <tt>Reader</tt> reading the text to be escaped. @param writer the <tt>java.io.Writer</tt> to which the escaped result will be written. Nothing will be written at all to this writer if input is <tt>null</tt>. @throws IOException if an input/output exception occurs @since 1.1.2
[ "<p", ">", "Perform", "an", "HTML5", "level", "2", "(", "result", "is", "ASCII", ")", "<strong", ">", "escape<", "/", "strong", ">", "operation", "on", "a", "<tt", ">", "Reader<", "/", "tt", ">", "input", "writing", "results", "to", "a", "<tt", ">", ...
train
https://github.com/unbescape/unbescape/blob/ec5435fb3508c2eed25d8165dc27ded2602cae13/src/main/java/org/unbescape/html/HtmlEscape.java#L637-L641
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/MessagePattern.java
MessagePattern.validateArgumentName
public static int validateArgumentName(String name) { if(!PatternProps.isIdentifier(name)) { return ARG_NAME_NOT_VALID; } return parseArgNumber(name, 0, name.length()); }
java
public static int validateArgumentName(String name) { if(!PatternProps.isIdentifier(name)) { return ARG_NAME_NOT_VALID; } return parseArgNumber(name, 0, name.length()); }
[ "public", "static", "int", "validateArgumentName", "(", "String", "name", ")", "{", "if", "(", "!", "PatternProps", ".", "isIdentifier", "(", "name", ")", ")", "{", "return", "ARG_NAME_NOT_VALID", ";", "}", "return", "parseArgNumber", "(", "name", ",", "0", ...
Validates and parses an argument name or argument number string. An argument name must be a "pattern identifier", that is, it must contain no Unicode Pattern_Syntax or Pattern_White_Space characters. If it only contains ASCII digits, then it must be a small integer with no leading zero. @param name Input string. @return &gt;=0 if the name is a valid number, ARG_NAME_NOT_NUMBER (-1) if it is a "pattern identifier" but not all ASCII digits, ARG_NAME_NOT_VALID (-2) if it is neither.
[ "Validates", "and", "parses", "an", "argument", "name", "or", "argument", "number", "string", ".", "An", "argument", "name", "must", "be", "a", "pattern", "identifier", "that", "is", "it", "must", "contain", "no", "Unicode", "Pattern_Syntax", "or", "Pattern_Wh...
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/MessagePattern.java#L345-L350
GerdHolz/TOVAL
src/de/invation/code/toval/os/WindowsRegistry.java
WindowsRegistry.deleteValue
public static void deleteValue(String keyName, String valueName) throws RegistryException { try (Key key = Key.open(keyName, KEY_WRITE)) { checkError(invoke(Methods.REG_DELETE_VALUE.get(), key.id, toByteArray(valueName))); } }
java
public static void deleteValue(String keyName, String valueName) throws RegistryException { try (Key key = Key.open(keyName, KEY_WRITE)) { checkError(invoke(Methods.REG_DELETE_VALUE.get(), key.id, toByteArray(valueName))); } }
[ "public", "static", "void", "deleteValue", "(", "String", "keyName", ",", "String", "valueName", ")", "throws", "RegistryException", "{", "try", "(", "Key", "key", "=", "Key", ".", "open", "(", "keyName", ",", "KEY_WRITE", ")", ")", "{", "checkError", "(",...
Deletes a value within a key. @param keyName Name of the key, which contains the value to delete. @param valueName Name of the value to delete. @throws RegistryException
[ "Deletes", "a", "value", "within", "a", "key", "." ]
train
https://github.com/GerdHolz/TOVAL/blob/036922cdfd710fa53b18e5dbe1e07f226f731fde/src/de/invation/code/toval/os/WindowsRegistry.java#L126-L130
strator-dev/greenpepper
greenpepper/core/src/main/java/com/greenpepper/util/CollectionUtil.java
CollectionUtil.joinAsString
public static String joinAsString( Object[] objects, String separator ) { StringBuilder result = new StringBuilder(); for (int i = 0; i < objects.length; i++) { Object element = objects[i]; result.append( String.valueOf( element ) ); if (i < objects.length - 1) result.append( separator ); } return result.toString(); }
java
public static String joinAsString( Object[] objects, String separator ) { StringBuilder result = new StringBuilder(); for (int i = 0; i < objects.length; i++) { Object element = objects[i]; result.append( String.valueOf( element ) ); if (i < objects.length - 1) result.append( separator ); } return result.toString(); }
[ "public", "static", "String", "joinAsString", "(", "Object", "[", "]", "objects", ",", "String", "separator", ")", "{", "StringBuilder", "result", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "objects", "...
<p>joinAsString.</p> @param objects an array of {@link java.lang.Object} objects. @param separator a {@link java.lang.String} object. @return a {@link java.lang.String} object.
[ "<p", ">", "joinAsString", ".", "<", "/", "p", ">" ]
train
https://github.com/strator-dev/greenpepper/blob/2a61e6c179b74085babcc559d677490b0cad2d30/greenpepper/core/src/main/java/com/greenpepper/util/CollectionUtil.java#L150-L160
threerings/nenya
core/src/main/java/com/threerings/media/tile/TrimmedTileSet.java
TrimmedTileSet.trimTileSet
public static TrimmedTileSet trimTileSet (TileSet source, OutputStream destImage, String imgFormat) throws IOException { final TrimmedTileSet tset = new TrimmedTileSet(); tset.setName(source.getName()); int tcount = source.getTileCount(); tset._tbounds = new Rectangle[tcount]; tset._obounds = new Rectangle[tcount]; // grab the dimensions of the original tiles for (int ii = 0; ii < tcount; ii++) { tset._tbounds[ii] = source.computeTileBounds(ii, new Rectangle()); } // create the trimmed tileset image TileSetTrimmer.TrimMetricsReceiver tmr = new TileSetTrimmer.TrimMetricsReceiver() { public void trimmedTile (int tileIndex, int imageX, int imageY, int trimX, int trimY, int trimWidth, int trimHeight) { tset._tbounds[tileIndex].x = trimX; tset._tbounds[tileIndex].y = trimY; tset._obounds[tileIndex] = new Rectangle(imageX, imageY, trimWidth, trimHeight); } }; TileSetTrimmer.trimTileSet(source, destImage, tmr, imgFormat); return tset; }
java
public static TrimmedTileSet trimTileSet (TileSet source, OutputStream destImage, String imgFormat) throws IOException { final TrimmedTileSet tset = new TrimmedTileSet(); tset.setName(source.getName()); int tcount = source.getTileCount(); tset._tbounds = new Rectangle[tcount]; tset._obounds = new Rectangle[tcount]; // grab the dimensions of the original tiles for (int ii = 0; ii < tcount; ii++) { tset._tbounds[ii] = source.computeTileBounds(ii, new Rectangle()); } // create the trimmed tileset image TileSetTrimmer.TrimMetricsReceiver tmr = new TileSetTrimmer.TrimMetricsReceiver() { public void trimmedTile (int tileIndex, int imageX, int imageY, int trimX, int trimY, int trimWidth, int trimHeight) { tset._tbounds[tileIndex].x = trimX; tset._tbounds[tileIndex].y = trimY; tset._obounds[tileIndex] = new Rectangle(imageX, imageY, trimWidth, trimHeight); } }; TileSetTrimmer.trimTileSet(source, destImage, tmr, imgFormat); return tset; }
[ "public", "static", "TrimmedTileSet", "trimTileSet", "(", "TileSet", "source", ",", "OutputStream", "destImage", ",", "String", "imgFormat", ")", "throws", "IOException", "{", "final", "TrimmedTileSet", "tset", "=", "new", "TrimmedTileSet", "(", ")", ";", "tset", ...
Creates a trimmed tileset from the supplied source tileset. The image path must be set by hand to the appropriate path based on where the image data that is written to the <code>destImage</code> parameter is actually stored on the file system. The image format indicateds how the resulting image should be saved. If null, we save using FastImageIO See {@link TileSetTrimmer#trimTileSet} for further information.
[ "Creates", "a", "trimmed", "tileset", "from", "the", "supplied", "source", "tileset", ".", "The", "image", "path", "must", "be", "set", "by", "hand", "to", "the", "appropriate", "path", "based", "on", "where", "the", "image", "data", "that", "is", "written...
train
https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/media/tile/TrimmedTileSet.java#L80-L107
RKumsher/utils
src/main/java/com/github/rkumsher/number/RandomNumberUtils.java
RandomNumberUtils.randomDoubleGreaterThan
public static double randomDoubleGreaterThan(double minExclusive) { checkArgument( minExclusive < Double.MAX_VALUE, "Cannot produce double greater than %s", Double.MAX_VALUE); return randomDouble(minExclusive + 1, Double.MAX_VALUE); }
java
public static double randomDoubleGreaterThan(double minExclusive) { checkArgument( minExclusive < Double.MAX_VALUE, "Cannot produce double greater than %s", Double.MAX_VALUE); return randomDouble(minExclusive + 1, Double.MAX_VALUE); }
[ "public", "static", "double", "randomDoubleGreaterThan", "(", "double", "minExclusive", ")", "{", "checkArgument", "(", "minExclusive", "<", "Double", ".", "MAX_VALUE", ",", "\"Cannot produce double greater than %s\"", ",", "Double", ".", "MAX_VALUE", ")", ";", "retur...
Returns a random double that is greater than the given double. @param minExclusive the value that returned double must be greater than @return the random double @throws IllegalArgumentException if minExclusive is greater than or equal to {@link Double#MAX_VALUE}
[ "Returns", "a", "random", "double", "that", "is", "greater", "than", "the", "given", "double", "." ]
train
https://github.com/RKumsher/utils/blob/fcdb190569cd0288249bf4b46fd418f8c01d1caf/src/main/java/com/github/rkumsher/number/RandomNumberUtils.java#L210-L214
kiegroup/drools
drools-compiler/src/main/java/org/drools/compiler/compiler/BuilderResultUtils.java
BuilderResultUtils.getProblemMessage
public static String getProblemMessage(Object object, String summary) { return getProblemMessage( object, summary, DEFAULT_SEPARATOR ); }
java
public static String getProblemMessage(Object object, String summary) { return getProblemMessage( object, summary, DEFAULT_SEPARATOR ); }
[ "public", "static", "String", "getProblemMessage", "(", "Object", "object", ",", "String", "summary", ")", "{", "return", "getProblemMessage", "(", "object", ",", "summary", ",", "DEFAULT_SEPARATOR", ")", ";", "}" ]
Appends compilation problems to summary message if object is an array of {@link CompilationProblem} separated with backspaces @param object object with compilation results @param summary summary message @return summary message with changes
[ "Appends", "compilation", "problems", "to", "summary", "message", "if", "object", "is", "an", "array", "of", "{", "@link", "CompilationProblem", "}", "separated", "with", "backspaces" ]
train
https://github.com/kiegroup/drools/blob/22b0275d6dbe93070b8090948502cf46eda543c4/drools-compiler/src/main/java/org/drools/compiler/compiler/BuilderResultUtils.java#L23-L25
couchbase/couchbase-java-client
src/main/java/com/couchbase/client/java/query/dsl/functions/StringFunctions.java
StringFunctions.trim
public static Expression trim(String expression, String characters) { return trim(x(expression), characters); }
java
public static Expression trim(String expression, String characters) { return trim(x(expression), characters); }
[ "public", "static", "Expression", "trim", "(", "String", "expression", ",", "String", "characters", ")", "{", "return", "trim", "(", "x", "(", "expression", ")", ",", "characters", ")", ";", "}" ]
Returned expression results in the string with all leading and trailing chars removed (any char in the characters string).
[ "Returned", "expression", "results", "in", "the", "string", "with", "all", "leading", "and", "trailing", "chars", "removed", "(", "any", "char", "in", "the", "characters", "string", ")", "." ]
train
https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/query/dsl/functions/StringFunctions.java#L325-L327
xmlet/XsdAsmFaster
src/main/java/org/xmlet/xsdasmfaster/classes/XsdAsmInterfaces.java
XsdAsmInterfaces.generateInterfaces
void generateInterfaces(Map<String, List<XsdAttribute>> createdAttributes, String apiName) { attributeGroupInterfaces.keySet().forEach(attributeGroupInterface -> generateAttributesGroupInterface(createdAttributes, attributeGroupInterface, attributeGroupInterfaces.get(attributeGroupInterface), apiName)); hierarchyInterfaces.values().forEach(hierarchyInterface -> generateHierarchyAttributeInterfaces(createdAttributes, hierarchyInterface, apiName)); }
java
void generateInterfaces(Map<String, List<XsdAttribute>> createdAttributes, String apiName) { attributeGroupInterfaces.keySet().forEach(attributeGroupInterface -> generateAttributesGroupInterface(createdAttributes, attributeGroupInterface, attributeGroupInterfaces.get(attributeGroupInterface), apiName)); hierarchyInterfaces.values().forEach(hierarchyInterface -> generateHierarchyAttributeInterfaces(createdAttributes, hierarchyInterface, apiName)); }
[ "void", "generateInterfaces", "(", "Map", "<", "String", ",", "List", "<", "XsdAttribute", ">", ">", "createdAttributes", ",", "String", "apiName", ")", "{", "attributeGroupInterfaces", ".", "keySet", "(", ")", ".", "forEach", "(", "attributeGroupInterface", "->...
Generates all the required interfaces, based on the information gathered while creating the other classes. It creates both types of interfaces: ElementGroupInterfaces - Interfaces that serve as a base to adding child elements to the current element; AttributeGroupInterfaces - Interface that serve as a base to adding attributes to the current element; @param createdAttributes Information about the attributes that are already created. @param apiName The name of the generated fluent interface.
[ "Generates", "all", "the", "required", "interfaces", "based", "on", "the", "information", "gathered", "while", "creating", "the", "other", "classes", ".", "It", "creates", "both", "types", "of", "interfaces", ":", "ElementGroupInterfaces", "-", "Interfaces", "that...
train
https://github.com/xmlet/XsdAsmFaster/blob/ccb78f9dd4b957ad5ac1ca349eaf24338c421e94/src/main/java/org/xmlet/xsdasmfaster/classes/XsdAsmInterfaces.java#L95-L98
fabiomaffioletti/jsondoc
jsondoc-springmvc/src/main/java/org/jsondoc/springmvc/scanner/builder/SpringQueryParamBuilder.java
SpringQueryParamBuilder.addRequestMappingParamDoc
private static void addRequestMappingParamDoc(Set<ApiParamDoc> apiParamDocs, RequestMapping requestMapping) { if (requestMapping.params().length > 0) { for (String param : requestMapping.params()) { String[] splitParam = param.split("="); if (splitParam.length > 1) { apiParamDocs.add(new ApiParamDoc(splitParam[0], "", JSONDocTypeBuilder.build(new JSONDocType(), String.class, null), "true", new String[] { splitParam[1] }, null, null)); } else { apiParamDocs.add(new ApiParamDoc(param, "", JSONDocTypeBuilder.build(new JSONDocType(), String.class, null), "true", new String[] {}, null, null)); } } } }
java
private static void addRequestMappingParamDoc(Set<ApiParamDoc> apiParamDocs, RequestMapping requestMapping) { if (requestMapping.params().length > 0) { for (String param : requestMapping.params()) { String[] splitParam = param.split("="); if (splitParam.length > 1) { apiParamDocs.add(new ApiParamDoc(splitParam[0], "", JSONDocTypeBuilder.build(new JSONDocType(), String.class, null), "true", new String[] { splitParam[1] }, null, null)); } else { apiParamDocs.add(new ApiParamDoc(param, "", JSONDocTypeBuilder.build(new JSONDocType(), String.class, null), "true", new String[] {}, null, null)); } } } }
[ "private", "static", "void", "addRequestMappingParamDoc", "(", "Set", "<", "ApiParamDoc", ">", "apiParamDocs", ",", "RequestMapping", "requestMapping", ")", "{", "if", "(", "requestMapping", ".", "params", "(", ")", ".", "length", ">", "0", ")", "{", "for", ...
Checks the request mapping annotation value and adds the resulting @ApiParamDoc to the documentation @param apiParamDocs @param requestMapping
[ "Checks", "the", "request", "mapping", "annotation", "value", "and", "adds", "the", "resulting" ]
train
https://github.com/fabiomaffioletti/jsondoc/blob/26bf413c236e7c3b66f534c2451b157783c1f45e/jsondoc-springmvc/src/main/java/org/jsondoc/springmvc/scanner/builder/SpringQueryParamBuilder.java#L86-L97
sirthias/parboiled
parboiled-core/src/main/java/org/parboiled/support/ParseTreeUtils.java
ParseTreeUtils.printNodeTree
public static <V> String printNodeTree(ParsingResult<V> parsingResult, Predicate<Node<V>> nodeFilter, Predicate<Node<V>> subTreeFilter) { checkArgNotNull(parsingResult, "parsingResult"); checkArgNotNull(nodeFilter, "nodeFilter"); checkArgNotNull(subTreeFilter, "subTreeFilter"); return printTree(parsingResult.parseTreeRoot, new NodeFormatter<V>(parsingResult.inputBuffer), nodeFilter, subTreeFilter); }
java
public static <V> String printNodeTree(ParsingResult<V> parsingResult, Predicate<Node<V>> nodeFilter, Predicate<Node<V>> subTreeFilter) { checkArgNotNull(parsingResult, "parsingResult"); checkArgNotNull(nodeFilter, "nodeFilter"); checkArgNotNull(subTreeFilter, "subTreeFilter"); return printTree(parsingResult.parseTreeRoot, new NodeFormatter<V>(parsingResult.inputBuffer), nodeFilter, subTreeFilter); }
[ "public", "static", "<", "V", ">", "String", "printNodeTree", "(", "ParsingResult", "<", "V", ">", "parsingResult", ",", "Predicate", "<", "Node", "<", "V", ">", ">", "nodeFilter", ",", "Predicate", "<", "Node", "<", "V", ">", ">", "subTreeFilter", ")", ...
Creates a readable string represenation of the parse tree in thee given {@link ParsingResult} object. The given filter predicate determines whether a particular node (incl. its subtree) is printed or not. @param parsingResult the parsing result containing the parse tree @param nodeFilter the predicate selecting the nodes to print @param subTreeFilter the predicate determining whether to descend into a given nodes subtree or not @return a new String
[ "Creates", "a", "readable", "string", "represenation", "of", "the", "parse", "tree", "in", "thee", "given", "{", "@link", "ParsingResult", "}", "object", ".", "The", "given", "filter", "predicate", "determines", "whether", "a", "particular", "node", "(", "incl...
train
https://github.com/sirthias/parboiled/blob/84f3ed43e3e171b4c6ab5e6ca6297d264a9d686a/parboiled-core/src/main/java/org/parboiled/support/ParseTreeUtils.java#L340-L347
google/error-prone-javac
src/jdk.compiler/share/classes/com/sun/tools/javac/code/Types.java
Types.setBounds
public void setBounds(TypeVar t, List<Type> bounds) { setBounds(t, bounds, bounds.head.tsym.isInterface()); }
java
public void setBounds(TypeVar t, List<Type> bounds) { setBounds(t, bounds, bounds.head.tsym.isInterface()); }
[ "public", "void", "setBounds", "(", "TypeVar", "t", ",", "List", "<", "Type", ">", "bounds", ")", "{", "setBounds", "(", "t", ",", "bounds", ",", "bounds", ".", "head", ".", "tsym", ".", "isInterface", "(", ")", ")", ";", "}" ]
Same as {@link Types#setBounds(TypeVar, List, boolean)}, except that third parameter is computed directly, as follows: if all all bounds are interface types, the computed supertype is Object,otherwise the supertype is simply left null (in this case, the supertype is assumed to be the head of the bound list passed as second argument). Note that this check might cause a symbol completion. Hence, this version of setBounds may not be called during a classfile read. @param t a type variable @param bounds the bounds, must be nonempty
[ "Same", "as", "{", "@link", "Types#setBounds", "(", "TypeVar", "List", "boolean", ")", "}", "except", "that", "third", "parameter", "is", "computed", "directly", "as", "follows", ":", "if", "all", "all", "bounds", "are", "interface", "types", "the", "compute...
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Types.java#L2405-L2407
nyla-solutions/nyla
nyla.solutions.core/src/main/java/nyla/solutions/core/patterns/servicefactory/ServiceFactory.java
ServiceFactory.getInstance
public synchronized static ServiceFactory getInstance(Class<?> aClass, String configurationPath) { if(configurationPath == null) { configurationPath = ""; } if (instances.get(configurationPath) == null) { instances.put(configurationPath, createServiceFactory(aClass,configurationPath)); } return (ServiceFactory)instances.get(configurationPath); }
java
public synchronized static ServiceFactory getInstance(Class<?> aClass, String configurationPath) { if(configurationPath == null) { configurationPath = ""; } if (instances.get(configurationPath) == null) { instances.put(configurationPath, createServiceFactory(aClass,configurationPath)); } return (ServiceFactory)instances.get(configurationPath); }
[ "public", "synchronized", "static", "ServiceFactory", "getInstance", "(", "Class", "<", "?", ">", "aClass", ",", "String", "configurationPath", ")", "{", "if", "(", "configurationPath", "==", "null", ")", "{", "configurationPath", "=", "\"\"", ";", "}", "if", ...
Singleton factory method @param aClass the class implements @param configurationPath the path to the configuration details @return a single instance of the ServiceFactory object for the JVM
[ "Singleton", "factory", "method" ]
train
https://github.com/nyla-solutions/nyla/blob/38d5b843c76eae9762bbca20453ed0f0ad8412a9/nyla.solutions.core/src/main/java/nyla/solutions/core/patterns/servicefactory/ServiceFactory.java#L107-L120
orbisgis/h2gis
h2gis-functions/src/main/java/org/h2gis/functions/io/shp/SHPDriverFunction.java
SHPDriverFunction.exportTable
@Override public void exportTable(Connection connection, String tableReference, File fileName, ProgressVisitor progress, String encoding) throws SQLException, IOException { final boolean isH2 = JDBCUtilities.isH2DataBase(connection.getMetaData()); String regex = ".*(?i)\\b(select|from)\\b.*"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(tableReference); if (matcher.find()) { if (tableReference.startsWith("(") && tableReference.endsWith(")")) { if (FileUtil.isExtensionWellFormated(fileName, "shp")) { PreparedStatement ps = connection.prepareStatement(tableReference, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet resultSet = ps.executeQuery(); int recordCount = 0; resultSet.last(); recordCount = resultSet.getRow(); resultSet.beforeFirst(); ProgressVisitor copyProgress = progress.subProcess(recordCount); List<String> spatialFieldNames = SFSUtilities.getGeometryFields(resultSet); int srid = doExport(tableReference, spatialFieldNames, resultSet, recordCount, fileName, progress, encoding); String path = fileName.getAbsolutePath(); String nameWithoutExt = path.substring(0, path.lastIndexOf('.')); PRJUtil.writePRJ(connection, srid, new File(nameWithoutExt + ".prj")); copyProgress.endOfProgress(); } else { throw new SQLException("Only .shp extension is supported"); } } else { throw new SQLException("The select query must be enclosed in parenthesis: '(SELECT * FROM ORDERS)'."); } } else { if (FileUtil.isExtensionWellFormated(fileName, "shp")) { TableLocation location = TableLocation.parse(tableReference, isH2); int recordCount = JDBCUtilities.getRowCount(connection, tableReference); ProgressVisitor copyProgress = progress.subProcess(recordCount); // Read Geometry Index and type List<String> spatialFieldNames = SFSUtilities.getGeometryFields(connection, TableLocation.parse(tableReference, isH2)); Statement st = connection.createStatement(); ResultSet rs = st.executeQuery(String.format("select * from %s", location.toString())); doExport(tableReference, spatialFieldNames, rs, recordCount, fileName, copyProgress, encoding); String path = fileName.getAbsolutePath(); String nameWithoutExt = path.substring(0, path.lastIndexOf('.')); PRJUtil.writePRJ(connection, location, spatialFieldNames.get(0), new File(nameWithoutExt + ".prj")); copyProgress.endOfProgress(); } else { throw new SQLException("Only .shp extension is supported"); } } }
java
@Override public void exportTable(Connection connection, String tableReference, File fileName, ProgressVisitor progress, String encoding) throws SQLException, IOException { final boolean isH2 = JDBCUtilities.isH2DataBase(connection.getMetaData()); String regex = ".*(?i)\\b(select|from)\\b.*"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(tableReference); if (matcher.find()) { if (tableReference.startsWith("(") && tableReference.endsWith(")")) { if (FileUtil.isExtensionWellFormated(fileName, "shp")) { PreparedStatement ps = connection.prepareStatement(tableReference, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet resultSet = ps.executeQuery(); int recordCount = 0; resultSet.last(); recordCount = resultSet.getRow(); resultSet.beforeFirst(); ProgressVisitor copyProgress = progress.subProcess(recordCount); List<String> spatialFieldNames = SFSUtilities.getGeometryFields(resultSet); int srid = doExport(tableReference, spatialFieldNames, resultSet, recordCount, fileName, progress, encoding); String path = fileName.getAbsolutePath(); String nameWithoutExt = path.substring(0, path.lastIndexOf('.')); PRJUtil.writePRJ(connection, srid, new File(nameWithoutExt + ".prj")); copyProgress.endOfProgress(); } else { throw new SQLException("Only .shp extension is supported"); } } else { throw new SQLException("The select query must be enclosed in parenthesis: '(SELECT * FROM ORDERS)'."); } } else { if (FileUtil.isExtensionWellFormated(fileName, "shp")) { TableLocation location = TableLocation.parse(tableReference, isH2); int recordCount = JDBCUtilities.getRowCount(connection, tableReference); ProgressVisitor copyProgress = progress.subProcess(recordCount); // Read Geometry Index and type List<String> spatialFieldNames = SFSUtilities.getGeometryFields(connection, TableLocation.parse(tableReference, isH2)); Statement st = connection.createStatement(); ResultSet rs = st.executeQuery(String.format("select * from %s", location.toString())); doExport(tableReference, spatialFieldNames, rs, recordCount, fileName, copyProgress, encoding); String path = fileName.getAbsolutePath(); String nameWithoutExt = path.substring(0, path.lastIndexOf('.')); PRJUtil.writePRJ(connection, location, spatialFieldNames.get(0), new File(nameWithoutExt + ".prj")); copyProgress.endOfProgress(); } else { throw new SQLException("Only .shp extension is supported"); } } }
[ "@", "Override", "public", "void", "exportTable", "(", "Connection", "connection", ",", "String", "tableReference", ",", "File", "fileName", ",", "ProgressVisitor", "progress", ",", "String", "encoding", ")", "throws", "SQLException", ",", "IOException", "{", "fin...
Save a table or a query to a shpfile @param connection Active connection, do not close this connection. @param tableReference [[catalog.]schema.]table reference @param fileName File path to write, if exists it may be replaced @param progress to display the IO progress @param encoding File encoding, null will use default encoding @throws SQLException @throws IOException
[ "Save", "a", "table", "or", "a", "query", "to", "a", "shpfile" ]
train
https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/io/shp/SHPDriverFunction.java#L75-L122
JOML-CI/JOML
src/org/joml/Matrix3x2f.java
Matrix3x2f.rotateTo
public Matrix3x2f rotateTo(Vector2fc fromDir, Vector2fc toDir, Matrix3x2f dest) { float dot = fromDir.x() * toDir.x() + fromDir.y() * toDir.y(); float det = fromDir.x() * toDir.y() - fromDir.y() * toDir.x(); float rm00 = dot; float rm01 = det; float rm10 = -det; float rm11 = dot; float nm00 = m00 * rm00 + m10 * rm01; float nm01 = m01 * rm00 + m11 * rm01; dest.m10 = m00 * rm10 + m10 * rm11; dest.m11 = m01 * rm10 + m11 * rm11; dest.m00 = nm00; dest.m01 = nm01; dest.m20 = m20; dest.m21 = m21; return dest; }
java
public Matrix3x2f rotateTo(Vector2fc fromDir, Vector2fc toDir, Matrix3x2f dest) { float dot = fromDir.x() * toDir.x() + fromDir.y() * toDir.y(); float det = fromDir.x() * toDir.y() - fromDir.y() * toDir.x(); float rm00 = dot; float rm01 = det; float rm10 = -det; float rm11 = dot; float nm00 = m00 * rm00 + m10 * rm01; float nm01 = m01 * rm00 + m11 * rm01; dest.m10 = m00 * rm10 + m10 * rm11; dest.m11 = m01 * rm10 + m11 * rm11; dest.m00 = nm00; dest.m01 = nm01; dest.m20 = m20; dest.m21 = m21; return dest; }
[ "public", "Matrix3x2f", "rotateTo", "(", "Vector2fc", "fromDir", ",", "Vector2fc", "toDir", ",", "Matrix3x2f", "dest", ")", "{", "float", "dot", "=", "fromDir", ".", "x", "(", ")", "*", "toDir", ".", "x", "(", ")", "+", "fromDir", ".", "y", "(", ")",...
Apply a rotation transformation to this matrix that rotates the given normalized <code>fromDir</code> direction vector to point along the normalized <code>toDir</code>, and store the result in <code>dest</code>. <p> If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, then the new matrix will be <code>M * R</code>. So when transforming a vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the rotation will be applied first! @param fromDir the normalized direction which should be rotate to point along <code>toDir</code> @param toDir the normalized destination direction @param dest will hold the result @return dest
[ "Apply", "a", "rotation", "transformation", "to", "this", "matrix", "that", "rotates", "the", "given", "normalized", "<code", ">", "fromDir<", "/", "code", ">", "direction", "vector", "to", "point", "along", "the", "normalized", "<code", ">", "toDir<", "/", ...
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix3x2f.java#L2014-L2030
alkacon/opencms-core
src/org/opencms/workplace/editors/CmsEditor.java
CmsEditor.showErrorPage
protected void showErrorPage(Object editor, Exception exception) throws JspException { // save initialized instance of the editor class in request attribute for included sub-elements getJsp().getRequest().setAttribute(SESSION_WORKPLACE_CLASS, editor); // reading of file contents failed, show error dialog setAction(ACTION_SHOW_ERRORMESSAGE); setParamTitle(key(Messages.GUI_TITLE_EDIT_1, new Object[] {CmsResource.getName(getParamResource())})); if (exception != null) { getJsp().getRequest().setAttribute(ATTRIBUTE_THROWABLE, exception); if (CmsLog.getLog(editor).isWarnEnabled()) { CmsLog.getLog(editor).warn(exception.getLocalizedMessage(), exception); } } // include the common error dialog getJsp().include(FILE_DIALOG_SCREEN_ERRORPAGE); }
java
protected void showErrorPage(Object editor, Exception exception) throws JspException { // save initialized instance of the editor class in request attribute for included sub-elements getJsp().getRequest().setAttribute(SESSION_WORKPLACE_CLASS, editor); // reading of file contents failed, show error dialog setAction(ACTION_SHOW_ERRORMESSAGE); setParamTitle(key(Messages.GUI_TITLE_EDIT_1, new Object[] {CmsResource.getName(getParamResource())})); if (exception != null) { getJsp().getRequest().setAttribute(ATTRIBUTE_THROWABLE, exception); if (CmsLog.getLog(editor).isWarnEnabled()) { CmsLog.getLog(editor).warn(exception.getLocalizedMessage(), exception); } } // include the common error dialog getJsp().include(FILE_DIALOG_SCREEN_ERRORPAGE); }
[ "protected", "void", "showErrorPage", "(", "Object", "editor", ",", "Exception", "exception", ")", "throws", "JspException", "{", "// save initialized instance of the editor class in request attribute for included sub-elements", "getJsp", "(", ")", ".", "getRequest", "(", ")"...
Shows the selected error page in case of an exception.<p> @param editor initialized instance of the editor class @param exception the current exception @throws JspException if inclusion of the error page fails
[ "Shows", "the", "selected", "error", "page", "in", "case", "of", "an", "exception", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/workplace/editors/CmsEditor.java#L1078-L1094
motown-io/motown
ocpp/websocket-json/src/main/java/io/motown/ocpp/websocketjson/response/handler/ChangeAvailabilityResponseHandler.java
ChangeAvailabilityResponseHandler.handleAcceptedOrScheduledChangeAvailabilityResponse
private void handleAcceptedOrScheduledChangeAvailabilityResponse(ChargingStationId chargingStationId, DomainService domainService, AddOnIdentity addOnIdentity) { if (Changeavailability.Type.INOPERATIVE.equals(availabilityType)) { if (evseId.getNumberedId() == 0) { domainService.changeChargingStationAvailabilityToInoperative(chargingStationId, getCorrelationToken(), addOnIdentity); } else { domainService.changeComponentAvailabilityToInoperative(chargingStationId, evseId, ChargingStationComponent.EVSE, getCorrelationToken(), addOnIdentity); } } else { if (evseId.getNumberedId() == 0) { domainService.changeChargingStationAvailabilityToOperative(chargingStationId, getCorrelationToken(), addOnIdentity); } else { domainService.changeComponentAvailabilityToOperative(chargingStationId, evseId, ChargingStationComponent.EVSE, getCorrelationToken(), addOnIdentity); } } }
java
private void handleAcceptedOrScheduledChangeAvailabilityResponse(ChargingStationId chargingStationId, DomainService domainService, AddOnIdentity addOnIdentity) { if (Changeavailability.Type.INOPERATIVE.equals(availabilityType)) { if (evseId.getNumberedId() == 0) { domainService.changeChargingStationAvailabilityToInoperative(chargingStationId, getCorrelationToken(), addOnIdentity); } else { domainService.changeComponentAvailabilityToInoperative(chargingStationId, evseId, ChargingStationComponent.EVSE, getCorrelationToken(), addOnIdentity); } } else { if (evseId.getNumberedId() == 0) { domainService.changeChargingStationAvailabilityToOperative(chargingStationId, getCorrelationToken(), addOnIdentity); } else { domainService.changeComponentAvailabilityToOperative(chargingStationId, evseId, ChargingStationComponent.EVSE, getCorrelationToken(), addOnIdentity); } } }
[ "private", "void", "handleAcceptedOrScheduledChangeAvailabilityResponse", "(", "ChargingStationId", "chargingStationId", ",", "DomainService", "domainService", ",", "AddOnIdentity", "addOnIdentity", ")", "{", "if", "(", "Changeavailability", ".", "Type", ".", "INOPERATIVE", ...
Handles the response when the change of availability has been accepted or scheduled, e.g. not rejected. @param chargingStationId The charging station identifier. @param domainService The domain service. @param addOnIdentity The AddOn identity.
[ "Handles", "the", "response", "when", "the", "change", "of", "availability", "has", "been", "accepted", "or", "scheduled", "e", ".", "g", ".", "not", "rejected", "." ]
train
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/ocpp/websocket-json/src/main/java/io/motown/ocpp/websocketjson/response/handler/ChangeAvailabilityResponseHandler.java#L70-L84
marklogic/java-client-api
marklogic-client-api/src/main/java/com/marklogic/client/DatabaseClientFactory.java
DatabaseClientFactory.newClient
@Deprecated static public DatabaseClient newClient(String host, int port, String user, String password, Authentication type) { return newClient(host, port, null, makeSecurityContext(user, password, type, null, null), null); }
java
@Deprecated static public DatabaseClient newClient(String host, int port, String user, String password, Authentication type) { return newClient(host, port, null, makeSecurityContext(user, password, type, null, null), null); }
[ "@", "Deprecated", "static", "public", "DatabaseClient", "newClient", "(", "String", "host", ",", "int", "port", ",", "String", "user", ",", "String", "password", ",", "Authentication", "type", ")", "{", "return", "newClient", "(", "host", ",", "port", ",", ...
Creates a client to access the database by means of a REST server. @param host the host with the REST server @param port the port for the REST server @param user the user with read, write, or administrative privileges @param password the password for the user @param type the type of authentication applied to the request @return a new client for making database requests @deprecated (as of 4.0.1) use {@link #newClient(String host, int port, SecurityContext securityContext)}
[ "Creates", "a", "client", "to", "access", "the", "database", "by", "means", "of", "a", "REST", "server", "." ]
train
https://github.com/marklogic/java-client-api/blob/acf60229a928abd4a8cc4b21b641d56957467da7/marklogic-client-api/src/main/java/com/marklogic/client/DatabaseClientFactory.java#L1268-L1271
facebookarchive/hadoop-20
src/contrib/eclipse-plugin/src/java/org/apache/hadoop/eclipse/dfs/DFSFolder.java
DFSFolder.mkdir
public void mkdir(String folderName) { try { getDFS().mkdirs(new Path(this.path, folderName)); } catch (IOException ioe) { ioe.printStackTrace(); } doRefresh(); }
java
public void mkdir(String folderName) { try { getDFS().mkdirs(new Path(this.path, folderName)); } catch (IOException ioe) { ioe.printStackTrace(); } doRefresh(); }
[ "public", "void", "mkdir", "(", "String", "folderName", ")", "{", "try", "{", "getDFS", "(", ")", ".", "mkdirs", "(", "new", "Path", "(", "this", ".", "path", ",", "folderName", ")", ")", ";", "}", "catch", "(", "IOException", "ioe", ")", "{", "ioe...
Create a new sub directory into this directory @param folderName
[ "Create", "a", "new", "sub", "directory", "into", "this", "directory" ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/eclipse-plugin/src/java/org/apache/hadoop/eclipse/dfs/DFSFolder.java#L150-L157
lecousin/java-framework-core
net.lecousin.core/src/main/java/net/lecousin/framework/xml/dom/DOMUtil.java
DOMUtil.getChildText
public static String getChildText(Element parent, String childName) { Element child = getChild(parent, childName); if (child == null) return null; return getInnerText(child); }
java
public static String getChildText(Element parent, String childName) { Element child = getChild(parent, childName); if (child == null) return null; return getInnerText(child); }
[ "public", "static", "String", "getChildText", "(", "Element", "parent", ",", "String", "childName", ")", "{", "Element", "child", "=", "getChild", "(", "parent", ",", "childName", ")", ";", "if", "(", "child", "==", "null", ")", "return", "null", ";", "r...
Return the inner text of the first child with the given name.
[ "Return", "the", "inner", "text", "of", "the", "first", "child", "with", "the", "given", "name", "." ]
train
https://github.com/lecousin/java-framework-core/blob/b0c893b44bfde2c03f90ea846a49ef5749d598f3/net.lecousin.core/src/main/java/net/lecousin/framework/xml/dom/DOMUtil.java#L52-L56
baratine/baratine
framework/src/main/java/com/caucho/v5/ramp/jamp/InJamp.java
InJamp.readMessages
public int readMessages(Reader is, OutboxAmp outbox) throws IOException { Objects.requireNonNull(outbox); JsonReaderImpl jIn = new JsonReaderImpl(is, _jsonFactory); return readMessages(jIn, outbox); }
java
public int readMessages(Reader is, OutboxAmp outbox) throws IOException { Objects.requireNonNull(outbox); JsonReaderImpl jIn = new JsonReaderImpl(is, _jsonFactory); return readMessages(jIn, outbox); }
[ "public", "int", "readMessages", "(", "Reader", "is", ",", "OutboxAmp", "outbox", ")", "throws", "IOException", "{", "Objects", ".", "requireNonNull", "(", "outbox", ")", ";", "JsonReaderImpl", "jIn", "=", "new", "JsonReaderImpl", "(", "is", ",", "_jsonFactory...
Reads the next HMTP packet from the stream, returning false on end of file.
[ "Reads", "the", "next", "HMTP", "packet", "from", "the", "stream", "returning", "false", "on", "end", "of", "file", "." ]
train
https://github.com/baratine/baratine/blob/db34b45c03c5a5e930d8142acc72319125569fcf/framework/src/main/java/com/caucho/v5/ramp/jamp/InJamp.java#L216-L224
alkacon/opencms-core
src/org/opencms/jsp/CmsJspNavBuilder.java
CmsJspNavBuilder.getNavigationForFolder
public List<CmsJspNavElement> getNavigationForFolder(String folder) { return getNavigationForFolder(folder, Visibility.navigation, CmsResourceFilter.DEFAULT); }
java
public List<CmsJspNavElement> getNavigationForFolder(String folder) { return getNavigationForFolder(folder, Visibility.navigation, CmsResourceFilter.DEFAULT); }
[ "public", "List", "<", "CmsJspNavElement", ">", "getNavigationForFolder", "(", "String", "folder", ")", "{", "return", "getNavigationForFolder", "(", "folder", ",", "Visibility", ".", "navigation", ",", "CmsResourceFilter", ".", "DEFAULT", ")", ";", "}" ]
Collect all navigation visible elements from the files in the given folder.<p> @param folder the selected folder @return A sorted (ascending to navigation position) list of navigation elements
[ "Collect", "all", "navigation", "visible", "elements", "from", "the", "files", "in", "the", "given", "folder", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/jsp/CmsJspNavBuilder.java#L494-L497
Microsoft/azure-maven-plugins
azure-maven-plugin-lib/src/main/java/com/microsoft/azure/maven/Utils.java
Utils.getServer
public static Server getServer(final Settings settings, final String serverId) { if (settings == null || StringUtils.isEmpty(serverId)) { return null; } return settings.getServer(serverId); }
java
public static Server getServer(final Settings settings, final String serverId) { if (settings == null || StringUtils.isEmpty(serverId)) { return null; } return settings.getServer(serverId); }
[ "public", "static", "Server", "getServer", "(", "final", "Settings", "settings", ",", "final", "String", "serverId", ")", "{", "if", "(", "settings", "==", "null", "||", "StringUtils", ".", "isEmpty", "(", "serverId", ")", ")", "{", "return", "null", ";", ...
Get server credential from Maven settings by server Id. @param settings Maven settings object. @param serverId Server Id. @return Server object if it exists in settings. Otherwise return null.
[ "Get", "server", "credential", "from", "Maven", "settings", "by", "server", "Id", "." ]
train
https://github.com/Microsoft/azure-maven-plugins/blob/a254902e820185df1823b1d692c7c1d119490b1e/azure-maven-plugin-lib/src/main/java/com/microsoft/azure/maven/Utils.java#L39-L44
apache/flink
flink-core/src/main/java/org/apache/flink/api/common/ExecutionConfig.java
ExecutionConfig.addDefaultKryoSerializer
public void addDefaultKryoSerializer(Class<?> type, Class<? extends Serializer<?>> serializerClass) { if (type == null || serializerClass == null) { throw new NullPointerException("Cannot register null class or serializer."); } defaultKryoSerializerClasses.put(type, serializerClass); }
java
public void addDefaultKryoSerializer(Class<?> type, Class<? extends Serializer<?>> serializerClass) { if (type == null || serializerClass == null) { throw new NullPointerException("Cannot register null class or serializer."); } defaultKryoSerializerClasses.put(type, serializerClass); }
[ "public", "void", "addDefaultKryoSerializer", "(", "Class", "<", "?", ">", "type", ",", "Class", "<", "?", "extends", "Serializer", "<", "?", ">", ">", "serializerClass", ")", "{", "if", "(", "type", "==", "null", "||", "serializerClass", "==", "null", "...
Adds a new Kryo default serializer to the Runtime. @param type The class of the types serialized with the given serializer. @param serializerClass The class of the serializer to use.
[ "Adds", "a", "new", "Kryo", "default", "serializer", "to", "the", "Runtime", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/api/common/ExecutionConfig.java#L782-L787
ggrandes/kvstore
src/main/java/org/javastack/kvstore/structures/btree/BplusTree.java
BplusTree.floorEntry
public synchronized TreeEntry<K, V> floorEntry(final K key) { // Retorna la clave mas cercana menor o igual a la clave indicada return getRoundEntry(key, false, true); }
java
public synchronized TreeEntry<K, V> floorEntry(final K key) { // Retorna la clave mas cercana menor o igual a la clave indicada return getRoundEntry(key, false, true); }
[ "public", "synchronized", "TreeEntry", "<", "K", ",", "V", ">", "floorEntry", "(", "final", "K", "key", ")", "{", "// Retorna la clave mas cercana menor o igual a la clave indicada", "return", "getRoundEntry", "(", "key", ",", "false", ",", "true", ")", ";", "}" ]
Returns the greatest key less than or equal to the given key, or null if there is no such key. @param key the key @return the Entry with greatest key less than or equal to key, or null if there is no such key
[ "Returns", "the", "greatest", "key", "less", "than", "or", "equal", "to", "the", "given", "key", "or", "null", "if", "there", "is", "no", "such", "key", "." ]
train
https://github.com/ggrandes/kvstore/blob/c79277f79f4604e0fec8349a98519838e3de38f0/src/main/java/org/javastack/kvstore/structures/btree/BplusTree.java#L660-L663
belaban/JGroups
src/org/jgroups/stack/Configurator.java
Configurator.setupProtocolStack
public static Protocol setupProtocolStack(List<ProtocolConfiguration> protocol_configs, ProtocolStack st) throws Exception { List<Protocol> protocols=createProtocols(protocol_configs, st); if(protocols == null) return null; // check InetAddress related features of stack Map<String, Map<String,InetAddressInfo>> inetAddressMap = createInetAddressMap(protocol_configs, protocols) ; Collection<InetAddress> addrs=getAddresses(inetAddressMap); StackType ip_version=Util.getIpStackType(); if(!addrs.isEmpty()) { // check that all user-supplied InetAddresses have a consistent version: // 1. If an addr is IPv6 and we have an IPv4 stack *only* --> FAIL for(InetAddress addr: addrs) { if(addr instanceof Inet6Address && ip_version == StackType.IPv4 && !Util.isIpv6StackAvailable()) throw new IllegalArgumentException("found IPv6 address " + addr + " in an IPv4-only stack"); // if(addr instanceof Inet4Address && addr.isMulticastAddress() && ip_version == StackType.IPv6) // throw new Exception("found IPv4 multicast address " + addr + " in an IPv6 stack"); } } // process default values setDefaultValues(protocol_configs, protocols, ip_version); ensureValidBindAddresses(protocols); // Fixes NPE with concurrent channel creation when using a shared stack (https://issues.jboss.org/browse/JGRP-1488) Protocol top_protocol=protocols.get(protocols.size() - 1); top_protocol.setUpProtocol(st); return connectProtocols(protocols); }
java
public static Protocol setupProtocolStack(List<ProtocolConfiguration> protocol_configs, ProtocolStack st) throws Exception { List<Protocol> protocols=createProtocols(protocol_configs, st); if(protocols == null) return null; // check InetAddress related features of stack Map<String, Map<String,InetAddressInfo>> inetAddressMap = createInetAddressMap(protocol_configs, protocols) ; Collection<InetAddress> addrs=getAddresses(inetAddressMap); StackType ip_version=Util.getIpStackType(); if(!addrs.isEmpty()) { // check that all user-supplied InetAddresses have a consistent version: // 1. If an addr is IPv6 and we have an IPv4 stack *only* --> FAIL for(InetAddress addr: addrs) { if(addr instanceof Inet6Address && ip_version == StackType.IPv4 && !Util.isIpv6StackAvailable()) throw new IllegalArgumentException("found IPv6 address " + addr + " in an IPv4-only stack"); // if(addr instanceof Inet4Address && addr.isMulticastAddress() && ip_version == StackType.IPv6) // throw new Exception("found IPv4 multicast address " + addr + " in an IPv6 stack"); } } // process default values setDefaultValues(protocol_configs, protocols, ip_version); ensureValidBindAddresses(protocols); // Fixes NPE with concurrent channel creation when using a shared stack (https://issues.jboss.org/browse/JGRP-1488) Protocol top_protocol=protocols.get(protocols.size() - 1); top_protocol.setUpProtocol(st); return connectProtocols(protocols); }
[ "public", "static", "Protocol", "setupProtocolStack", "(", "List", "<", "ProtocolConfiguration", ">", "protocol_configs", ",", "ProtocolStack", "st", ")", "throws", "Exception", "{", "List", "<", "Protocol", ">", "protocols", "=", "createProtocols", "(", "protocol_c...
The configuration string has a number of entries, separated by a ':' (colon). Each entry consists of the name of the protocol, followed by an optional configuration of that protocol. The configuration is enclosed in parentheses, and contains entries which are name/value pairs connected with an assignment sign (=) and separated by a semicolon. <pre>UDP(in_port=5555;out_port=4445):FRAG(frag_size=1024)</pre><p> The <em>first</em> entry defines the <em>bottommost</em> layer, the string is parsed left to right and the protocol stack constructed bottom up. Example: the string "UDP(in_port=5555):FRAG(frag_size=32000):DEBUG" results is the following stack:<pre> ----------------------- | DEBUG | |-----------------------| | FRAG frag_size=32000 | |-----------------------| | UDP in_port=32000 | ----------------------- </pre>
[ "The", "configuration", "string", "has", "a", "number", "of", "entries", "separated", "by", "a", ":", "(", "colon", ")", ".", "Each", "entry", "consists", "of", "the", "name", "of", "the", "protocol", "followed", "by", "an", "optional", "configuration", "o...
train
https://github.com/belaban/JGroups/blob/bd3ca786aa57fed41dfbc10a94b1281e388be03b/src/org/jgroups/stack/Configurator.java#L82-L114
guardtime/ksi-java-sdk
ksi-api/src/main/java/com/guardtime/ksi/PublicationsHandlerBuilder.java
PublicationsHandlerBuilder.setPublicationsFilePkiTrustStore
public PublicationsHandlerBuilder setPublicationsFilePkiTrustStore(File file, String password) throws KSIException { this.trustStore = Util.loadKeyStore(file, password); return this; }
java
public PublicationsHandlerBuilder setPublicationsFilePkiTrustStore(File file, String password) throws KSIException { this.trustStore = Util.loadKeyStore(file, password); return this; }
[ "public", "PublicationsHandlerBuilder", "setPublicationsFilePkiTrustStore", "(", "File", "file", ",", "String", "password", ")", "throws", "KSIException", "{", "this", ".", "trustStore", "=", "Util", ".", "loadKeyStore", "(", "file", ",", "password", ")", ";", "re...
Loads the {@link KeyStore} from the file system and sets the {@link KeyStore} to be used as truststore to verify the certificate that was used to sign the publications file. @param file keystore file on disk, not null. @param password password of the keystore, null if keystore isn't protected by password. @return Instance of {@link PublicationsHandlerBuilder}. @throws KSIException when any error occurs.
[ "Loads", "the", "{", "@link", "KeyStore", "}", "from", "the", "file", "system", "and", "sets", "the", "{", "@link", "KeyStore", "}", "to", "be", "used", "as", "truststore", "to", "verify", "the", "certificate", "that", "was", "used", "to", "sign", "the",...
train
https://github.com/guardtime/ksi-java-sdk/blob/b2cd877050f0f392657c724452318d10a1002171/ksi-api/src/main/java/com/guardtime/ksi/PublicationsHandlerBuilder.java#L93-L96
ocelotds/ocelot
ocelot-web/src/main/java/org/ocelotds/topic/TopicsMessagesBroadcaster.java
TopicsMessagesBroadcaster.checkMessageTopic
void checkMessageTopic(UserContext ctx, String topic, Object payload, JsTopicMessageController msgControl) throws NotRecipientException { if (null != msgControl) { msgControl.checkRight(ctx, topic, payload); } }
java
void checkMessageTopic(UserContext ctx, String topic, Object payload, JsTopicMessageController msgControl) throws NotRecipientException { if (null != msgControl) { msgControl.checkRight(ctx, topic, payload); } }
[ "void", "checkMessageTopic", "(", "UserContext", "ctx", ",", "String", "topic", ",", "Object", "payload", ",", "JsTopicMessageController", "msgControl", ")", "throws", "NotRecipientException", "{", "if", "(", "null", "!=", "msgControl", ")", "{", "msgControl", "."...
Check if message is granted by messageControl @param ctx @param mtc @param msgControl @return @throws NotRecipientException
[ "Check", "if", "message", "is", "granted", "by", "messageControl" ]
train
https://github.com/ocelotds/ocelot/blob/5f0ac37afd8fa4dc9f7234a2aac8abbb522128e7/ocelot-web/src/main/java/org/ocelotds/topic/TopicsMessagesBroadcaster.java#L143-L147
riccardove/easyjasub
easyjasub-lib/src/main/java/com/github/riccardove/easyjasub/cssbox/CssBoxPngRenderer.java
CssBoxPngRenderer.renderURL
private boolean renderURL(URL urlstring, URL baseUrl, OutputStream out) throws IOException, SAXException { // Open the network connection DocumentSource docSource = new DefaultDocumentSource(urlstring); // Parse the input document DOMSource parser = new DefaultDOMSource(docSource); Document doc = parser.parse(); // create the media specification MediaSpec media = new MediaSpec(mediaType); media.setDimensions(windowSize.width, windowSize.height); media.setDeviceDimensions(windowSize.width, windowSize.height); // Create the CSS analyzer DOMAnalyzer da = new DOMAnalyzer(doc, baseUrl); da.setMediaSpec(media); da.attributesToStyles(); // convert the HTML presentation attributes to // inline styles da.addStyleSheet(baseUrl, CSSNorm.stdStyleSheet(), DOMAnalyzer.Origin.AGENT); // use the standard style sheet da.addStyleSheet(null, CSSNorm.userStyleSheet(), DOMAnalyzer.Origin.AGENT); // use the additional style sheet da.addStyleSheet(null, CSSNorm.formsStyleSheet(), DOMAnalyzer.Origin.AGENT); // render form fields using css da.getStyleSheets(); // load the author style sheets BrowserCanvas contentCanvas = new BrowserCanvas(da.getRoot(), da, baseUrl); // contentCanvas.setAutoMediaUpdate(false); // we have a correct media // // specification, do not // // update contentCanvas.getConfig().setClipViewport(cropWindow); contentCanvas.getConfig().setLoadImages(loadImages); contentCanvas.getConfig().setLoadBackgroundImages(loadBackgroundImages); contentCanvas.setPreferredSize(new Dimension(windowSize.width, 10)); contentCanvas.setAutoSizeUpdate(true); setDefaultFonts(contentCanvas.getConfig()); contentCanvas.createLayout(windowSize); contentCanvas.validate(); ImageIO.write(contentCanvas.getImage(), "png", out); // Image image = contentCanvas.createImage(windowSize.width, // windowSize.height); docSource.close(); return true; }
java
private boolean renderURL(URL urlstring, URL baseUrl, OutputStream out) throws IOException, SAXException { // Open the network connection DocumentSource docSource = new DefaultDocumentSource(urlstring); // Parse the input document DOMSource parser = new DefaultDOMSource(docSource); Document doc = parser.parse(); // create the media specification MediaSpec media = new MediaSpec(mediaType); media.setDimensions(windowSize.width, windowSize.height); media.setDeviceDimensions(windowSize.width, windowSize.height); // Create the CSS analyzer DOMAnalyzer da = new DOMAnalyzer(doc, baseUrl); da.setMediaSpec(media); da.attributesToStyles(); // convert the HTML presentation attributes to // inline styles da.addStyleSheet(baseUrl, CSSNorm.stdStyleSheet(), DOMAnalyzer.Origin.AGENT); // use the standard style sheet da.addStyleSheet(null, CSSNorm.userStyleSheet(), DOMAnalyzer.Origin.AGENT); // use the additional style sheet da.addStyleSheet(null, CSSNorm.formsStyleSheet(), DOMAnalyzer.Origin.AGENT); // render form fields using css da.getStyleSheets(); // load the author style sheets BrowserCanvas contentCanvas = new BrowserCanvas(da.getRoot(), da, baseUrl); // contentCanvas.setAutoMediaUpdate(false); // we have a correct media // // specification, do not // // update contentCanvas.getConfig().setClipViewport(cropWindow); contentCanvas.getConfig().setLoadImages(loadImages); contentCanvas.getConfig().setLoadBackgroundImages(loadBackgroundImages); contentCanvas.setPreferredSize(new Dimension(windowSize.width, 10)); contentCanvas.setAutoSizeUpdate(true); setDefaultFonts(contentCanvas.getConfig()); contentCanvas.createLayout(windowSize); contentCanvas.validate(); ImageIO.write(contentCanvas.getImage(), "png", out); // Image image = contentCanvas.createImage(windowSize.width, // windowSize.height); docSource.close(); return true; }
[ "private", "boolean", "renderURL", "(", "URL", "urlstring", ",", "URL", "baseUrl", ",", "OutputStream", "out", ")", "throws", "IOException", ",", "SAXException", "{", "// Open the network connection", "DocumentSource", "docSource", "=", "new", "DefaultDocumentSource", ...
Renders the URL and prints the result to the specified output stream in the specified format. @param urlstring the source URL @param out output stream @param type output type @return true in case of success, false otherwise @throws SAXException
[ "Renders", "the", "URL", "and", "prints", "the", "result", "to", "the", "specified", "output", "stream", "in", "the", "specified", "format", "." ]
train
https://github.com/riccardove/easyjasub/blob/58d6af66b1b1c738326c74d9ad5e4ad514120e27/easyjasub-lib/src/main/java/com/github/riccardove/easyjasub/cssbox/CssBoxPngRenderer.java#L106-L157
tango-controls/JTango
server/src/main/java/org/tango/server/build/ClassPropertyBuilder.java
ClassPropertyBuilder.build
public void build(final Class<?> clazz, final Field field, final DeviceImpl device, final Object businessObject) throws DevFailed { xlogger.entry(); // create class property final ClassProperty annot = field.getAnnotation(ClassProperty.class); String propName; final String fieldName = field.getName(); if (annot.name().equals("")) { propName = fieldName; } else { propName = annot.name(); } logger.debug("Has a ClassProperty : {}", propName); BuilderUtils.checkStatic(field); final String setterName = BuilderUtils.SET + fieldName.substring(0, 1).toUpperCase(Locale.ENGLISH) + fieldName.substring(1); Method setter = null; try { setter = businessObject.getClass().getMethod(setterName, field.getType()); } catch (final NoSuchMethodException e) { throw DevFailedUtils.newDevFailed(e); } final ClassPropertyImpl property = new ClassPropertyImpl(propName, annot.description(), setter, businessObject, device.getClassName(), annot.defaultValue()); device.addClassProperty(property); xlogger.exit(); }
java
public void build(final Class<?> clazz, final Field field, final DeviceImpl device, final Object businessObject) throws DevFailed { xlogger.entry(); // create class property final ClassProperty annot = field.getAnnotation(ClassProperty.class); String propName; final String fieldName = field.getName(); if (annot.name().equals("")) { propName = fieldName; } else { propName = annot.name(); } logger.debug("Has a ClassProperty : {}", propName); BuilderUtils.checkStatic(field); final String setterName = BuilderUtils.SET + fieldName.substring(0, 1).toUpperCase(Locale.ENGLISH) + fieldName.substring(1); Method setter = null; try { setter = businessObject.getClass().getMethod(setterName, field.getType()); } catch (final NoSuchMethodException e) { throw DevFailedUtils.newDevFailed(e); } final ClassPropertyImpl property = new ClassPropertyImpl(propName, annot.description(), setter, businessObject, device.getClassName(), annot.defaultValue()); device.addClassProperty(property); xlogger.exit(); }
[ "public", "void", "build", "(", "final", "Class", "<", "?", ">", "clazz", ",", "final", "Field", "field", ",", "final", "DeviceImpl", "device", ",", "final", "Object", "businessObject", ")", "throws", "DevFailed", "{", "xlogger", ".", "entry", "(", ")", ...
Create class properties {@link ClassProperty} @param clazz @param field @param device @param businessObject @throws DevFailed
[ "Create", "class", "properties", "{", "@link", "ClassProperty", "}" ]
train
https://github.com/tango-controls/JTango/blob/1ccc9dcb83e6de2359a9f1906d170571cacf1345/server/src/main/java/org/tango/server/build/ClassPropertyBuilder.java#L62-L88
LAW-Unimi/BUbiNG
src/it/unimi/di/law/bubing/util/URLRespectsRobots.java
URLRespectsRobots.parseRobotsResponse
public static char[][] parseRobotsResponse(final URIResponse robotsResponse, final String userAgent) throws IOException { final int status = robotsResponse.response().getStatusLine().getStatusCode(); if (status / 100 != 2) LOGGER.info("Got status " + status + " while fetching robots: URL was " + robotsResponse.uri()); if (status / 100 == 4 || status / 100 == 5) return EMPTY_ROBOTS_FILTER; // For status 4xx and 5xx, we consider everything allowed. if (status / 100 != 2 && status / 100 != 3) return null; // For status 2xx and 3xx we parse the content. For the rest, we consider everything forbidden. // See if BOM is present and compute its length BOMInputStream bomInputStream = new BOMInputStream(robotsResponse.response().getEntity().getContent(), true); int bomLength = bomInputStream.hasBOM()? bomInputStream.getBOM().length() : 0; // Skip BOM, if necessary bomInputStream.skip(bomLength); // Parse robots (BOM is ignored, robots are UTF-8, as suggested by https://developers.google.com/search/reference/robots_txt char[][] result = parseRobotsReader(new InputStreamReader(bomInputStream, Charsets.UTF_8), userAgent); if (LOGGER.isDebugEnabled()) LOGGER.debug("Robots for {} successfully got with status {}: {}", robotsResponse.uri(), Integer.valueOf(status), toString(result)); return result; }
java
public static char[][] parseRobotsResponse(final URIResponse robotsResponse, final String userAgent) throws IOException { final int status = robotsResponse.response().getStatusLine().getStatusCode(); if (status / 100 != 2) LOGGER.info("Got status " + status + " while fetching robots: URL was " + robotsResponse.uri()); if (status / 100 == 4 || status / 100 == 5) return EMPTY_ROBOTS_FILTER; // For status 4xx and 5xx, we consider everything allowed. if (status / 100 != 2 && status / 100 != 3) return null; // For status 2xx and 3xx we parse the content. For the rest, we consider everything forbidden. // See if BOM is present and compute its length BOMInputStream bomInputStream = new BOMInputStream(robotsResponse.response().getEntity().getContent(), true); int bomLength = bomInputStream.hasBOM()? bomInputStream.getBOM().length() : 0; // Skip BOM, if necessary bomInputStream.skip(bomLength); // Parse robots (BOM is ignored, robots are UTF-8, as suggested by https://developers.google.com/search/reference/robots_txt char[][] result = parseRobotsReader(new InputStreamReader(bomInputStream, Charsets.UTF_8), userAgent); if (LOGGER.isDebugEnabled()) LOGGER.debug("Robots for {} successfully got with status {}: {}", robotsResponse.uri(), Integer.valueOf(status), toString(result)); return result; }
[ "public", "static", "char", "[", "]", "[", "]", "parseRobotsResponse", "(", "final", "URIResponse", "robotsResponse", ",", "final", "String", "userAgent", ")", "throws", "IOException", "{", "final", "int", "status", "=", "robotsResponse", ".", "response", "(", ...
Parses a <code>robots.txt</code> file contained in a {@link FetchData} and returns the corresponding filter as an array of sorted prefixes. HTTP statuses different from 2xx are {@linkplain Logger#warn(String) logged}. HTTP statuses of class 4xx generate an empty filter. HTTP statuses 2xx/3xx cause the tentative parsing of the request content. In the remaining cases we return {@code null}. @param robotsResponse the response containing <code>robots.txt</code>. @param userAgent the string representing the user agent of interest. @return an array of character arrays, which are prefixes of the URLs not to follow, in sorted order, or {@code null}
[ "Parses", "a", "<code", ">", "robots", ".", "txt<", "/", "code", ">", "file", "contained", "in", "a", "{", "@link", "FetchData", "}", "and", "returns", "the", "corresponding", "filter", "as", "an", "array", "of", "sorted", "prefixes", ".", "HTTP", "statu...
train
https://github.com/LAW-Unimi/BUbiNG/blob/e148acc90031a4f3967422705a9fb07ddaf155e4/src/it/unimi/di/law/bubing/util/URLRespectsRobots.java#L177-L191
alkacon/opencms-core
src-gwt/org/opencms/gwt/client/property/CmsVfsModePropertyEditor.java
CmsVfsModePropertyEditor.createStringModel
private I_CmsStringModel createStringModel(final CmsUUID id, final String propName, final boolean isStructure) { final CmsClientProperty property = m_properties.get(propName); return new I_CmsStringModel() { private boolean m_active; private EventBus m_eventBus = new SimpleEventBus(); public HandlerRegistration addValueChangeHandler(ValueChangeHandler<String> handler) { return m_eventBus.addHandler(ValueChangeEvent.getType(), handler); } /** * @see com.google.gwt.event.shared.HasHandlers#fireEvent(com.google.gwt.event.shared.GwtEvent) */ public void fireEvent(GwtEvent<?> event) { m_eventBus.fireEvent(event); } public String getId() { return Joiner.on("/").join(id.toString(), propName, isStructure ? "S" : "R"); } public String getValue() { if (isStructure) { return property.getStructureValue(); } else { return property.getResourceValue(); } } public void setValue(String value, boolean notify) { if (!m_active) { m_active = true; try { String oldValue = getValue(); boolean changed = !Objects.equal(value, oldValue); if (isStructure) { property.setStructureValue(value); } else { property.setResourceValue(value); } if (notify && changed) { ValueChangeEvent.fire(this, value); } } finally { m_active = false; } } } }; }
java
private I_CmsStringModel createStringModel(final CmsUUID id, final String propName, final boolean isStructure) { final CmsClientProperty property = m_properties.get(propName); return new I_CmsStringModel() { private boolean m_active; private EventBus m_eventBus = new SimpleEventBus(); public HandlerRegistration addValueChangeHandler(ValueChangeHandler<String> handler) { return m_eventBus.addHandler(ValueChangeEvent.getType(), handler); } /** * @see com.google.gwt.event.shared.HasHandlers#fireEvent(com.google.gwt.event.shared.GwtEvent) */ public void fireEvent(GwtEvent<?> event) { m_eventBus.fireEvent(event); } public String getId() { return Joiner.on("/").join(id.toString(), propName, isStructure ? "S" : "R"); } public String getValue() { if (isStructure) { return property.getStructureValue(); } else { return property.getResourceValue(); } } public void setValue(String value, boolean notify) { if (!m_active) { m_active = true; try { String oldValue = getValue(); boolean changed = !Objects.equal(value, oldValue); if (isStructure) { property.setStructureValue(value); } else { property.setResourceValue(value); } if (notify && changed) { ValueChangeEvent.fire(this, value); } } finally { m_active = false; } } } }; }
[ "private", "I_CmsStringModel", "createStringModel", "(", "final", "CmsUUID", "id", ",", "final", "String", "propName", ",", "final", "boolean", "isStructure", ")", "{", "final", "CmsClientProperty", "property", "=", "m_properties", ".", "get", "(", "propName", ")"...
Creates a string model which uses a field of a CmsClientProperty for storing its value.<p> @param id the structure id @param propName the property id @param isStructure if true, the structure value field should be used, else the resource value field @return the new model object
[ "Creates", "a", "string", "model", "which", "uses", "a", "field", "of", "a", "CmsClientProperty", "for", "storing", "its", "value", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/property/CmsVfsModePropertyEditor.java#L450-L508
biojava/biojava
biojava-structure/src/main/java/org/biojava/nbio/structure/SubstructureIdentifier.java
SubstructureIdentifier.copyLigandsByProximity
protected static void copyLigandsByProximity(Structure full, Structure reduced, double cutoff, int fromModel, int toModel) { // Geometric hashing of the reduced structure Grid grid = new Grid(cutoff); Atom[] nonwaters = StructureTools.getAllNonHAtomArray(reduced,true,toModel); if( nonwaters.length < 1 ) return; grid.addAtoms(nonwaters); full.getNonPolyChains(fromModel).stream() //potential ligand chains .flatMap((chain) -> chain.getAtomGroups().stream() ) // potential ligand groups .filter( (g) -> !g.isWater() ) // ignore waters .filter( (g) -> !g.isPolymeric() ) // already shouldn't be polymeric, but filter anyways .filter( (g) -> grid.hasAnyContact(Calc.atomsToPoints(g.getAtoms())) ) // must contact reduced .sequential() // Keeps ligands from the same chain together if possible .reduce((Chain)null, // reduction updates the chain guess (guess, g ) -> { boolean wasAdded; try { // Check that it's not in reduced already wasAdded = reduced.findGroup(g.getChainId(), g.getResidueNumber().toString(), toModel) != null; } catch (StructureException e) { // not found wasAdded = false; } if( !wasAdded ) { // Add the ligand to reduced // note this is not idempotent, but it is synchronized on reduced logger.info("Adding ligand group {} {} by proximity",g.getPDBName(), g.getResidueNumber().toPDB()); return StructureTools.addGroupToStructure(reduced, g, toModel, guess, false); } return guess; }, // update to the new guess (oldGuess, newGuess) -> newGuess ); }
java
protected static void copyLigandsByProximity(Structure full, Structure reduced, double cutoff, int fromModel, int toModel) { // Geometric hashing of the reduced structure Grid grid = new Grid(cutoff); Atom[] nonwaters = StructureTools.getAllNonHAtomArray(reduced,true,toModel); if( nonwaters.length < 1 ) return; grid.addAtoms(nonwaters); full.getNonPolyChains(fromModel).stream() //potential ligand chains .flatMap((chain) -> chain.getAtomGroups().stream() ) // potential ligand groups .filter( (g) -> !g.isWater() ) // ignore waters .filter( (g) -> !g.isPolymeric() ) // already shouldn't be polymeric, but filter anyways .filter( (g) -> grid.hasAnyContact(Calc.atomsToPoints(g.getAtoms())) ) // must contact reduced .sequential() // Keeps ligands from the same chain together if possible .reduce((Chain)null, // reduction updates the chain guess (guess, g ) -> { boolean wasAdded; try { // Check that it's not in reduced already wasAdded = reduced.findGroup(g.getChainId(), g.getResidueNumber().toString(), toModel) != null; } catch (StructureException e) { // not found wasAdded = false; } if( !wasAdded ) { // Add the ligand to reduced // note this is not idempotent, but it is synchronized on reduced logger.info("Adding ligand group {} {} by proximity",g.getPDBName(), g.getResidueNumber().toPDB()); return StructureTools.addGroupToStructure(reduced, g, toModel, guess, false); } return guess; }, // update to the new guess (oldGuess, newGuess) -> newGuess ); }
[ "protected", "static", "void", "copyLigandsByProximity", "(", "Structure", "full", ",", "Structure", "reduced", ",", "double", "cutoff", ",", "int", "fromModel", ",", "int", "toModel", ")", "{", "// Geometric hashing of the reduced structure", "Grid", "grid", "=", "...
Supplements the reduced structure with ligands from the full structure based on a distance cutoff. Ligand groups are moved (destructively) from full to reduced if they fall within the cutoff of any atom in the reduced structure. @param full Structure containing all ligands @param reduced Structure with a subset of the polymer groups from full @param cutoff Distance cutoff (Å) @param fromModel source model in full @param toModel destination model in reduced @see StructureTools#getLigandsByProximity(java.util.Collection, Atom[], double)
[ "Supplements", "the", "reduced", "structure", "with", "ligands", "from", "the", "full", "structure", "based", "on", "a", "distance", "cutoff", ".", "Ligand", "groups", "are", "moved", "(", "destructively", ")", "from", "full", "to", "reduced", "if", "they", ...
train
https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/SubstructureIdentifier.java#L327-L362
aws/aws-sdk-java
aws-java-sdk-kinesis/src/main/java/com/amazonaws/services/kinesis/model/EnhancedMetrics.java
EnhancedMetrics.getShardLevelMetrics
public java.util.List<String> getShardLevelMetrics() { if (shardLevelMetrics == null) { shardLevelMetrics = new com.amazonaws.internal.SdkInternalList<String>(); } return shardLevelMetrics; }
java
public java.util.List<String> getShardLevelMetrics() { if (shardLevelMetrics == null) { shardLevelMetrics = new com.amazonaws.internal.SdkInternalList<String>(); } return shardLevelMetrics; }
[ "public", "java", ".", "util", ".", "List", "<", "String", ">", "getShardLevelMetrics", "(", ")", "{", "if", "(", "shardLevelMetrics", "==", "null", ")", "{", "shardLevelMetrics", "=", "new", "com", ".", "amazonaws", ".", "internal", ".", "SdkInternalList", ...
<p> List of shard-level metrics. </p> <p> The following are the valid shard-level metrics. The value "<code>ALL</code>" enhances every metric. </p> <ul> <li> <p> <code>IncomingBytes</code> </p> </li> <li> <p> <code>IncomingRecords</code> </p> </li> <li> <p> <code>OutgoingBytes</code> </p> </li> <li> <p> <code>OutgoingRecords</code> </p> </li> <li> <p> <code>WriteProvisionedThroughputExceeded</code> </p> </li> <li> <p> <code>ReadProvisionedThroughputExceeded</code> </p> </li> <li> <p> <code>IteratorAgeMilliseconds</code> </p> </li> <li> <p> <code>ALL</code> </p> </li> </ul> <p> For more information, see <a href="http://docs.aws.amazon.com/kinesis/latest/dev/monitoring-with-cloudwatch.html">Monitoring the Amazon Kinesis Data Streams Service with Amazon CloudWatch</a> in the <i>Amazon Kinesis Data Streams Developer Guide</i>. </p> @return List of shard-level metrics.</p> <p> The following are the valid shard-level metrics. The value "<code>ALL</code>" enhances every metric. </p> <ul> <li> <p> <code>IncomingBytes</code> </p> </li> <li> <p> <code>IncomingRecords</code> </p> </li> <li> <p> <code>OutgoingBytes</code> </p> </li> <li> <p> <code>OutgoingRecords</code> </p> </li> <li> <p> <code>WriteProvisionedThroughputExceeded</code> </p> </li> <li> <p> <code>ReadProvisionedThroughputExceeded</code> </p> </li> <li> <p> <code>IteratorAgeMilliseconds</code> </p> </li> <li> <p> <code>ALL</code> </p> </li> </ul> <p> For more information, see <a href="http://docs.aws.amazon.com/kinesis/latest/dev/monitoring-with-cloudwatch.html">Monitoring the Amazon Kinesis Data Streams Service with Amazon CloudWatch</a> in the <i>Amazon Kinesis Data Streams Developer Guide</i>. @see MetricsName
[ "<p", ">", "List", "of", "shard", "-", "level", "metrics", ".", "<", "/", "p", ">", "<p", ">", "The", "following", "are", "the", "valid", "shard", "-", "level", "metrics", ".", "The", "value", "<code", ">", "ALL<", "/", "code", ">", "enhances", "ev...
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-kinesis/src/main/java/com/amazonaws/services/kinesis/model/EnhancedMetrics.java#L199-L204
jamesagnew/hapi-fhir
hapi-fhir-structures-dstu3/src/main/java/org/hl7/fhir/dstu3/model/Meta.java
Meta.addTag
public Meta addTag(String theSystem, String theCode, String theDisplay) { addTag().setSystem(theSystem).setCode(theCode).setDisplay(theDisplay); return this; }
java
public Meta addTag(String theSystem, String theCode, String theDisplay) { addTag().setSystem(theSystem).setCode(theCode).setDisplay(theDisplay); return this; }
[ "public", "Meta", "addTag", "(", "String", "theSystem", ",", "String", "theCode", ",", "String", "theDisplay", ")", "{", "addTag", "(", ")", ".", "setSystem", "(", "theSystem", ")", ".", "setCode", "(", "theCode", ")", ".", "setDisplay", "(", "theDisplay",...
Convenience method which adds a tag @param theSystem The code system @param theCode The code @param theDisplay The display name @return Returns a reference to <code>this</code> for easy chaining
[ "Convenience", "method", "which", "adds", "a", "tag" ]
train
https://github.com/jamesagnew/hapi-fhir/blob/150a84d52fe691b7f48fcb28247c4bddb7aec352/hapi-fhir-structures-dstu3/src/main/java/org/hl7/fhir/dstu3/model/Meta.java#L371-L374
bitcoinj/bitcoinj
core/src/main/java/org/bitcoinj/script/Script.java
Script.getPubKeys
public List<ECKey> getPubKeys() { if (!ScriptPattern.isSentToMultisig(this)) throw new ScriptException(ScriptError.SCRIPT_ERR_UNKNOWN_ERROR, "Only usable for multisig scripts."); ArrayList<ECKey> result = Lists.newArrayList(); int numKeys = Script.decodeFromOpN(chunks.get(chunks.size() - 2).opcode); for (int i = 0 ; i < numKeys ; i++) result.add(ECKey.fromPublicOnly(chunks.get(1 + i).data)); return result; }
java
public List<ECKey> getPubKeys() { if (!ScriptPattern.isSentToMultisig(this)) throw new ScriptException(ScriptError.SCRIPT_ERR_UNKNOWN_ERROR, "Only usable for multisig scripts."); ArrayList<ECKey> result = Lists.newArrayList(); int numKeys = Script.decodeFromOpN(chunks.get(chunks.size() - 2).opcode); for (int i = 0 ; i < numKeys ; i++) result.add(ECKey.fromPublicOnly(chunks.get(1 + i).data)); return result; }
[ "public", "List", "<", "ECKey", ">", "getPubKeys", "(", ")", "{", "if", "(", "!", "ScriptPattern", ".", "isSentToMultisig", "(", "this", ")", ")", "throw", "new", "ScriptException", "(", "ScriptError", ".", "SCRIPT_ERR_UNKNOWN_ERROR", ",", "\"Only usable for mul...
Returns a list of the keys required by this script, assuming a multi-sig script. @throws ScriptException if the script type is not understood or is pay to address or is P2SH (run this method on the "Redeem script" instead).
[ "Returns", "a", "list", "of", "the", "keys", "required", "by", "this", "script", "assuming", "a", "multi", "-", "sig", "script", "." ]
train
https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/script/Script.java#L482-L491
maven-nar/nar-maven-plugin
src/main/java/com/github/maven_nar/cpptasks/borland/CBuilderXProjectWriter.java
CBuilderXProjectWriter.writeIlinkArgs
private void writeIlinkArgs(final PropertyWriter writer, final String linkID, final String[] args) throws SAXException { for (final String arg : args) { if (arg.charAt(0) == '/' || arg.charAt(0) == '-') { final int equalsPos = arg.indexOf('='); if (equalsPos > 0) { final String option = "option." + arg.substring(0, equalsPos - 1); writer.write(linkID, option + ".enabled", "1"); writer.write(linkID, option + ".value", arg.substring(equalsPos + 1)); } else { writer.write(linkID, "option." + arg.substring(1) + ".enabled", "1"); } } } }
java
private void writeIlinkArgs(final PropertyWriter writer, final String linkID, final String[] args) throws SAXException { for (final String arg : args) { if (arg.charAt(0) == '/' || arg.charAt(0) == '-') { final int equalsPos = arg.indexOf('='); if (equalsPos > 0) { final String option = "option." + arg.substring(0, equalsPos - 1); writer.write(linkID, option + ".enabled", "1"); writer.write(linkID, option + ".value", arg.substring(equalsPos + 1)); } else { writer.write(linkID, "option." + arg.substring(1) + ".enabled", "1"); } } } }
[ "private", "void", "writeIlinkArgs", "(", "final", "PropertyWriter", "writer", ",", "final", "String", "linkID", ",", "final", "String", "[", "]", "args", ")", "throws", "SAXException", "{", "for", "(", "final", "String", "arg", ":", "args", ")", "{", "if"...
Writes ilink32 linker options to project file. @param writer PropertyWriter property writer @param linkID String linker identifier @param preArgs String[] linker arguments @throws SAXException thrown if unable to write option
[ "Writes", "ilink32", "linker", "options", "to", "project", "file", "." ]
train
https://github.com/maven-nar/nar-maven-plugin/blob/3c622e2024296b4203431bbae3bde290a01dac00/src/main/java/com/github/maven_nar/cpptasks/borland/CBuilderXProjectWriter.java#L259-L273
GCRC/nunaliit
nunaliit2-multimedia/src/main/java/ca/carleton/gcrc/olkit/multimedia/file/SystemFile.java
SystemFile.addKnownString
static public void addKnownString(String mimeType, String knownString) { Map<String,String> map = getKnownStrings(); if( null != mimeType && null != knownString ) { map.put(knownString.trim(), mimeType.trim()); } }
java
static public void addKnownString(String mimeType, String knownString) { Map<String,String> map = getKnownStrings(); if( null != mimeType && null != knownString ) { map.put(knownString.trim(), mimeType.trim()); } }
[ "static", "public", "void", "addKnownString", "(", "String", "mimeType", ",", "String", "knownString", ")", "{", "Map", "<", "String", ",", "String", ">", "map", "=", "getKnownStrings", "(", ")", ";", "if", "(", "null", "!=", "mimeType", "&&", "null", "!...
Adds a relation between a known string for File and a mime type. @param mimeType Mime type that should be returned if known string is encountered @param knownString A string that is found when performing "file -bnk"
[ "Adds", "a", "relation", "between", "a", "known", "string", "for", "File", "and", "a", "mime", "type", "." ]
train
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-multimedia/src/main/java/ca/carleton/gcrc/olkit/multimedia/file/SystemFile.java#L69-L74
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/lang/UCharacter.java
UCharacter.foldCase
public static final String foldCase(String str, int options) { if (str.length() <= 100) { if (str.isEmpty()) { return str; } // Collect and apply only changes. // Good if no or few changes. Bad (slow) if many changes. Edits edits = new Edits(); StringBuilder replacementChars = CaseMapImpl.fold( options | CaseMapImpl.OMIT_UNCHANGED_TEXT, str, new StringBuilder(), edits); return applyEdits(str, replacementChars, edits); } else { return CaseMapImpl.fold(options, str, new StringBuilder(str.length()), null).toString(); } }
java
public static final String foldCase(String str, int options) { if (str.length() <= 100) { if (str.isEmpty()) { return str; } // Collect and apply only changes. // Good if no or few changes. Bad (slow) if many changes. Edits edits = new Edits(); StringBuilder replacementChars = CaseMapImpl.fold( options | CaseMapImpl.OMIT_UNCHANGED_TEXT, str, new StringBuilder(), edits); return applyEdits(str, replacementChars, edits); } else { return CaseMapImpl.fold(options, str, new StringBuilder(str.length()), null).toString(); } }
[ "public", "static", "final", "String", "foldCase", "(", "String", "str", ",", "int", "options", ")", "{", "if", "(", "str", ".", "length", "(", ")", "<=", "100", ")", "{", "if", "(", "str", ".", "isEmpty", "(", ")", ")", "{", "return", "str", ";"...
<strong>[icu]</strong> The given string is mapped to its case folding equivalent according to UnicodeData.txt and CaseFolding.txt; if any character has no case folding equivalent, the character itself is returned. "Full", multiple-code point case folding mappings are returned here. For "simple" single-code point mappings use the API foldCase(int ch, boolean defaultmapping). @param str the String to be converted @param options A bit set for special processing. Currently the recognised options are FOLD_CASE_EXCLUDE_SPECIAL_I and FOLD_CASE_DEFAULT @return the case folding equivalent of the character, if any; otherwise the character itself. @see #foldCase(int, boolean)
[ "<strong", ">", "[", "icu", "]", "<", "/", "strong", ">", "The", "given", "string", "is", "mapped", "to", "its", "case", "folding", "equivalent", "according", "to", "UnicodeData", ".", "txt", "and", "CaseFolding", ".", "txt", ";", "if", "any", "character...
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/lang/UCharacter.java#L4741-L4755
Alluxio/alluxio
core/server/worker/src/main/java/alluxio/worker/block/TieredBlockStore.java
TieredBlockStore.abortBlockInternal
private void abortBlockInternal(long sessionId, long blockId) throws BlockDoesNotExistException, BlockAlreadyExistsException, InvalidWorkerStateException, IOException { String path; TempBlockMeta tempBlockMeta; try (LockResource r = new LockResource(mMetadataReadLock)) { checkTempBlockOwnedBySession(sessionId, blockId); tempBlockMeta = mMetaManager.getTempBlockMeta(blockId); path = tempBlockMeta.getPath(); } // The metadata lock is released during heavy IO. The temp block is private to one session, so // we do not lock it. Files.delete(Paths.get(path)); try (LockResource r = new LockResource(mMetadataWriteLock)) { mMetaManager.abortTempBlockMeta(tempBlockMeta); } catch (BlockDoesNotExistException e) { throw Throwables.propagate(e); // We shall never reach here } }
java
private void abortBlockInternal(long sessionId, long blockId) throws BlockDoesNotExistException, BlockAlreadyExistsException, InvalidWorkerStateException, IOException { String path; TempBlockMeta tempBlockMeta; try (LockResource r = new LockResource(mMetadataReadLock)) { checkTempBlockOwnedBySession(sessionId, blockId); tempBlockMeta = mMetaManager.getTempBlockMeta(blockId); path = tempBlockMeta.getPath(); } // The metadata lock is released during heavy IO. The temp block is private to one session, so // we do not lock it. Files.delete(Paths.get(path)); try (LockResource r = new LockResource(mMetadataWriteLock)) { mMetaManager.abortTempBlockMeta(tempBlockMeta); } catch (BlockDoesNotExistException e) { throw Throwables.propagate(e); // We shall never reach here } }
[ "private", "void", "abortBlockInternal", "(", "long", "sessionId", ",", "long", "blockId", ")", "throws", "BlockDoesNotExistException", ",", "BlockAlreadyExistsException", ",", "InvalidWorkerStateException", ",", "IOException", "{", "String", "path", ";", "TempBlockMeta",...
Aborts a temp block. @param sessionId the id of session @param blockId the id of block @throws BlockDoesNotExistException if block id can not be found in temporary blocks @throws BlockAlreadyExistsException if block id already exists in committed blocks @throws InvalidWorkerStateException if block id is not owned by session id
[ "Aborts", "a", "temp", "block", "." ]
train
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/worker/src/main/java/alluxio/worker/block/TieredBlockStore.java#L555-L575
alibaba/jstorm
jstorm-on-yarn/src/main/java/com/alibaba/jstorm/yarn/utils/JStormUtils.java
JStormUtils.zipContainsDir
public static boolean zipContainsDir(String zipfile, String resources) { Enumeration<? extends ZipEntry> entries = null; try { entries = (new ZipFile(zipfile)).entries(); while (entries != null && entries.hasMoreElements()) { ZipEntry ze = entries.nextElement(); String name = ze.getName(); if (name.startsWith(resources + "/")) { return true; } } } catch (IOException e) { // TODO Auto-generated catch block // e.printStackTrace(); LOG.error(e + "zipContainsDir error"); } return false; }
java
public static boolean zipContainsDir(String zipfile, String resources) { Enumeration<? extends ZipEntry> entries = null; try { entries = (new ZipFile(zipfile)).entries(); while (entries != null && entries.hasMoreElements()) { ZipEntry ze = entries.nextElement(); String name = ze.getName(); if (name.startsWith(resources + "/")) { return true; } } } catch (IOException e) { // TODO Auto-generated catch block // e.printStackTrace(); LOG.error(e + "zipContainsDir error"); } return false; }
[ "public", "static", "boolean", "zipContainsDir", "(", "String", "zipfile", ",", "String", "resources", ")", "{", "Enumeration", "<", "?", "extends", "ZipEntry", ">", "entries", "=", "null", ";", "try", "{", "entries", "=", "(", "new", "ZipFile", "(", "zipf...
Check whether the zipfile contain the resources @param zipfile @param resources @return
[ "Check", "whether", "the", "zipfile", "contain", "the", "resources" ]
train
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-on-yarn/src/main/java/com/alibaba/jstorm/yarn/utils/JStormUtils.java#L797-L816