repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
218
func_name
stringlengths
4
140
whole_func_string
stringlengths
153
5.32k
language
stringclasses
1 value
func_code_string
stringlengths
72
4k
func_code_tokens
sequencelengths
20
832
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
sequencelengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
102
339
selendroid/selendroid
selendroid-server/src/main/java/io/selendroid/server/extension/ExtensionLoader.java
ExtensionLoader.loadHandler
public BaseRequestHandler loadHandler(String handlerClassName, String uri) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { """ Loads a {@link BaseRequestHandler} class from the extension dex. """ Class<? extends BaseRequestHandler> handlerClass = classLoader.loadClass(handlerClassName).asSubclass(BaseRequestHandler.class); Constructor<? extends BaseRequestHandler> constructor = handlerClass.getConstructor(String.class); return constructor.newInstance(uri); }
java
public BaseRequestHandler loadHandler(String handlerClassName, String uri) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { Class<? extends BaseRequestHandler> handlerClass = classLoader.loadClass(handlerClassName).asSubclass(BaseRequestHandler.class); Constructor<? extends BaseRequestHandler> constructor = handlerClass.getConstructor(String.class); return constructor.newInstance(uri); }
[ "public", "BaseRequestHandler", "loadHandler", "(", "String", "handlerClassName", ",", "String", "uri", ")", "throws", "ClassNotFoundException", ",", "NoSuchMethodException", ",", "IllegalAccessException", ",", "InvocationTargetException", ",", "InstantiationException", "{", "Class", "<", "?", "extends", "BaseRequestHandler", ">", "handlerClass", "=", "classLoader", ".", "loadClass", "(", "handlerClassName", ")", ".", "asSubclass", "(", "BaseRequestHandler", ".", "class", ")", ";", "Constructor", "<", "?", "extends", "BaseRequestHandler", ">", "constructor", "=", "handlerClass", ".", "getConstructor", "(", "String", ".", "class", ")", ";", "return", "constructor", ".", "newInstance", "(", "uri", ")", ";", "}" ]
Loads a {@link BaseRequestHandler} class from the extension dex.
[ "Loads", "a", "{" ]
train
https://github.com/selendroid/selendroid/blob/a32c1a96c973b80c14a588b1075f084201f7fe94/selendroid-server/src/main/java/io/selendroid/server/extension/ExtensionLoader.java#L110-L119
pravega/pravega
segmentstore/storage/src/main/java/io/pravega/segmentstore/storage/rolling/RollingSegmentHandle.java
RollingSegmentHandle.addChunk
synchronized void addChunk(SegmentChunk segmentChunk, SegmentHandle activeChunkHandle) { """ Adds a new SegmentChunk. @param segmentChunk The SegmentChunk to add. This SegmentChunk must be in continuity of any existing SegmentChunks. @param activeChunkHandle The newly added SegmentChunk's write handle. """ Preconditions.checkState(!this.sealed, "Cannot add SegmentChunks for a Sealed Handle."); if (this.segmentChunks.size() > 0) { long expectedOffset = this.segmentChunks.get(this.segmentChunks.size() - 1).getLastOffset(); Preconditions.checkArgument(segmentChunk.getStartOffset() == expectedOffset, "Invalid SegmentChunk StartOffset. Expected %s, given %s.", expectedOffset, segmentChunk.getStartOffset()); } // Update the SegmentChunk and its Handle atomically. Preconditions.checkNotNull(activeChunkHandle, "activeChunkHandle"); Preconditions.checkArgument(!activeChunkHandle.isReadOnly(), "Active SegmentChunk handle cannot be readonly."); Preconditions.checkArgument(activeChunkHandle.getSegmentName().equals(segmentChunk.getName()), "Active SegmentChunk handle must be for the last SegmentChunk."); this.activeChunkHandle = activeChunkHandle; this.segmentChunks.add(segmentChunk); }
java
synchronized void addChunk(SegmentChunk segmentChunk, SegmentHandle activeChunkHandle) { Preconditions.checkState(!this.sealed, "Cannot add SegmentChunks for a Sealed Handle."); if (this.segmentChunks.size() > 0) { long expectedOffset = this.segmentChunks.get(this.segmentChunks.size() - 1).getLastOffset(); Preconditions.checkArgument(segmentChunk.getStartOffset() == expectedOffset, "Invalid SegmentChunk StartOffset. Expected %s, given %s.", expectedOffset, segmentChunk.getStartOffset()); } // Update the SegmentChunk and its Handle atomically. Preconditions.checkNotNull(activeChunkHandle, "activeChunkHandle"); Preconditions.checkArgument(!activeChunkHandle.isReadOnly(), "Active SegmentChunk handle cannot be readonly."); Preconditions.checkArgument(activeChunkHandle.getSegmentName().equals(segmentChunk.getName()), "Active SegmentChunk handle must be for the last SegmentChunk."); this.activeChunkHandle = activeChunkHandle; this.segmentChunks.add(segmentChunk); }
[ "synchronized", "void", "addChunk", "(", "SegmentChunk", "segmentChunk", ",", "SegmentHandle", "activeChunkHandle", ")", "{", "Preconditions", ".", "checkState", "(", "!", "this", ".", "sealed", ",", "\"Cannot add SegmentChunks for a Sealed Handle.\"", ")", ";", "if", "(", "this", ".", "segmentChunks", ".", "size", "(", ")", ">", "0", ")", "{", "long", "expectedOffset", "=", "this", ".", "segmentChunks", ".", "get", "(", "this", ".", "segmentChunks", ".", "size", "(", ")", "-", "1", ")", ".", "getLastOffset", "(", ")", ";", "Preconditions", ".", "checkArgument", "(", "segmentChunk", ".", "getStartOffset", "(", ")", "==", "expectedOffset", ",", "\"Invalid SegmentChunk StartOffset. Expected %s, given %s.\"", ",", "expectedOffset", ",", "segmentChunk", ".", "getStartOffset", "(", ")", ")", ";", "}", "// Update the SegmentChunk and its Handle atomically.", "Preconditions", ".", "checkNotNull", "(", "activeChunkHandle", ",", "\"activeChunkHandle\"", ")", ";", "Preconditions", ".", "checkArgument", "(", "!", "activeChunkHandle", ".", "isReadOnly", "(", ")", ",", "\"Active SegmentChunk handle cannot be readonly.\"", ")", ";", "Preconditions", ".", "checkArgument", "(", "activeChunkHandle", ".", "getSegmentName", "(", ")", ".", "equals", "(", "segmentChunk", ".", "getName", "(", ")", ")", ",", "\"Active SegmentChunk handle must be for the last SegmentChunk.\"", ")", ";", "this", ".", "activeChunkHandle", "=", "activeChunkHandle", ";", "this", ".", "segmentChunks", ".", "add", "(", "segmentChunk", ")", ";", "}" ]
Adds a new SegmentChunk. @param segmentChunk The SegmentChunk to add. This SegmentChunk must be in continuity of any existing SegmentChunks. @param activeChunkHandle The newly added SegmentChunk's write handle.
[ "Adds", "a", "new", "SegmentChunk", "." ]
train
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/segmentstore/storage/src/main/java/io/pravega/segmentstore/storage/rolling/RollingSegmentHandle.java#L179-L194
BioPAX/Paxtools
pattern/src/main/java/org/biopax/paxtools/pattern/PatternBox.java
PatternBox.controlsStateChangeButIsParticipant
public static Pattern controlsStateChangeButIsParticipant() { """ Pattern for a EntityReference has a member PhysicalEntity that is controlling a state change reaction of another EntityReference. This pattern is different from the original controls-state-change. The controller in this case is not modeled as a controller, but as a participant of the conversion, and it is at both sides. @return the pattern """ Pattern p = new Pattern(SequenceEntityReference.class, "controller ER"); p.add(linkedER(true), "controller ER", "controller generic ER"); p.add(erToPE(), "controller generic ER", "controller simple PE"); p.add(linkToComplex(), "controller simple PE", "controller PE"); p.add(participatesInConv(), "controller PE", "Conversion"); p.add(left(), "Conversion", "controller PE"); p.add(right(), "Conversion", "controller PE"); // The controller ER is not associated with the Conversion in another way. p.add(new NOT(new InterToPartER(1)), "Conversion", "controller PE", "controller ER"); stateChange(p, null); p.add(equal(false), "controller ER", "changed ER"); p.add(equal(false), "controller PE", "input PE"); p.add(equal(false), "controller PE", "output PE"); return p; }
java
public static Pattern controlsStateChangeButIsParticipant() { Pattern p = new Pattern(SequenceEntityReference.class, "controller ER"); p.add(linkedER(true), "controller ER", "controller generic ER"); p.add(erToPE(), "controller generic ER", "controller simple PE"); p.add(linkToComplex(), "controller simple PE", "controller PE"); p.add(participatesInConv(), "controller PE", "Conversion"); p.add(left(), "Conversion", "controller PE"); p.add(right(), "Conversion", "controller PE"); // The controller ER is not associated with the Conversion in another way. p.add(new NOT(new InterToPartER(1)), "Conversion", "controller PE", "controller ER"); stateChange(p, null); p.add(equal(false), "controller ER", "changed ER"); p.add(equal(false), "controller PE", "input PE"); p.add(equal(false), "controller PE", "output PE"); return p; }
[ "public", "static", "Pattern", "controlsStateChangeButIsParticipant", "(", ")", "{", "Pattern", "p", "=", "new", "Pattern", "(", "SequenceEntityReference", ".", "class", ",", "\"controller ER\"", ")", ";", "p", ".", "add", "(", "linkedER", "(", "true", ")", ",", "\"controller ER\"", ",", "\"controller generic ER\"", ")", ";", "p", ".", "add", "(", "erToPE", "(", ")", ",", "\"controller generic ER\"", ",", "\"controller simple PE\"", ")", ";", "p", ".", "add", "(", "linkToComplex", "(", ")", ",", "\"controller simple PE\"", ",", "\"controller PE\"", ")", ";", "p", ".", "add", "(", "participatesInConv", "(", ")", ",", "\"controller PE\"", ",", "\"Conversion\"", ")", ";", "p", ".", "add", "(", "left", "(", ")", ",", "\"Conversion\"", ",", "\"controller PE\"", ")", ";", "p", ".", "add", "(", "right", "(", ")", ",", "\"Conversion\"", ",", "\"controller PE\"", ")", ";", "// The controller ER is not associated with the Conversion in another way.", "p", ".", "add", "(", "new", "NOT", "(", "new", "InterToPartER", "(", "1", ")", ")", ",", "\"Conversion\"", ",", "\"controller PE\"", ",", "\"controller ER\"", ")", ";", "stateChange", "(", "p", ",", "null", ")", ";", "p", ".", "add", "(", "equal", "(", "false", ")", ",", "\"controller ER\"", ",", "\"changed ER\"", ")", ";", "p", ".", "add", "(", "equal", "(", "false", ")", ",", "\"controller PE\"", ",", "\"input PE\"", ")", ";", "p", ".", "add", "(", "equal", "(", "false", ")", ",", "\"controller PE\"", ",", "\"output PE\"", ")", ";", "return", "p", ";", "}" ]
Pattern for a EntityReference has a member PhysicalEntity that is controlling a state change reaction of another EntityReference. This pattern is different from the original controls-state-change. The controller in this case is not modeled as a controller, but as a participant of the conversion, and it is at both sides. @return the pattern
[ "Pattern", "for", "a", "EntityReference", "has", "a", "member", "PhysicalEntity", "that", "is", "controlling", "a", "state", "change", "reaction", "of", "another", "EntityReference", ".", "This", "pattern", "is", "different", "from", "the", "original", "controls", "-", "state", "-", "change", ".", "The", "controller", "in", "this", "case", "is", "not", "modeled", "as", "a", "controller", "but", "as", "a", "participant", "of", "the", "conversion", "and", "it", "is", "at", "both", "sides", "." ]
train
https://github.com/BioPAX/Paxtools/blob/2f93afa94426bf8b5afc2e0e61cd4b269a83288d/pattern/src/main/java/org/biopax/paxtools/pattern/PatternBox.java#L151-L170
lazy-koala/java-toolkit
fast-toolkit/src/main/java/com/thankjava/toolkit/core/utils/TimeUtil.java
TimeUtil.formatDate
public static String formatDate(TimeType timeType, Date date) { """ 格式化日期 <p>Function: formatDate</p> <p>Description: </p> @param timeType @param date @return @author [email protected] @date 2015年6月18日 上午10:01:09 @version 1.0 """ return getDateFormat(timeType).format(date); }
java
public static String formatDate(TimeType timeType, Date date) { return getDateFormat(timeType).format(date); }
[ "public", "static", "String", "formatDate", "(", "TimeType", "timeType", ",", "Date", "date", ")", "{", "return", "getDateFormat", "(", "timeType", ")", ".", "format", "(", "date", ")", ";", "}" ]
格式化日期 <p>Function: formatDate</p> <p>Description: </p> @param timeType @param date @return @author [email protected] @date 2015年6月18日 上午10:01:09 @version 1.0
[ "格式化日期", "<p", ">", "Function", ":", "formatDate<", "/", "p", ">", "<p", ">", "Description", ":", "<", "/", "p", ">" ]
train
https://github.com/lazy-koala/java-toolkit/blob/f46055fae0cc73049597a3708e515f5c6582d27a/fast-toolkit/src/main/java/com/thankjava/toolkit/core/utils/TimeUtil.java#L86-L88
geomajas/geomajas-project-client-gwt
client/src/main/java/org/geomajas/gwt/client/map/feature/Feature.java
Feature.addOneToManyValue
public void addOneToManyValue(String name, AssociationValue value) { """ Set attribute value of given type. @param name attribute name @param value attribute value """ Attribute attribute = getAttributes().get(name); if (!(attribute instanceof OneToManyAttribute)) { throw new IllegalStateException("Cannot set oneToMany value on attribute with different type, " + attribute.getClass().getName() + " setting value " + value); } OneToManyAttribute oneToMany = (OneToManyAttribute) attribute; if (oneToMany.getValue() == null) { oneToMany.setValue(new ArrayList<AssociationValue>()); } oneToMany.getValue().add(value); }
java
public void addOneToManyValue(String name, AssociationValue value) { Attribute attribute = getAttributes().get(name); if (!(attribute instanceof OneToManyAttribute)) { throw new IllegalStateException("Cannot set oneToMany value on attribute with different type, " + attribute.getClass().getName() + " setting value " + value); } OneToManyAttribute oneToMany = (OneToManyAttribute) attribute; if (oneToMany.getValue() == null) { oneToMany.setValue(new ArrayList<AssociationValue>()); } oneToMany.getValue().add(value); }
[ "public", "void", "addOneToManyValue", "(", "String", "name", ",", "AssociationValue", "value", ")", "{", "Attribute", "attribute", "=", "getAttributes", "(", ")", ".", "get", "(", "name", ")", ";", "if", "(", "!", "(", "attribute", "instanceof", "OneToManyAttribute", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Cannot set oneToMany value on attribute with different type, \"", "+", "attribute", ".", "getClass", "(", ")", ".", "getName", "(", ")", "+", "\" setting value \"", "+", "value", ")", ";", "}", "OneToManyAttribute", "oneToMany", "=", "(", "OneToManyAttribute", ")", "attribute", ";", "if", "(", "oneToMany", ".", "getValue", "(", ")", "==", "null", ")", "{", "oneToMany", ".", "setValue", "(", "new", "ArrayList", "<", "AssociationValue", ">", "(", ")", ")", ";", "}", "oneToMany", ".", "getValue", "(", ")", ".", "add", "(", "value", ")", ";", "}" ]
Set attribute value of given type. @param name attribute name @param value attribute value
[ "Set", "attribute", "value", "of", "given", "type", "." ]
train
https://github.com/geomajas/geomajas-project-client-gwt/blob/1c1adc48deb192ed825265eebcc74d70bbf45670/client/src/main/java/org/geomajas/gwt/client/map/feature/Feature.java#L395-L406
prometheus/client_java
simpleclient_dropwizard/src/main/java/io/prometheus/client/dropwizard/DropwizardExports.java
DropwizardExports.fromSnapshotAndCount
MetricFamilySamples fromSnapshotAndCount(String dropwizardName, Snapshot snapshot, long count, double factor, String helpMessage) { """ Export a histogram snapshot as a prometheus SUMMARY. @param dropwizardName metric name. @param snapshot the histogram snapshot. @param count the total sample count for this snapshot. @param factor a factor to apply to histogram values. """ List<MetricFamilySamples.Sample> samples = Arrays.asList( sampleBuilder.createSample(dropwizardName, "", Arrays.asList("quantile"), Arrays.asList("0.5"), snapshot.getMedian() * factor), sampleBuilder.createSample(dropwizardName, "", Arrays.asList("quantile"), Arrays.asList("0.75"), snapshot.get75thPercentile() * factor), sampleBuilder.createSample(dropwizardName, "", Arrays.asList("quantile"), Arrays.asList("0.95"), snapshot.get95thPercentile() * factor), sampleBuilder.createSample(dropwizardName, "", Arrays.asList("quantile"), Arrays.asList("0.98"), snapshot.get98thPercentile() * factor), sampleBuilder.createSample(dropwizardName, "", Arrays.asList("quantile"), Arrays.asList("0.99"), snapshot.get99thPercentile() * factor), sampleBuilder.createSample(dropwizardName, "", Arrays.asList("quantile"), Arrays.asList("0.999"), snapshot.get999thPercentile() * factor), sampleBuilder.createSample(dropwizardName, "_count", new ArrayList<String>(), new ArrayList<String>(), count) ); return new MetricFamilySamples(samples.get(0).name, Type.SUMMARY, helpMessage, samples); }
java
MetricFamilySamples fromSnapshotAndCount(String dropwizardName, Snapshot snapshot, long count, double factor, String helpMessage) { List<MetricFamilySamples.Sample> samples = Arrays.asList( sampleBuilder.createSample(dropwizardName, "", Arrays.asList("quantile"), Arrays.asList("0.5"), snapshot.getMedian() * factor), sampleBuilder.createSample(dropwizardName, "", Arrays.asList("quantile"), Arrays.asList("0.75"), snapshot.get75thPercentile() * factor), sampleBuilder.createSample(dropwizardName, "", Arrays.asList("quantile"), Arrays.asList("0.95"), snapshot.get95thPercentile() * factor), sampleBuilder.createSample(dropwizardName, "", Arrays.asList("quantile"), Arrays.asList("0.98"), snapshot.get98thPercentile() * factor), sampleBuilder.createSample(dropwizardName, "", Arrays.asList("quantile"), Arrays.asList("0.99"), snapshot.get99thPercentile() * factor), sampleBuilder.createSample(dropwizardName, "", Arrays.asList("quantile"), Arrays.asList("0.999"), snapshot.get999thPercentile() * factor), sampleBuilder.createSample(dropwizardName, "_count", new ArrayList<String>(), new ArrayList<String>(), count) ); return new MetricFamilySamples(samples.get(0).name, Type.SUMMARY, helpMessage, samples); }
[ "MetricFamilySamples", "fromSnapshotAndCount", "(", "String", "dropwizardName", ",", "Snapshot", "snapshot", ",", "long", "count", ",", "double", "factor", ",", "String", "helpMessage", ")", "{", "List", "<", "MetricFamilySamples", ".", "Sample", ">", "samples", "=", "Arrays", ".", "asList", "(", "sampleBuilder", ".", "createSample", "(", "dropwizardName", ",", "\"\"", ",", "Arrays", ".", "asList", "(", "\"quantile\"", ")", ",", "Arrays", ".", "asList", "(", "\"0.5\"", ")", ",", "snapshot", ".", "getMedian", "(", ")", "*", "factor", ")", ",", "sampleBuilder", ".", "createSample", "(", "dropwizardName", ",", "\"\"", ",", "Arrays", ".", "asList", "(", "\"quantile\"", ")", ",", "Arrays", ".", "asList", "(", "\"0.75\"", ")", ",", "snapshot", ".", "get75thPercentile", "(", ")", "*", "factor", ")", ",", "sampleBuilder", ".", "createSample", "(", "dropwizardName", ",", "\"\"", ",", "Arrays", ".", "asList", "(", "\"quantile\"", ")", ",", "Arrays", ".", "asList", "(", "\"0.95\"", ")", ",", "snapshot", ".", "get95thPercentile", "(", ")", "*", "factor", ")", ",", "sampleBuilder", ".", "createSample", "(", "dropwizardName", ",", "\"\"", ",", "Arrays", ".", "asList", "(", "\"quantile\"", ")", ",", "Arrays", ".", "asList", "(", "\"0.98\"", ")", ",", "snapshot", ".", "get98thPercentile", "(", ")", "*", "factor", ")", ",", "sampleBuilder", ".", "createSample", "(", "dropwizardName", ",", "\"\"", ",", "Arrays", ".", "asList", "(", "\"quantile\"", ")", ",", "Arrays", ".", "asList", "(", "\"0.99\"", ")", ",", "snapshot", ".", "get99thPercentile", "(", ")", "*", "factor", ")", ",", "sampleBuilder", ".", "createSample", "(", "dropwizardName", ",", "\"\"", ",", "Arrays", ".", "asList", "(", "\"quantile\"", ")", ",", "Arrays", ".", "asList", "(", "\"0.999\"", ")", ",", "snapshot", ".", "get999thPercentile", "(", ")", "*", "factor", ")", ",", "sampleBuilder", ".", "createSample", "(", "dropwizardName", ",", "\"_count\"", ",", "new", "ArrayList", "<", "String", ">", "(", ")", ",", "new", "ArrayList", "<", "String", ">", "(", ")", ",", "count", ")", ")", ";", "return", "new", "MetricFamilySamples", "(", "samples", ".", "get", "(", "0", ")", ".", "name", ",", "Type", ".", "SUMMARY", ",", "helpMessage", ",", "samples", ")", ";", "}" ]
Export a histogram snapshot as a prometheus SUMMARY. @param dropwizardName metric name. @param snapshot the histogram snapshot. @param count the total sample count for this snapshot. @param factor a factor to apply to histogram values.
[ "Export", "a", "histogram", "snapshot", "as", "a", "prometheus", "SUMMARY", "." ]
train
https://github.com/prometheus/client_java/blob/4e0e7527b048f1ffd0382dcb74c0b9dab23b4d9f/simpleclient_dropwizard/src/main/java/io/prometheus/client/dropwizard/DropwizardExports.java#L86-L97
duracloud/management-console
account-management-monitor/src/main/java/org/duracloud/account/monitor/duplication/DuplicationMonitor.java
DuplicationMonitor.monitorDuplication
public DuplicationReport monitorDuplication() { """ This method performs the duplication checks. These checks compare the number of content items in identically named spaces. @return DuplicationReport report """ log.info("starting duplication monitor"); DuplicationReport report = new DuplicationReport(); for (String host : dupHosts.keySet()) { DuplicationInfo info = new DuplicationInfo(host); try { // Connect to storage providers ContentStoreManager storeManager = getStoreManager(host); ContentStore primary = storeManager.getPrimaryContentStore(); String primaryStoreId = primary.getStoreId(); List<ContentStore> secondaryList = getSecondaryStores(storeManager, primaryStoreId); // Get primary space listing and count List<String> primarySpaces = getSpaces(host, primary); countSpaces(host, info, primary, primarySpaces, true); // Get space listing and space counts for secondary providers for (ContentStore secondary : secondaryList) { List<String> secondarySpaces = getSpaces(host, secondary); if (primarySpaces.size() != secondarySpaces.size()) { info.addIssue("The spaces listings do not match " + "between primary and secondary " + "provider: " + secondary.getStorageProviderType()); } // Determine item count for secondary provider spaces countSpaces(host, info, secondary, secondarySpaces, false); } // Compare the space counts between providers compareSpaces(primaryStoreId, info); } catch (Exception e) { String error = e.getClass() + " exception encountered while " + "running dup monitor for host " + host + ". Exception message: " + e.getMessage(); log.error(error); info.addIssue(error); } finally { report.addDupInfo(host, info); } } return report; }
java
public DuplicationReport monitorDuplication() { log.info("starting duplication monitor"); DuplicationReport report = new DuplicationReport(); for (String host : dupHosts.keySet()) { DuplicationInfo info = new DuplicationInfo(host); try { // Connect to storage providers ContentStoreManager storeManager = getStoreManager(host); ContentStore primary = storeManager.getPrimaryContentStore(); String primaryStoreId = primary.getStoreId(); List<ContentStore> secondaryList = getSecondaryStores(storeManager, primaryStoreId); // Get primary space listing and count List<String> primarySpaces = getSpaces(host, primary); countSpaces(host, info, primary, primarySpaces, true); // Get space listing and space counts for secondary providers for (ContentStore secondary : secondaryList) { List<String> secondarySpaces = getSpaces(host, secondary); if (primarySpaces.size() != secondarySpaces.size()) { info.addIssue("The spaces listings do not match " + "between primary and secondary " + "provider: " + secondary.getStorageProviderType()); } // Determine item count for secondary provider spaces countSpaces(host, info, secondary, secondarySpaces, false); } // Compare the space counts between providers compareSpaces(primaryStoreId, info); } catch (Exception e) { String error = e.getClass() + " exception encountered while " + "running dup monitor for host " + host + ". Exception message: " + e.getMessage(); log.error(error); info.addIssue(error); } finally { report.addDupInfo(host, info); } } return report; }
[ "public", "DuplicationReport", "monitorDuplication", "(", ")", "{", "log", ".", "info", "(", "\"starting duplication monitor\"", ")", ";", "DuplicationReport", "report", "=", "new", "DuplicationReport", "(", ")", ";", "for", "(", "String", "host", ":", "dupHosts", ".", "keySet", "(", ")", ")", "{", "DuplicationInfo", "info", "=", "new", "DuplicationInfo", "(", "host", ")", ";", "try", "{", "// Connect to storage providers", "ContentStoreManager", "storeManager", "=", "getStoreManager", "(", "host", ")", ";", "ContentStore", "primary", "=", "storeManager", ".", "getPrimaryContentStore", "(", ")", ";", "String", "primaryStoreId", "=", "primary", ".", "getStoreId", "(", ")", ";", "List", "<", "ContentStore", ">", "secondaryList", "=", "getSecondaryStores", "(", "storeManager", ",", "primaryStoreId", ")", ";", "// Get primary space listing and count", "List", "<", "String", ">", "primarySpaces", "=", "getSpaces", "(", "host", ",", "primary", ")", ";", "countSpaces", "(", "host", ",", "info", ",", "primary", ",", "primarySpaces", ",", "true", ")", ";", "// Get space listing and space counts for secondary providers", "for", "(", "ContentStore", "secondary", ":", "secondaryList", ")", "{", "List", "<", "String", ">", "secondarySpaces", "=", "getSpaces", "(", "host", ",", "secondary", ")", ";", "if", "(", "primarySpaces", ".", "size", "(", ")", "!=", "secondarySpaces", ".", "size", "(", ")", ")", "{", "info", ".", "addIssue", "(", "\"The spaces listings do not match \"", "+", "\"between primary and secondary \"", "+", "\"provider: \"", "+", "secondary", ".", "getStorageProviderType", "(", ")", ")", ";", "}", "// Determine item count for secondary provider spaces", "countSpaces", "(", "host", ",", "info", ",", "secondary", ",", "secondarySpaces", ",", "false", ")", ";", "}", "// Compare the space counts between providers", "compareSpaces", "(", "primaryStoreId", ",", "info", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "String", "error", "=", "e", ".", "getClass", "(", ")", "+", "\" exception encountered while \"", "+", "\"running dup monitor for host \"", "+", "host", "+", "\". Exception message: \"", "+", "e", ".", "getMessage", "(", ")", ";", "log", ".", "error", "(", "error", ")", ";", "info", ".", "addIssue", "(", "error", ")", ";", "}", "finally", "{", "report", ".", "addDupInfo", "(", "host", ",", "info", ")", ";", "}", "}", "return", "report", ";", "}" ]
This method performs the duplication checks. These checks compare the number of content items in identically named spaces. @return DuplicationReport report
[ "This", "method", "performs", "the", "duplication", "checks", ".", "These", "checks", "compare", "the", "number", "of", "content", "items", "in", "identically", "named", "spaces", "." ]
train
https://github.com/duracloud/management-console/blob/7331015c01f9ac5cc5c0aa8ae9a2a1a77e9f4ac6/account-management-monitor/src/main/java/org/duracloud/account/monitor/duplication/DuplicationMonitor.java#L57-L102
pip-services3-java/pip-services3-commons-java
src/org/pipservices3/commons/reflect/RecursiveObjectWriter.java
RecursiveObjectWriter.setProperties
public static void setProperties(Object obj, Map<String, Object> values) { """ Recursively sets values of some (all) object and its subobjects properties. The object can be a user defined object, map or array. Property values correspondently are object properties, map key-pairs or array elements with their indexes. If some properties do not exist or introspection fails they are just silently skipped and no errors thrown. @param obj an object to write properties to. @param values a map, containing property names and their values. @see #setProperty(Object, String, Object) """ if (values == null || values.size() == 0) return; for (Map.Entry<String, Object> entry : values.entrySet()) { setProperty(obj, entry.getKey(), entry.getValue()); } }
java
public static void setProperties(Object obj, Map<String, Object> values) { if (values == null || values.size() == 0) return; for (Map.Entry<String, Object> entry : values.entrySet()) { setProperty(obj, entry.getKey(), entry.getValue()); } }
[ "public", "static", "void", "setProperties", "(", "Object", "obj", ",", "Map", "<", "String", ",", "Object", ">", "values", ")", "{", "if", "(", "values", "==", "null", "||", "values", ".", "size", "(", ")", "==", "0", ")", "return", ";", "for", "(", "Map", ".", "Entry", "<", "String", ",", "Object", ">", "entry", ":", "values", ".", "entrySet", "(", ")", ")", "{", "setProperty", "(", "obj", ",", "entry", ".", "getKey", "(", ")", ",", "entry", ".", "getValue", "(", ")", ")", ";", "}", "}" ]
Recursively sets values of some (all) object and its subobjects properties. The object can be a user defined object, map or array. Property values correspondently are object properties, map key-pairs or array elements with their indexes. If some properties do not exist or introspection fails they are just silently skipped and no errors thrown. @param obj an object to write properties to. @param values a map, containing property names and their values. @see #setProperty(Object, String, Object)
[ "Recursively", "sets", "values", "of", "some", "(", "all", ")", "object", "and", "its", "subobjects", "properties", "." ]
train
https://github.com/pip-services3-java/pip-services3-commons-java/blob/a8a0c3e5ec58f0663c295aa855c6b3afad2af86a/src/org/pipservices3/commons/reflect/RecursiveObjectWriter.java#L78-L85
pressgang-ccms/PressGangCCMSQuery
src/main/java/org/jboss/pressgang/ccms/filter/utils/JPAUtils.java
JPAUtils.addOrder
public static String addOrder(String queryString, String propertyPath, boolean asc) { """ Add order by clause to queryString @param queryString JPL Query String @param propertyPath Order properti @param asc true if ascending @return JQL Query String with Order clause appened. """ if (StringUtils.containsIgnoreCase(queryString, "order by")) { return queryString; } StringBuilder sb = new StringBuilder(queryString); sb.append(" ORDER BY "); sb.append(getAlias(queryString)); sb.append("."); sb.append(propertyPath); sb.append(" "); sb.append(asc ? "ASC" : "DESC"); return sb.toString(); }
java
public static String addOrder(String queryString, String propertyPath, boolean asc) { if (StringUtils.containsIgnoreCase(queryString, "order by")) { return queryString; } StringBuilder sb = new StringBuilder(queryString); sb.append(" ORDER BY "); sb.append(getAlias(queryString)); sb.append("."); sb.append(propertyPath); sb.append(" "); sb.append(asc ? "ASC" : "DESC"); return sb.toString(); }
[ "public", "static", "String", "addOrder", "(", "String", "queryString", ",", "String", "propertyPath", ",", "boolean", "asc", ")", "{", "if", "(", "StringUtils", ".", "containsIgnoreCase", "(", "queryString", ",", "\"order by\"", ")", ")", "{", "return", "queryString", ";", "}", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", "queryString", ")", ";", "sb", ".", "append", "(", "\" ORDER BY \"", ")", ";", "sb", ".", "append", "(", "getAlias", "(", "queryString", ")", ")", ";", "sb", ".", "append", "(", "\".\"", ")", ";", "sb", ".", "append", "(", "propertyPath", ")", ";", "sb", ".", "append", "(", "\" \"", ")", ";", "sb", ".", "append", "(", "asc", "?", "\"ASC\"", ":", "\"DESC\"", ")", ";", "return", "sb", ".", "toString", "(", ")", ";", "}" ]
Add order by clause to queryString @param queryString JPL Query String @param propertyPath Order properti @param asc true if ascending @return JQL Query String with Order clause appened.
[ "Add", "order", "by", "clause", "to", "queryString" ]
train
https://github.com/pressgang-ccms/PressGangCCMSQuery/blob/2bb23430adab956737d0301cd2ea933f986dd85b/src/main/java/org/jboss/pressgang/ccms/filter/utils/JPAUtils.java#L209-L224
raydac/netbeans-mmd-plugin
mind-map/mind-map-swing-panel/src/main/java/com/igormaznitsa/mindmap/swing/panel/utils/Utils.java
Utils.rescaleImageAndEncodeAsBase64
@Nullable public static String rescaleImageAndEncodeAsBase64(@Nonnull final InputStream in, final int maxSize) throws IOException { """ Load and encode image into Base64. @param in stream to read image @param maxSize max size of image, if less or zero then don't rescale @return null if it was impossible to load image for its format, loaded prepared image @throws IOException if any error during conversion or loading @since 1.4.0 """ final Image image = ImageIO.read(in); String result = null; if (image != null) { result = rescaleImageAndEncodeAsBase64(image, maxSize); } return result; }
java
@Nullable public static String rescaleImageAndEncodeAsBase64(@Nonnull final InputStream in, final int maxSize) throws IOException { final Image image = ImageIO.read(in); String result = null; if (image != null) { result = rescaleImageAndEncodeAsBase64(image, maxSize); } return result; }
[ "@", "Nullable", "public", "static", "String", "rescaleImageAndEncodeAsBase64", "(", "@", "Nonnull", "final", "InputStream", "in", ",", "final", "int", "maxSize", ")", "throws", "IOException", "{", "final", "Image", "image", "=", "ImageIO", ".", "read", "(", "in", ")", ";", "String", "result", "=", "null", ";", "if", "(", "image", "!=", "null", ")", "{", "result", "=", "rescaleImageAndEncodeAsBase64", "(", "image", ",", "maxSize", ")", ";", "}", "return", "result", ";", "}" ]
Load and encode image into Base64. @param in stream to read image @param maxSize max size of image, if less or zero then don't rescale @return null if it was impossible to load image for its format, loaded prepared image @throws IOException if any error during conversion or loading @since 1.4.0
[ "Load", "and", "encode", "image", "into", "Base64", "." ]
train
https://github.com/raydac/netbeans-mmd-plugin/blob/997493d23556a25354372b6419a64a0fbd0ac6ba/mind-map/mind-map-swing-panel/src/main/java/com/igormaznitsa/mindmap/swing/panel/utils/Utils.java#L282-L290
Azure/azure-sdk-for-java
redis/resource-manager/v2018_03_01/src/main/java/com/microsoft/azure/management/redis/v2018_03_01/implementation/PatchSchedulesInner.java
PatchSchedulesInner.listByRedisResourceAsync
public Observable<Page<RedisPatchScheduleInner>> listByRedisResourceAsync(final String resourceGroupName, final String cacheName) { """ Gets all patch schedules in the specified redis cache (there is only one). @param resourceGroupName The name of the resource group. @param cacheName The name of the Redis cache. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;RedisPatchScheduleInner&gt; object """ return listByRedisResourceWithServiceResponseAsync(resourceGroupName, cacheName) .map(new Func1<ServiceResponse<Page<RedisPatchScheduleInner>>, Page<RedisPatchScheduleInner>>() { @Override public Page<RedisPatchScheduleInner> call(ServiceResponse<Page<RedisPatchScheduleInner>> response) { return response.body(); } }); }
java
public Observable<Page<RedisPatchScheduleInner>> listByRedisResourceAsync(final String resourceGroupName, final String cacheName) { return listByRedisResourceWithServiceResponseAsync(resourceGroupName, cacheName) .map(new Func1<ServiceResponse<Page<RedisPatchScheduleInner>>, Page<RedisPatchScheduleInner>>() { @Override public Page<RedisPatchScheduleInner> call(ServiceResponse<Page<RedisPatchScheduleInner>> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Page", "<", "RedisPatchScheduleInner", ">", ">", "listByRedisResourceAsync", "(", "final", "String", "resourceGroupName", ",", "final", "String", "cacheName", ")", "{", "return", "listByRedisResourceWithServiceResponseAsync", "(", "resourceGroupName", ",", "cacheName", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "Page", "<", "RedisPatchScheduleInner", ">", ">", ",", "Page", "<", "RedisPatchScheduleInner", ">", ">", "(", ")", "{", "@", "Override", "public", "Page", "<", "RedisPatchScheduleInner", ">", "call", "(", "ServiceResponse", "<", "Page", "<", "RedisPatchScheduleInner", ">", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Gets all patch schedules in the specified redis cache (there is only one). @param resourceGroupName The name of the resource group. @param cacheName The name of the Redis cache. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;RedisPatchScheduleInner&gt; object
[ "Gets", "all", "patch", "schedules", "in", "the", "specified", "redis", "cache", "(", "there", "is", "only", "one", ")", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/redis/resource-manager/v2018_03_01/src/main/java/com/microsoft/azure/management/redis/v2018_03_01/implementation/PatchSchedulesInner.java#L137-L145
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/photos/PhotosInterface.java
PhotosInterface.setContentType
public void setContentType(String photoId, String contentType) throws FlickrException { """ Set the content type of a photo. This method requires authentication with 'write' permission. @see com.flickr4java.flickr.Flickr#CONTENTTYPE_PHOTO @see com.flickr4java.flickr.Flickr#CONTENTTYPE_SCREENSHOT @see com.flickr4java.flickr.Flickr#CONTENTTYPE_OTHER @param photoId The photo ID @param contentType The contentType to set @throws FlickrException """ Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("method", METHOD_SET_CONTENTTYPE); parameters.put("photo_id", photoId); parameters.put("content_type", contentType); Response response = transport.post(transport.getPath(), parameters, apiKey, sharedSecret); if (response.isError()) { throw new FlickrException(response.getErrorCode(), response.getErrorMessage()); } }
java
public void setContentType(String photoId, String contentType) throws FlickrException { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("method", METHOD_SET_CONTENTTYPE); parameters.put("photo_id", photoId); parameters.put("content_type", contentType); Response response = transport.post(transport.getPath(), parameters, apiKey, sharedSecret); if (response.isError()) { throw new FlickrException(response.getErrorCode(), response.getErrorMessage()); } }
[ "public", "void", "setContentType", "(", "String", "photoId", ",", "String", "contentType", ")", "throws", "FlickrException", "{", "Map", "<", "String", ",", "Object", ">", "parameters", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "parameters", ".", "put", "(", "\"method\"", ",", "METHOD_SET_CONTENTTYPE", ")", ";", "parameters", ".", "put", "(", "\"photo_id\"", ",", "photoId", ")", ";", "parameters", ".", "put", "(", "\"content_type\"", ",", "contentType", ")", ";", "Response", "response", "=", "transport", ".", "post", "(", "transport", ".", "getPath", "(", ")", ",", "parameters", ",", "apiKey", ",", "sharedSecret", ")", ";", "if", "(", "response", ".", "isError", "(", ")", ")", "{", "throw", "new", "FlickrException", "(", "response", ".", "getErrorCode", "(", ")", ",", "response", ".", "getErrorMessage", "(", ")", ")", ";", "}", "}" ]
Set the content type of a photo. This method requires authentication with 'write' permission. @see com.flickr4java.flickr.Flickr#CONTENTTYPE_PHOTO @see com.flickr4java.flickr.Flickr#CONTENTTYPE_SCREENSHOT @see com.flickr4java.flickr.Flickr#CONTENTTYPE_OTHER @param photoId The photo ID @param contentType The contentType to set @throws FlickrException
[ "Set", "the", "content", "type", "of", "a", "photo", "." ]
train
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/photos/PhotosInterface.java#L1136-L1147
networknt/light-4j
metrics/src/main/java/io/dropwizard/metrics/InstrumentedExecutors.java
InstrumentedExecutors.newFixedThreadPool
public static InstrumentedExecutorService newFixedThreadPool( int nThreads, ThreadFactory threadFactory, MetricRegistry registry, String name) { """ Creates an instrumented thread pool that reuses a fixed number of threads operating off a shared unbounded queue, using the provided ThreadFactory to create new threads when needed. At any point, at most {@code nThreads} threads will be active processing tasks. If additional tasks are submitted when all threads are active, they will wait in the queue until a thread is available. If any thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks. The threads in the pool will exist until it is explicitly {@link ExecutorService#shutdown shutdown}. @param nThreads the number of threads in the pool @param threadFactory the factory to use when creating new threads @param registry the {@link MetricRegistry} that will contain the metrics. @param name the (metrics) name for this executor service, see {@link MetricRegistry#name(String, String...)}. @return the newly created thread pool @throws NullPointerException if threadFactory is null @throws IllegalArgumentException if {@code nThreads <= 0} @see Executors#newFixedThreadPool(int, ThreadFactory) """ return new InstrumentedExecutorService(Executors.newFixedThreadPool(nThreads, threadFactory), registry, name); }
java
public static InstrumentedExecutorService newFixedThreadPool( int nThreads, ThreadFactory threadFactory, MetricRegistry registry, String name) { return new InstrumentedExecutorService(Executors.newFixedThreadPool(nThreads, threadFactory), registry, name); }
[ "public", "static", "InstrumentedExecutorService", "newFixedThreadPool", "(", "int", "nThreads", ",", "ThreadFactory", "threadFactory", ",", "MetricRegistry", "registry", ",", "String", "name", ")", "{", "return", "new", "InstrumentedExecutorService", "(", "Executors", ".", "newFixedThreadPool", "(", "nThreads", ",", "threadFactory", ")", ",", "registry", ",", "name", ")", ";", "}" ]
Creates an instrumented thread pool that reuses a fixed number of threads operating off a shared unbounded queue, using the provided ThreadFactory to create new threads when needed. At any point, at most {@code nThreads} threads will be active processing tasks. If additional tasks are submitted when all threads are active, they will wait in the queue until a thread is available. If any thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks. The threads in the pool will exist until it is explicitly {@link ExecutorService#shutdown shutdown}. @param nThreads the number of threads in the pool @param threadFactory the factory to use when creating new threads @param registry the {@link MetricRegistry} that will contain the metrics. @param name the (metrics) name for this executor service, see {@link MetricRegistry#name(String, String...)}. @return the newly created thread pool @throws NullPointerException if threadFactory is null @throws IllegalArgumentException if {@code nThreads <= 0} @see Executors#newFixedThreadPool(int, ThreadFactory)
[ "Creates", "an", "instrumented", "thread", "pool", "that", "reuses", "a", "fixed", "number", "of", "threads", "operating", "off", "a", "shared", "unbounded", "queue", "using", "the", "provided", "ThreadFactory", "to", "create", "new", "threads", "when", "needed", ".", "At", "any", "point", "at", "most", "{", "@code", "nThreads", "}", "threads", "will", "be", "active", "processing", "tasks", ".", "If", "additional", "tasks", "are", "submitted", "when", "all", "threads", "are", "active", "they", "will", "wait", "in", "the", "queue", "until", "a", "thread", "is", "available", ".", "If", "any", "thread", "terminates", "due", "to", "a", "failure", "during", "execution", "prior", "to", "shutdown", "a", "new", "one", "will", "take", "its", "place", "if", "needed", "to", "execute", "subsequent", "tasks", ".", "The", "threads", "in", "the", "pool", "will", "exist", "until", "it", "is", "explicitly", "{", "@link", "ExecutorService#shutdown", "shutdown", "}", "." ]
train
https://github.com/networknt/light-4j/blob/2a60257c60663684c8f6dc8b5ea3cf184e534db6/metrics/src/main/java/io/dropwizard/metrics/InstrumentedExecutors.java#L107-L110
ironjacamar/ironjacamar
core/src/main/java/org/ironjacamar/core/connectionmanager/ccm/Context.java
Context.switchConnectionListener
void switchConnectionListener(Object c, ConnectionListener from, ConnectionListener to) { """ Switch the connection listener for a connection @param c The connection @param from The from connection listener @param to The to connection listener """ if (clToC != null && clToC.get(from) != null && clToC.get(to) != null) { clToC.get(from).remove(c); clToC.get(to).add(c); } }
java
void switchConnectionListener(Object c, ConnectionListener from, ConnectionListener to) { if (clToC != null && clToC.get(from) != null && clToC.get(to) != null) { clToC.get(from).remove(c); clToC.get(to).add(c); } }
[ "void", "switchConnectionListener", "(", "Object", "c", ",", "ConnectionListener", "from", ",", "ConnectionListener", "to", ")", "{", "if", "(", "clToC", "!=", "null", "&&", "clToC", ".", "get", "(", "from", ")", "!=", "null", "&&", "clToC", ".", "get", "(", "to", ")", "!=", "null", ")", "{", "clToC", ".", "get", "(", "from", ")", ".", "remove", "(", "c", ")", ";", "clToC", ".", "get", "(", "to", ")", ".", "add", "(", "c", ")", ";", "}", "}" ]
Switch the connection listener for a connection @param c The connection @param from The from connection listener @param to The to connection listener
[ "Switch", "the", "connection", "listener", "for", "a", "connection" ]
train
https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/core/src/main/java/org/ironjacamar/core/connectionmanager/ccm/Context.java#L164-L171
eurekaclinical/protempa
protempa-framework/src/main/java/org/protempa/graph/Weight.java
Weight.max
public static Weight max(Weight w1, Weight w2) { """ Gets the larger of the two given weights. @param w1 a weight. Cannot be <code>null</code>. @param w2 a weight. Cannot be <code>null</code>. @return a weight. """ if (w1 == null) { throw new IllegalArgumentException("Argument w1 cannot be null"); } if (w2 == null) { throw new IllegalArgumentException("Argument w2 cannot be null"); } if ((w1.isInfinity && w1.posOrNeg) || (w2.isInfinity && !w2.posOrNeg)) { return w1; } else if ((w2.isInfinity && w2.posOrNeg) || (w1.isInfinity && !w1.posOrNeg)) { return w2; } else if (w1.val >= w2.val) { return w1; } else { return w2; } }
java
public static Weight max(Weight w1, Weight w2) { if (w1 == null) { throw new IllegalArgumentException("Argument w1 cannot be null"); } if (w2 == null) { throw new IllegalArgumentException("Argument w2 cannot be null"); } if ((w1.isInfinity && w1.posOrNeg) || (w2.isInfinity && !w2.posOrNeg)) { return w1; } else if ((w2.isInfinity && w2.posOrNeg) || (w1.isInfinity && !w1.posOrNeg)) { return w2; } else if (w1.val >= w2.val) { return w1; } else { return w2; } }
[ "public", "static", "Weight", "max", "(", "Weight", "w1", ",", "Weight", "w2", ")", "{", "if", "(", "w1", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Argument w1 cannot be null\"", ")", ";", "}", "if", "(", "w2", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Argument w2 cannot be null\"", ")", ";", "}", "if", "(", "(", "w1", ".", "isInfinity", "&&", "w1", ".", "posOrNeg", ")", "||", "(", "w2", ".", "isInfinity", "&&", "!", "w2", ".", "posOrNeg", ")", ")", "{", "return", "w1", ";", "}", "else", "if", "(", "(", "w2", ".", "isInfinity", "&&", "w2", ".", "posOrNeg", ")", "||", "(", "w1", ".", "isInfinity", "&&", "!", "w1", ".", "posOrNeg", ")", ")", "{", "return", "w2", ";", "}", "else", "if", "(", "w1", ".", "val", ">=", "w2", ".", "val", ")", "{", "return", "w1", ";", "}", "else", "{", "return", "w2", ";", "}", "}" ]
Gets the larger of the two given weights. @param w1 a weight. Cannot be <code>null</code>. @param w2 a weight. Cannot be <code>null</code>. @return a weight.
[ "Gets", "the", "larger", "of", "the", "two", "given", "weights", "." ]
train
https://github.com/eurekaclinical/protempa/blob/5a620d1a407c7a5426d1cf17d47b97717cf71634/protempa-framework/src/main/java/org/protempa/graph/Weight.java#L280-L297
groundupworks/wings
wings-facebook/src/main/java/com/groundupworks/wings/facebook/FacebookEndpoint.java
FacebookEndpoint.requestAccounts
boolean requestAccounts(Callback callback) { """ Asynchronously requests the Page accounts associated with the linked account. Requires an opened active {@link Session}. @param callback a {@link Callback} when the request completes. @return true if the request is made; false if no opened {@link Session} is active. """ boolean isSuccessful = false; Session session = Session.getActiveSession(); if (session != null && session.isOpened()) { // Construct fields to request. Bundle params = new Bundle(); params.putString(ACCOUNTS_LISTING_FEILDS_KEY, ACCOUNTS_LISTING_FIELDS_VALUE); // Construct and execute albums listing request. Request request = new Request(session, ACCOUNTS_LISTING_GRAPH_PATH, params, HttpMethod.GET, callback); request.executeAsync(); isSuccessful = true; } return isSuccessful; }
java
boolean requestAccounts(Callback callback) { boolean isSuccessful = false; Session session = Session.getActiveSession(); if (session != null && session.isOpened()) { // Construct fields to request. Bundle params = new Bundle(); params.putString(ACCOUNTS_LISTING_FEILDS_KEY, ACCOUNTS_LISTING_FIELDS_VALUE); // Construct and execute albums listing request. Request request = new Request(session, ACCOUNTS_LISTING_GRAPH_PATH, params, HttpMethod.GET, callback); request.executeAsync(); isSuccessful = true; } return isSuccessful; }
[ "boolean", "requestAccounts", "(", "Callback", "callback", ")", "{", "boolean", "isSuccessful", "=", "false", ";", "Session", "session", "=", "Session", ".", "getActiveSession", "(", ")", ";", "if", "(", "session", "!=", "null", "&&", "session", ".", "isOpened", "(", ")", ")", "{", "// Construct fields to request.", "Bundle", "params", "=", "new", "Bundle", "(", ")", ";", "params", ".", "putString", "(", "ACCOUNTS_LISTING_FEILDS_KEY", ",", "ACCOUNTS_LISTING_FIELDS_VALUE", ")", ";", "// Construct and execute albums listing request.", "Request", "request", "=", "new", "Request", "(", "session", ",", "ACCOUNTS_LISTING_GRAPH_PATH", ",", "params", ",", "HttpMethod", ".", "GET", ",", "callback", ")", ";", "request", ".", "executeAsync", "(", ")", ";", "isSuccessful", "=", "true", ";", "}", "return", "isSuccessful", ";", "}" ]
Asynchronously requests the Page accounts associated with the linked account. Requires an opened active {@link Session}. @param callback a {@link Callback} when the request completes. @return true if the request is made; false if no opened {@link Session} is active.
[ "Asynchronously", "requests", "the", "Page", "accounts", "associated", "with", "the", "linked", "account", ".", "Requires", "an", "opened", "active", "{", "@link", "Session", "}", "." ]
train
https://github.com/groundupworks/wings/blob/03d2827c30ef55f2db4e23f7500e016c7771fa39/wings-facebook/src/main/java/com/groundupworks/wings/facebook/FacebookEndpoint.java#L675-L691
OpenLiberty/open-liberty
dev/com.ibm.jbatch.container/src/com/ibm/jbatch/container/ws/JoblogUtil.java
JoblogUtil.logToJobLogAndTraceOnly
@Trivial public static void logToJobLogAndTraceOnly(Level level, String msg, Object[] params, Logger traceLogger) { """ Logs the message to joblog and trace. If level > FINE, this method will reduce the level to FINE while logging to trace to prevent the message to be logged in console.log and messages.log file Joblog messages will be logged as per original logging level Use this method when you don't want a very verbose stack in messages.log and console.log @param level Original logging level the message was logged at by the code writing the log msg. @param msgKey Message key. @param params Message params (fillins) @param traceLogger Logger to use to attempt to log message to trace.log (whether it will or not depends on config) """ String formattedMsg = getFormattedMessage(msg, params, "Job event."); logRawMsgToJobLogAndTraceOnly(level, formattedMsg, traceLogger); }
java
@Trivial public static void logToJobLogAndTraceOnly(Level level, String msg, Object[] params, Logger traceLogger){ String formattedMsg = getFormattedMessage(msg, params, "Job event."); logRawMsgToJobLogAndTraceOnly(level, formattedMsg, traceLogger); }
[ "@", "Trivial", "public", "static", "void", "logToJobLogAndTraceOnly", "(", "Level", "level", ",", "String", "msg", ",", "Object", "[", "]", "params", ",", "Logger", "traceLogger", ")", "{", "String", "formattedMsg", "=", "getFormattedMessage", "(", "msg", ",", "params", ",", "\"Job event.\"", ")", ";", "logRawMsgToJobLogAndTraceOnly", "(", "level", ",", "formattedMsg", ",", "traceLogger", ")", ";", "}" ]
Logs the message to joblog and trace. If level > FINE, this method will reduce the level to FINE while logging to trace to prevent the message to be logged in console.log and messages.log file Joblog messages will be logged as per original logging level Use this method when you don't want a very verbose stack in messages.log and console.log @param level Original logging level the message was logged at by the code writing the log msg. @param msgKey Message key. @param params Message params (fillins) @param traceLogger Logger to use to attempt to log message to trace.log (whether it will or not depends on config)
[ "Logs", "the", "message", "to", "joblog", "and", "trace", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.jbatch.container/src/com/ibm/jbatch/container/ws/JoblogUtil.java#L50-L54
apache/incubator-gobblin
gobblin-restli/gobblin-flow-config-service/gobblin-flow-config-service-server/src/main/java/org/apache/gobblin/service/FlowConfigResourceLocalHandler.java
FlowConfigResourceLocalHandler.createFlowConfig
public CreateResponse createFlowConfig(FlowConfig flowConfig, boolean triggerListener) throws FlowConfigLoggedException { """ Add flowConfig locally and trigger all listeners iff @param triggerListener is set to true """ log.info("[GAAS-REST] Create called with flowGroup " + flowConfig.getId().getFlowGroup() + " flowName " + flowConfig.getId().getFlowName()); if (flowConfig.hasExplain()) { //Return Error if FlowConfig has explain set. Explain request is only valid for v2 FlowConfig. return new CreateResponse(new RestLiServiceException(HttpStatus.S_400_BAD_REQUEST, "FlowConfig with explain not supported.")); } FlowSpec flowSpec = createFlowSpecForConfig(flowConfig); // Existence of a flow spec in the flow catalog implies that the flow is currently running. // If the new flow spec has a schedule we should allow submission of the new flow to accept the new schedule. // However, if the new flow spec does not have a schedule, we should allow submission only if it is not running. if (!flowConfig.hasSchedule() && this.flowCatalog.exists(flowSpec.getUri())) { return new CreateResponse(new ComplexResourceKey<>(flowConfig.getId(), new EmptyRecord()), HttpStatus.S_409_CONFLICT); } else { this.flowCatalog.put(flowSpec, triggerListener); return new CreateResponse(new ComplexResourceKey<>(flowConfig.getId(), new EmptyRecord()), HttpStatus.S_201_CREATED); } }
java
public CreateResponse createFlowConfig(FlowConfig flowConfig, boolean triggerListener) throws FlowConfigLoggedException { log.info("[GAAS-REST] Create called with flowGroup " + flowConfig.getId().getFlowGroup() + " flowName " + flowConfig.getId().getFlowName()); if (flowConfig.hasExplain()) { //Return Error if FlowConfig has explain set. Explain request is only valid for v2 FlowConfig. return new CreateResponse(new RestLiServiceException(HttpStatus.S_400_BAD_REQUEST, "FlowConfig with explain not supported.")); } FlowSpec flowSpec = createFlowSpecForConfig(flowConfig); // Existence of a flow spec in the flow catalog implies that the flow is currently running. // If the new flow spec has a schedule we should allow submission of the new flow to accept the new schedule. // However, if the new flow spec does not have a schedule, we should allow submission only if it is not running. if (!flowConfig.hasSchedule() && this.flowCatalog.exists(flowSpec.getUri())) { return new CreateResponse(new ComplexResourceKey<>(flowConfig.getId(), new EmptyRecord()), HttpStatus.S_409_CONFLICT); } else { this.flowCatalog.put(flowSpec, triggerListener); return new CreateResponse(new ComplexResourceKey<>(flowConfig.getId(), new EmptyRecord()), HttpStatus.S_201_CREATED); } }
[ "public", "CreateResponse", "createFlowConfig", "(", "FlowConfig", "flowConfig", ",", "boolean", "triggerListener", ")", "throws", "FlowConfigLoggedException", "{", "log", ".", "info", "(", "\"[GAAS-REST] Create called with flowGroup \"", "+", "flowConfig", ".", "getId", "(", ")", ".", "getFlowGroup", "(", ")", "+", "\" flowName \"", "+", "flowConfig", ".", "getId", "(", ")", ".", "getFlowName", "(", ")", ")", ";", "if", "(", "flowConfig", ".", "hasExplain", "(", ")", ")", "{", "//Return Error if FlowConfig has explain set. Explain request is only valid for v2 FlowConfig.", "return", "new", "CreateResponse", "(", "new", "RestLiServiceException", "(", "HttpStatus", ".", "S_400_BAD_REQUEST", ",", "\"FlowConfig with explain not supported.\"", ")", ")", ";", "}", "FlowSpec", "flowSpec", "=", "createFlowSpecForConfig", "(", "flowConfig", ")", ";", "// Existence of a flow spec in the flow catalog implies that the flow is currently running.", "// If the new flow spec has a schedule we should allow submission of the new flow to accept the new schedule.", "// However, if the new flow spec does not have a schedule, we should allow submission only if it is not running.", "if", "(", "!", "flowConfig", ".", "hasSchedule", "(", ")", "&&", "this", ".", "flowCatalog", ".", "exists", "(", "flowSpec", ".", "getUri", "(", ")", ")", ")", "{", "return", "new", "CreateResponse", "(", "new", "ComplexResourceKey", "<>", "(", "flowConfig", ".", "getId", "(", ")", ",", "new", "EmptyRecord", "(", ")", ")", ",", "HttpStatus", ".", "S_409_CONFLICT", ")", ";", "}", "else", "{", "this", ".", "flowCatalog", ".", "put", "(", "flowSpec", ",", "triggerListener", ")", ";", "return", "new", "CreateResponse", "(", "new", "ComplexResourceKey", "<>", "(", "flowConfig", ".", "getId", "(", ")", ",", "new", "EmptyRecord", "(", ")", ")", ",", "HttpStatus", ".", "S_201_CREATED", ")", ";", "}", "}" ]
Add flowConfig locally and trigger all listeners iff @param triggerListener is set to true
[ "Add", "flowConfig", "locally", "and", "trigger", "all", "listeners", "iff" ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-restli/gobblin-flow-config-service/gobblin-flow-config-service-server/src/main/java/org/apache/gobblin/service/FlowConfigResourceLocalHandler.java#L109-L127
SonarSource/sonarqube
server/sonar-server/src/main/java/org/sonar/server/qualityprofile/RegisterQualityProfiles.java
RegisterQualityProfiles.renameOutdatedProfiles
private void renameOutdatedProfiles(DbSession dbSession, BuiltInQProfile profile) { """ The Quality profiles created by users should be renamed when they have the same name as the built-in profile to be persisted. <p> When upgrading from < 6.5 , all existing profiles are considered as "custom" (created by users) because the concept of built-in profile is not persisted. The "Sonar way" profiles are renamed to "Sonar way (outdated copy) in order to avoid conflicts with the new built-in profile "Sonar way", which has probably different configuration. """ Collection<String> uuids = dbClient.qualityProfileDao().selectUuidsOfCustomRulesProfiles(dbSession, profile.getLanguage(), profile.getName()); if (uuids.isEmpty()) { return; } Profiler profiler = Profiler.createIfDebug(Loggers.get(getClass())).start(); String newName = profile.getName() + " (outdated copy)"; LOGGER.info("Rename Quality profiles [{}/{}] to [{}] in {} organizations", profile.getLanguage(), profile.getName(), newName, uuids.size()); dbClient.qualityProfileDao().renameRulesProfilesAndCommit(dbSession, uuids, newName); profiler.stopDebug(format("%d Quality profiles renamed to [%s]", uuids.size(), newName)); }
java
private void renameOutdatedProfiles(DbSession dbSession, BuiltInQProfile profile) { Collection<String> uuids = dbClient.qualityProfileDao().selectUuidsOfCustomRulesProfiles(dbSession, profile.getLanguage(), profile.getName()); if (uuids.isEmpty()) { return; } Profiler profiler = Profiler.createIfDebug(Loggers.get(getClass())).start(); String newName = profile.getName() + " (outdated copy)"; LOGGER.info("Rename Quality profiles [{}/{}] to [{}] in {} organizations", profile.getLanguage(), profile.getName(), newName, uuids.size()); dbClient.qualityProfileDao().renameRulesProfilesAndCommit(dbSession, uuids, newName); profiler.stopDebug(format("%d Quality profiles renamed to [%s]", uuids.size(), newName)); }
[ "private", "void", "renameOutdatedProfiles", "(", "DbSession", "dbSession", ",", "BuiltInQProfile", "profile", ")", "{", "Collection", "<", "String", ">", "uuids", "=", "dbClient", ".", "qualityProfileDao", "(", ")", ".", "selectUuidsOfCustomRulesProfiles", "(", "dbSession", ",", "profile", ".", "getLanguage", "(", ")", ",", "profile", ".", "getName", "(", ")", ")", ";", "if", "(", "uuids", ".", "isEmpty", "(", ")", ")", "{", "return", ";", "}", "Profiler", "profiler", "=", "Profiler", ".", "createIfDebug", "(", "Loggers", ".", "get", "(", "getClass", "(", ")", ")", ")", ".", "start", "(", ")", ";", "String", "newName", "=", "profile", ".", "getName", "(", ")", "+", "\" (outdated copy)\"", ";", "LOGGER", ".", "info", "(", "\"Rename Quality profiles [{}/{}] to [{}] in {} organizations\",", " ", "rofile.", "g", "etLanguage(", ")", ",", " ", "rofile.", "g", "etName(", ")", ",", " ", "ewName,", " ", "uids.", "s", "ize(", ")", ")", ";", "", "dbClient", ".", "qualityProfileDao", "(", ")", ".", "renameRulesProfilesAndCommit", "(", "dbSession", ",", "uuids", ",", "newName", ")", ";", "profiler", ".", "stopDebug", "(", "format", "(", "\"%d Quality profiles renamed to [%s]\"", ",", "uuids", ".", "size", "(", ")", ",", "newName", ")", ")", ";", "}" ]
The Quality profiles created by users should be renamed when they have the same name as the built-in profile to be persisted. <p> When upgrading from < 6.5 , all existing profiles are considered as "custom" (created by users) because the concept of built-in profile is not persisted. The "Sonar way" profiles are renamed to "Sonar way (outdated copy) in order to avoid conflicts with the new built-in profile "Sonar way", which has probably different configuration.
[ "The", "Quality", "profiles", "created", "by", "users", "should", "be", "renamed", "when", "they", "have", "the", "same", "name", "as", "the", "built", "-", "in", "profile", "to", "be", "persisted", ".", "<p", ">", "When", "upgrading", "from", "<", "6", ".", "5", "all", "existing", "profiles", "are", "considered", "as", "custom", "(", "created", "by", "users", ")", "because", "the", "concept", "of", "built", "-", "in", "profile", "is", "not", "persisted", ".", "The", "Sonar", "way", "profiles", "are", "renamed", "to", "Sonar", "way", "(", "outdated", "copy", ")", "in", "order", "to", "avoid", "conflicts", "with", "the", "new", "built", "-", "in", "profile", "Sonar", "way", "which", "has", "probably", "different", "configuration", "." ]
train
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/RegisterQualityProfiles.java#L137-L147
UrielCh/ovh-java-sdk
ovh-java-sdk-vps/src/main/java/net/minidev/ovh/api/ApiOvhVps.java
ApiOvhVps.serviceName_snapshot_PUT
public void serviceName_snapshot_PUT(String serviceName, OvhSnapshot body) throws IOException { """ Alter this object properties REST: PUT /vps/{serviceName}/snapshot @param body [required] New object properties @param serviceName [required] The internal name of your VPS offer """ String qPath = "/vps/{serviceName}/snapshot"; StringBuilder sb = path(qPath, serviceName); exec(qPath, "PUT", sb.toString(), body); }
java
public void serviceName_snapshot_PUT(String serviceName, OvhSnapshot body) throws IOException { String qPath = "/vps/{serviceName}/snapshot"; StringBuilder sb = path(qPath, serviceName); exec(qPath, "PUT", sb.toString(), body); }
[ "public", "void", "serviceName_snapshot_PUT", "(", "String", "serviceName", ",", "OvhSnapshot", "body", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/vps/{serviceName}/snapshot\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ")", ";", "exec", "(", "qPath", ",", "\"PUT\"", ",", "sb", ".", "toString", "(", ")", ",", "body", ")", ";", "}" ]
Alter this object properties REST: PUT /vps/{serviceName}/snapshot @param body [required] New object properties @param serviceName [required] The internal name of your VPS offer
[ "Alter", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-vps/src/main/java/net/minidev/ovh/api/ApiOvhVps.java#L1116-L1120
Waikato/moa
moa/src/main/java/moa/gui/visualization/GraphScatter.java
GraphScatter.scatter
private void scatter(Graphics g, int i) { """ Paint a dot onto the panel. @param g graphics object @param i index of the varied parameter """ int height = getHeight(); int width = getWidth(); int x = (int)(((this.variedParamValues[i] - this.lower_x_value) / (this.upper_x_value - this.lower_x_value)) * width); double value = this.measures[i].getLastValue(this.measureSelected); if(Double.isNaN(value)){ // no result for this budget yet return; } int y = (int)(height - (value / this.upper_y_value) * height); g.setColor(this.colors[i]); if (this.isStandardDeviationPainted) { int len = (int) ((this.measureStds[i].getLastValue(this.measureSelected)/this.upper_y_value)*height); paintStandardDeviation(g, len, x, y); } g.fillOval(x - DOT_SIZE/2, y - DOT_SIZE/2, DOT_SIZE, DOT_SIZE); }
java
private void scatter(Graphics g, int i) { int height = getHeight(); int width = getWidth(); int x = (int)(((this.variedParamValues[i] - this.lower_x_value) / (this.upper_x_value - this.lower_x_value)) * width); double value = this.measures[i].getLastValue(this.measureSelected); if(Double.isNaN(value)){ // no result for this budget yet return; } int y = (int)(height - (value / this.upper_y_value) * height); g.setColor(this.colors[i]); if (this.isStandardDeviationPainted) { int len = (int) ((this.measureStds[i].getLastValue(this.measureSelected)/this.upper_y_value)*height); paintStandardDeviation(g, len, x, y); } g.fillOval(x - DOT_SIZE/2, y - DOT_SIZE/2, DOT_SIZE, DOT_SIZE); }
[ "private", "void", "scatter", "(", "Graphics", "g", ",", "int", "i", ")", "{", "int", "height", "=", "getHeight", "(", ")", ";", "int", "width", "=", "getWidth", "(", ")", ";", "int", "x", "=", "(", "int", ")", "(", "(", "(", "this", ".", "variedParamValues", "[", "i", "]", "-", "this", ".", "lower_x_value", ")", "/", "(", "this", ".", "upper_x_value", "-", "this", ".", "lower_x_value", ")", ")", "*", "width", ")", ";", "double", "value", "=", "this", ".", "measures", "[", "i", "]", ".", "getLastValue", "(", "this", ".", "measureSelected", ")", ";", "if", "(", "Double", ".", "isNaN", "(", "value", ")", ")", "{", "// no result for this budget yet", "return", ";", "}", "int", "y", "=", "(", "int", ")", "(", "height", "-", "(", "value", "/", "this", ".", "upper_y_value", ")", "*", "height", ")", ";", "g", ".", "setColor", "(", "this", ".", "colors", "[", "i", "]", ")", ";", "if", "(", "this", ".", "isStandardDeviationPainted", ")", "{", "int", "len", "=", "(", "int", ")", "(", "(", "this", ".", "measureStds", "[", "i", "]", ".", "getLastValue", "(", "this", ".", "measureSelected", ")", "/", "this", ".", "upper_y_value", ")", "*", "height", ")", ";", "paintStandardDeviation", "(", "g", ",", "len", ",", "x", ",", "y", ")", ";", "}", "g", ".", "fillOval", "(", "x", "-", "DOT_SIZE", "/", "2", ",", "y", "-", "DOT_SIZE", "/", "2", ",", "DOT_SIZE", ",", "DOT_SIZE", ")", ";", "}" ]
Paint a dot onto the panel. @param g graphics object @param i index of the varied parameter
[ "Paint", "a", "dot", "onto", "the", "panel", "." ]
train
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/gui/visualization/GraphScatter.java#L76-L100
ops4j/org.ops4j.pax.logging
pax-logging-api/src/main/java/org/apache/logging/log4j/message/MapMessage.java
MapMessage.forEach
public <CV, S> void forEach(final TriConsumer<String, ? super CV, S> action, final S state) { """ Performs the given action for each key-value pair in this data structure until all entries have been processed or the action throws an exception. <p> The third parameter lets callers pass in a stateful object to be modified with the key-value pairs, so the TriConsumer implementation itself can be stateless and potentially reusable. </p> <p> Some implementations may not support structural modifications (adding new elements or removing elements) while iterating over the contents. In such implementations, attempts to add or remove elements from the {@code TriConsumer}'s {@link TriConsumer#accept(Object, Object, Object) accept} method may cause a {@code ConcurrentModificationException} to be thrown. </p> @param action The action to be performed for each key-value pair in this collection @param state the object to be passed as the third parameter to each invocation on the specified triconsumer @param <CV> type of the consumer value @param <S> type of the third parameter @throws java.util.ConcurrentModificationException some implementations may not support structural modifications to this data structure while iterating over the contents with {@link #forEach(BiConsumer)} or {@link #forEach(TriConsumer, Object)}. @see ReadOnlyStringMap#forEach(TriConsumer, Object) @since 2.9 """ data.forEach(action, state); }
java
public <CV, S> void forEach(final TriConsumer<String, ? super CV, S> action, final S state) { data.forEach(action, state); }
[ "public", "<", "CV", ",", "S", ">", "void", "forEach", "(", "final", "TriConsumer", "<", "String", ",", "?", "super", "CV", ",", "S", ">", "action", ",", "final", "S", "state", ")", "{", "data", ".", "forEach", "(", "action", ",", "state", ")", ";", "}" ]
Performs the given action for each key-value pair in this data structure until all entries have been processed or the action throws an exception. <p> The third parameter lets callers pass in a stateful object to be modified with the key-value pairs, so the TriConsumer implementation itself can be stateless and potentially reusable. </p> <p> Some implementations may not support structural modifications (adding new elements or removing elements) while iterating over the contents. In such implementations, attempts to add or remove elements from the {@code TriConsumer}'s {@link TriConsumer#accept(Object, Object, Object) accept} method may cause a {@code ConcurrentModificationException} to be thrown. </p> @param action The action to be performed for each key-value pair in this collection @param state the object to be passed as the third parameter to each invocation on the specified triconsumer @param <CV> type of the consumer value @param <S> type of the third parameter @throws java.util.ConcurrentModificationException some implementations may not support structural modifications to this data structure while iterating over the contents with {@link #forEach(BiConsumer)} or {@link #forEach(TriConsumer, Object)}. @see ReadOnlyStringMap#forEach(TriConsumer, Object) @since 2.9
[ "Performs", "the", "given", "action", "for", "each", "key", "-", "value", "pair", "in", "this", "data", "structure", "until", "all", "entries", "have", "been", "processed", "or", "the", "action", "throws", "an", "exception", ".", "<p", ">", "The", "third", "parameter", "lets", "callers", "pass", "in", "a", "stateful", "object", "to", "be", "modified", "with", "the", "key", "-", "value", "pairs", "so", "the", "TriConsumer", "implementation", "itself", "can", "be", "stateless", "and", "potentially", "reusable", ".", "<", "/", "p", ">", "<p", ">", "Some", "implementations", "may", "not", "support", "structural", "modifications", "(", "adding", "new", "elements", "or", "removing", "elements", ")", "while", "iterating", "over", "the", "contents", ".", "In", "such", "implementations", "attempts", "to", "add", "or", "remove", "elements", "from", "the", "{", "@code", "TriConsumer", "}", "s", "{", "@link", "TriConsumer#accept", "(", "Object", "Object", "Object", ")", "accept", "}", "method", "may", "cause", "a", "{", "@code", "ConcurrentModificationException", "}", "to", "be", "thrown", ".", "<", "/", "p", ">" ]
train
https://github.com/ops4j/org.ops4j.pax.logging/blob/493de4e1db4fe9f981f3dd78b8e40e5bf2b2e59d/pax-logging-api/src/main/java/org/apache/logging/log4j/message/MapMessage.java#L298-L300
alkacon/opencms-core
src/org/opencms/ui/sitemap/CmsLocaleComparePanel.java
CmsLocaleComparePanel.showHeader
private void showHeader() throws CmsException { """ Shows the header for the currently selected sitemap root.<p> @throws CmsException if something goes wrong """ CmsSitemapUI ui = (CmsSitemapUI)A_CmsUI.get(); String title = null; String description = null; String path = null; String locale = m_rootLocale.toString(); CmsObject cms = A_CmsUI.getCmsObject(); CmsResource targetRes = getRoot(); if (targetRes.isFolder()) { targetRes = cms.readDefaultFile(targetRes, CmsResourceFilter.IGNORE_EXPIRATION); if (targetRes == null) { targetRes = getRoot(); } } CmsResourceUtil resUtil = new CmsResourceUtil(cms, getRoot()); title = resUtil.getTitle(); description = resUtil.getGalleryDescription(A_CmsUI.get().getLocale()); path = OpenCms.getLinkManager().getServerLink( cms, cms.getRequestContext().removeSiteRoot(targetRes.getRootPath())); String iconClasses = CmsIconUtil.getIconClasses( CmsIconUtil.getDisplayType(cms, getRoot()), getRoot().getName(), false); ui.getSitemapExtension().showInfoHeader(title, description, path, locale, iconClasses); }
java
private void showHeader() throws CmsException { CmsSitemapUI ui = (CmsSitemapUI)A_CmsUI.get(); String title = null; String description = null; String path = null; String locale = m_rootLocale.toString(); CmsObject cms = A_CmsUI.getCmsObject(); CmsResource targetRes = getRoot(); if (targetRes.isFolder()) { targetRes = cms.readDefaultFile(targetRes, CmsResourceFilter.IGNORE_EXPIRATION); if (targetRes == null) { targetRes = getRoot(); } } CmsResourceUtil resUtil = new CmsResourceUtil(cms, getRoot()); title = resUtil.getTitle(); description = resUtil.getGalleryDescription(A_CmsUI.get().getLocale()); path = OpenCms.getLinkManager().getServerLink( cms, cms.getRequestContext().removeSiteRoot(targetRes.getRootPath())); String iconClasses = CmsIconUtil.getIconClasses( CmsIconUtil.getDisplayType(cms, getRoot()), getRoot().getName(), false); ui.getSitemapExtension().showInfoHeader(title, description, path, locale, iconClasses); }
[ "private", "void", "showHeader", "(", ")", "throws", "CmsException", "{", "CmsSitemapUI", "ui", "=", "(", "CmsSitemapUI", ")", "A_CmsUI", ".", "get", "(", ")", ";", "String", "title", "=", "null", ";", "String", "description", "=", "null", ";", "String", "path", "=", "null", ";", "String", "locale", "=", "m_rootLocale", ".", "toString", "(", ")", ";", "CmsObject", "cms", "=", "A_CmsUI", ".", "getCmsObject", "(", ")", ";", "CmsResource", "targetRes", "=", "getRoot", "(", ")", ";", "if", "(", "targetRes", ".", "isFolder", "(", ")", ")", "{", "targetRes", "=", "cms", ".", "readDefaultFile", "(", "targetRes", ",", "CmsResourceFilter", ".", "IGNORE_EXPIRATION", ")", ";", "if", "(", "targetRes", "==", "null", ")", "{", "targetRes", "=", "getRoot", "(", ")", ";", "}", "}", "CmsResourceUtil", "resUtil", "=", "new", "CmsResourceUtil", "(", "cms", ",", "getRoot", "(", ")", ")", ";", "title", "=", "resUtil", ".", "getTitle", "(", ")", ";", "description", "=", "resUtil", ".", "getGalleryDescription", "(", "A_CmsUI", ".", "get", "(", ")", ".", "getLocale", "(", ")", ")", ";", "path", "=", "OpenCms", ".", "getLinkManager", "(", ")", ".", "getServerLink", "(", "cms", ",", "cms", ".", "getRequestContext", "(", ")", ".", "removeSiteRoot", "(", "targetRes", ".", "getRootPath", "(", ")", ")", ")", ";", "String", "iconClasses", "=", "CmsIconUtil", ".", "getIconClasses", "(", "CmsIconUtil", ".", "getDisplayType", "(", "cms", ",", "getRoot", "(", ")", ")", ",", "getRoot", "(", ")", ".", "getName", "(", ")", ",", "false", ")", ";", "ui", ".", "getSitemapExtension", "(", ")", ".", "showInfoHeader", "(", "title", ",", "description", ",", "path", ",", "locale", ",", "iconClasses", ")", ";", "}" ]
Shows the header for the currently selected sitemap root.<p> @throws CmsException if something goes wrong
[ "Shows", "the", "header", "for", "the", "currently", "selected", "sitemap", "root", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/sitemap/CmsLocaleComparePanel.java#L438-L464
apache/groovy
subprojects/groovy-datetime/src/main/java/org/apache/groovy/datetime/extensions/DateTimeExtensions.java
DateTimeExtensions.offsetFieldValue
private static int offsetFieldValue(ZoneOffset offset, TemporalField field) { """ Returns the value of the provided field for the ZoneOffset as if the ZoneOffset's hours/minutes/seconds were reckoned as a LocalTime. """ int offsetSeconds = offset.getTotalSeconds(); int value = LocalTime.ofSecondOfDay(Math.abs(offsetSeconds)).get(field); return offsetSeconds < 0 ? value * -1 : value; }
java
private static int offsetFieldValue(ZoneOffset offset, TemporalField field) { int offsetSeconds = offset.getTotalSeconds(); int value = LocalTime.ofSecondOfDay(Math.abs(offsetSeconds)).get(field); return offsetSeconds < 0 ? value * -1 : value; }
[ "private", "static", "int", "offsetFieldValue", "(", "ZoneOffset", "offset", ",", "TemporalField", "field", ")", "{", "int", "offsetSeconds", "=", "offset", ".", "getTotalSeconds", "(", ")", ";", "int", "value", "=", "LocalTime", ".", "ofSecondOfDay", "(", "Math", ".", "abs", "(", "offsetSeconds", ")", ")", ".", "get", "(", "field", ")", ";", "return", "offsetSeconds", "<", "0", "?", "value", "*", "-", "1", ":", "value", ";", "}" ]
Returns the value of the provided field for the ZoneOffset as if the ZoneOffset's hours/minutes/seconds were reckoned as a LocalTime.
[ "Returns", "the", "value", "of", "the", "provided", "field", "for", "the", "ZoneOffset", "as", "if", "the", "ZoneOffset", "s", "hours", "/", "minutes", "/", "seconds", "were", "reckoned", "as", "a", "LocalTime", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-datetime/src/main/java/org/apache/groovy/datetime/extensions/DateTimeExtensions.java#L1885-L1889
apptentive/apptentive-android
apptentive/src/main/java/com/apptentive/android/sdk/util/Util.java
Util.getThemeColorFromAttrOrRes
public static int getThemeColorFromAttrOrRes(Context ctx, int attr, int res) { """ helper method to get the color by attr (if defined in the style) or by resource. @param ctx @param attr attribute that defines the color @param res color resource id @return """ int color = getThemeColor(ctx, attr); // If this color is not styled, use the default from the resource if (color == 0) { color = ContextCompat.getColor(ctx, res); } return color; }
java
public static int getThemeColorFromAttrOrRes(Context ctx, int attr, int res) { int color = getThemeColor(ctx, attr); // If this color is not styled, use the default from the resource if (color == 0) { color = ContextCompat.getColor(ctx, res); } return color; }
[ "public", "static", "int", "getThemeColorFromAttrOrRes", "(", "Context", "ctx", ",", "int", "attr", ",", "int", "res", ")", "{", "int", "color", "=", "getThemeColor", "(", "ctx", ",", "attr", ")", ";", "// If this color is not styled, use the default from the resource", "if", "(", "color", "==", "0", ")", "{", "color", "=", "ContextCompat", ".", "getColor", "(", "ctx", ",", "res", ")", ";", "}", "return", "color", ";", "}" ]
helper method to get the color by attr (if defined in the style) or by resource. @param ctx @param attr attribute that defines the color @param res color resource id @return
[ "helper", "method", "to", "get", "the", "color", "by", "attr", "(", "if", "defined", "in", "the", "style", ")", "or", "by", "resource", "." ]
train
https://github.com/apptentive/apptentive-android/blob/887c08d7bd5ae6488a90366dfb58f58938861a93/apptentive/src/main/java/com/apptentive/android/sdk/util/Util.java#L427-L434
katharsis-project/katharsis-framework
katharsis-rs/src/main/java/io/katharsis/rs/JsonApiResponseFilter.java
JsonApiResponseFilter.filter
@Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { """ Creates JSON API responses for custom JAX-RS actions returning Katharsis resources. """ Object response = responseContext.getEntity(); if (response == null) { return; } // only modify responses which contain a single or a list of Katharsis resources if (isResourceResponse(response)) { KatharsisBoot boot = feature.getBoot(); ResourceRegistry resourceRegistry = boot.getResourceRegistry(); DocumentMapper documentMapper = boot.getDocumentMapper(); ServiceUrlProvider serviceUrlProvider = resourceRegistry.getServiceUrlProvider(); try { UriInfo uriInfo = requestContext.getUriInfo(); if (serviceUrlProvider instanceof UriInfoServiceUrlProvider) { ((UriInfoServiceUrlProvider) serviceUrlProvider).onRequestStarted(uriInfo); } JsonApiResponse jsonApiResponse = new JsonApiResponse(); jsonApiResponse.setEntity(response); // use the Katharsis document mapper to create a JSON API response responseContext.setEntity(documentMapper.toDocument(jsonApiResponse, null)); responseContext.getHeaders().put("Content-Type", Arrays.asList((Object)JsonApiMediaType.APPLICATION_JSON_API)); } finally { if (serviceUrlProvider instanceof UriInfoServiceUrlProvider) { ((UriInfoServiceUrlProvider) serviceUrlProvider).onRequestFinished(); } } } }
java
@Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { Object response = responseContext.getEntity(); if (response == null) { return; } // only modify responses which contain a single or a list of Katharsis resources if (isResourceResponse(response)) { KatharsisBoot boot = feature.getBoot(); ResourceRegistry resourceRegistry = boot.getResourceRegistry(); DocumentMapper documentMapper = boot.getDocumentMapper(); ServiceUrlProvider serviceUrlProvider = resourceRegistry.getServiceUrlProvider(); try { UriInfo uriInfo = requestContext.getUriInfo(); if (serviceUrlProvider instanceof UriInfoServiceUrlProvider) { ((UriInfoServiceUrlProvider) serviceUrlProvider).onRequestStarted(uriInfo); } JsonApiResponse jsonApiResponse = new JsonApiResponse(); jsonApiResponse.setEntity(response); // use the Katharsis document mapper to create a JSON API response responseContext.setEntity(documentMapper.toDocument(jsonApiResponse, null)); responseContext.getHeaders().put("Content-Type", Arrays.asList((Object)JsonApiMediaType.APPLICATION_JSON_API)); } finally { if (serviceUrlProvider instanceof UriInfoServiceUrlProvider) { ((UriInfoServiceUrlProvider) serviceUrlProvider).onRequestFinished(); } } } }
[ "@", "Override", "public", "void", "filter", "(", "ContainerRequestContext", "requestContext", ",", "ContainerResponseContext", "responseContext", ")", "throws", "IOException", "{", "Object", "response", "=", "responseContext", ".", "getEntity", "(", ")", ";", "if", "(", "response", "==", "null", ")", "{", "return", ";", "}", "// only modify responses which contain a single or a list of Katharsis resources", "if", "(", "isResourceResponse", "(", "response", ")", ")", "{", "KatharsisBoot", "boot", "=", "feature", ".", "getBoot", "(", ")", ";", "ResourceRegistry", "resourceRegistry", "=", "boot", ".", "getResourceRegistry", "(", ")", ";", "DocumentMapper", "documentMapper", "=", "boot", ".", "getDocumentMapper", "(", ")", ";", "ServiceUrlProvider", "serviceUrlProvider", "=", "resourceRegistry", ".", "getServiceUrlProvider", "(", ")", ";", "try", "{", "UriInfo", "uriInfo", "=", "requestContext", ".", "getUriInfo", "(", ")", ";", "if", "(", "serviceUrlProvider", "instanceof", "UriInfoServiceUrlProvider", ")", "{", "(", "(", "UriInfoServiceUrlProvider", ")", "serviceUrlProvider", ")", ".", "onRequestStarted", "(", "uriInfo", ")", ";", "}", "JsonApiResponse", "jsonApiResponse", "=", "new", "JsonApiResponse", "(", ")", ";", "jsonApiResponse", ".", "setEntity", "(", "response", ")", ";", "// use the Katharsis document mapper to create a JSON API response", "responseContext", ".", "setEntity", "(", "documentMapper", ".", "toDocument", "(", "jsonApiResponse", ",", "null", ")", ")", ";", "responseContext", ".", "getHeaders", "(", ")", ".", "put", "(", "\"Content-Type\"", ",", "Arrays", ".", "asList", "(", "(", "Object", ")", "JsonApiMediaType", ".", "APPLICATION_JSON_API", ")", ")", ";", "}", "finally", "{", "if", "(", "serviceUrlProvider", "instanceof", "UriInfoServiceUrlProvider", ")", "{", "(", "(", "UriInfoServiceUrlProvider", ")", "serviceUrlProvider", ")", ".", "onRequestFinished", "(", ")", ";", "}", "}", "}", "}" ]
Creates JSON API responses for custom JAX-RS actions returning Katharsis resources.
[ "Creates", "JSON", "API", "responses", "for", "custom", "JAX", "-", "RS", "actions", "returning", "Katharsis", "resources", "." ]
train
https://github.com/katharsis-project/katharsis-framework/blob/73d1a8763c49c5cf4643d43e2dbfedb647630c46/katharsis-rs/src/main/java/io/katharsis/rs/JsonApiResponseFilter.java#L37-L70
seam/faces
impl/src/main/java/org/jboss/seam/faces/view/SeamViewHandler.java
SeamViewHandler.getViewDeclarationLanguage
@Override public ViewDeclarationLanguage getViewDeclarationLanguage(FacesContext context, String viewId) { """ If non-null, wrap the {@link ViewDeclarationLanguage} returned by the delegate in a new {@link SeamViewDeclarationLanguage} instance. """ ViewDeclarationLanguage vdl = delegate.getViewDeclarationLanguage(context, viewId); if (vdl != null) { return new SeamViewDeclarationLanguage(vdl); } else { return null; } }
java
@Override public ViewDeclarationLanguage getViewDeclarationLanguage(FacesContext context, String viewId) { ViewDeclarationLanguage vdl = delegate.getViewDeclarationLanguage(context, viewId); if (vdl != null) { return new SeamViewDeclarationLanguage(vdl); } else { return null; } }
[ "@", "Override", "public", "ViewDeclarationLanguage", "getViewDeclarationLanguage", "(", "FacesContext", "context", ",", "String", "viewId", ")", "{", "ViewDeclarationLanguage", "vdl", "=", "delegate", ".", "getViewDeclarationLanguage", "(", "context", ",", "viewId", ")", ";", "if", "(", "vdl", "!=", "null", ")", "{", "return", "new", "SeamViewDeclarationLanguage", "(", "vdl", ")", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
If non-null, wrap the {@link ViewDeclarationLanguage} returned by the delegate in a new {@link SeamViewDeclarationLanguage} instance.
[ "If", "non", "-", "null", "wrap", "the", "{" ]
train
https://github.com/seam/faces/blob/2fdedbc7070318c2c58bfffb8a26f1ea1d0ee1e3/impl/src/main/java/org/jboss/seam/faces/view/SeamViewHandler.java#L42-L50
EdwardRaff/JSAT
JSAT/src/jsat/classifiers/svm/PegasosK.java
PegasosK.setRegularization
public void setRegularization(double regularization) { """ Sets the amount of regularization to apply. The regularization must be a positive value @param regularization the amount of regularization to apply """ if(Double.isNaN(regularization) || Double.isInfinite(regularization) || regularization <= 0) throw new ArithmeticException("Regularization must be a positive constant, not " + regularization); this.regularization = regularization; }
java
public void setRegularization(double regularization) { if(Double.isNaN(regularization) || Double.isInfinite(regularization) || regularization <= 0) throw new ArithmeticException("Regularization must be a positive constant, not " + regularization); this.regularization = regularization; }
[ "public", "void", "setRegularization", "(", "double", "regularization", ")", "{", "if", "(", "Double", ".", "isNaN", "(", "regularization", ")", "||", "Double", ".", "isInfinite", "(", "regularization", ")", "||", "regularization", "<=", "0", ")", "throw", "new", "ArithmeticException", "(", "\"Regularization must be a positive constant, not \"", "+", "regularization", ")", ";", "this", ".", "regularization", "=", "regularization", ";", "}" ]
Sets the amount of regularization to apply. The regularization must be a positive value @param regularization the amount of regularization to apply
[ "Sets", "the", "amount", "of", "regularization", "to", "apply", ".", "The", "regularization", "must", "be", "a", "positive", "value" ]
train
https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/classifiers/svm/PegasosK.java#L107-L112
Whiley/WhileyCompiler
src/main/java/wyil/interpreter/Interpreter.java
Interpreter.executeReturn
private Status executeReturn(Stmt.Return stmt, CallStack frame, EnclosingScope scope) { """ Execute a Return statement at a given point in the function or method body @param stmt --- The return statement to execute @param frame --- The current stack frame @return """ // We know that a return statement can only appear in either a function // or method declaration. It cannot appear, for example, in a type // declaration. Therefore, the enclosing declaration is a function or // method. Decl.Callable context = scope.getEnclosingScope(FunctionOrMethodScope.class).getContext(); Tuple<Decl.Variable> returns = context.getReturns(); RValue[] values = executeExpressions(stmt.getReturns(), frame); for (int i = 0; i != returns.size(); ++i) { frame.putLocal(returns.get(i).getName(), values[i]); } return Status.RETURN; }
java
private Status executeReturn(Stmt.Return stmt, CallStack frame, EnclosingScope scope) { // We know that a return statement can only appear in either a function // or method declaration. It cannot appear, for example, in a type // declaration. Therefore, the enclosing declaration is a function or // method. Decl.Callable context = scope.getEnclosingScope(FunctionOrMethodScope.class).getContext(); Tuple<Decl.Variable> returns = context.getReturns(); RValue[] values = executeExpressions(stmt.getReturns(), frame); for (int i = 0; i != returns.size(); ++i) { frame.putLocal(returns.get(i).getName(), values[i]); } return Status.RETURN; }
[ "private", "Status", "executeReturn", "(", "Stmt", ".", "Return", "stmt", ",", "CallStack", "frame", ",", "EnclosingScope", "scope", ")", "{", "// We know that a return statement can only appear in either a function", "// or method declaration. It cannot appear, for example, in a type", "// declaration. Therefore, the enclosing declaration is a function or", "// method.", "Decl", ".", "Callable", "context", "=", "scope", ".", "getEnclosingScope", "(", "FunctionOrMethodScope", ".", "class", ")", ".", "getContext", "(", ")", ";", "Tuple", "<", "Decl", ".", "Variable", ">", "returns", "=", "context", ".", "getReturns", "(", ")", ";", "RValue", "[", "]", "values", "=", "executeExpressions", "(", "stmt", ".", "getReturns", "(", ")", ",", "frame", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "!=", "returns", ".", "size", "(", ")", ";", "++", "i", ")", "{", "frame", ".", "putLocal", "(", "returns", ".", "get", "(", "i", ")", ".", "getName", "(", ")", ",", "values", "[", "i", "]", ")", ";", "}", "return", "Status", ".", "RETURN", ";", "}" ]
Execute a Return statement at a given point in the function or method body @param stmt --- The return statement to execute @param frame --- The current stack frame @return
[ "Execute", "a", "Return", "statement", "at", "a", "given", "point", "in", "the", "function", "or", "method", "body" ]
train
https://github.com/Whiley/WhileyCompiler/blob/680f8a657d3fc286f8cc422755988b6d74ab3f4c/src/main/java/wyil/interpreter/Interpreter.java#L445-L457
googleapis/google-cloud-java
google-cloud-clients/google-cloud-spanner/src/main/java/com/google/cloud/spanner/Value.java
Value.int64Array
public static Value int64Array(@Nullable long[] v, int pos, int length) { """ Returns an {@code ARRAY<INT64>} value that takes its elements from a region of an array. @param v the source of element values, which may be null to produce a value for which {@code isNull()} is {@code true} @param pos the start position of {@code v} to copy values from. Ignored if {@code v} is {@code null}. @param length the number of values to copy from {@code v}. Ignored if {@code v} is {@code null}. """ return int64ArrayFactory.create(v, pos, length); }
java
public static Value int64Array(@Nullable long[] v, int pos, int length) { return int64ArrayFactory.create(v, pos, length); }
[ "public", "static", "Value", "int64Array", "(", "@", "Nullable", "long", "[", "]", "v", ",", "int", "pos", ",", "int", "length", ")", "{", "return", "int64ArrayFactory", ".", "create", "(", "v", ",", "pos", ",", "length", ")", ";", "}" ]
Returns an {@code ARRAY<INT64>} value that takes its elements from a region of an array. @param v the source of element values, which may be null to produce a value for which {@code isNull()} is {@code true} @param pos the start position of {@code v} to copy values from. Ignored if {@code v} is {@code null}. @param length the number of values to copy from {@code v}. Ignored if {@code v} is {@code null}.
[ "Returns", "an", "{", "@code", "ARRAY<INT64", ">", "}", "value", "that", "takes", "its", "elements", "from", "a", "region", "of", "an", "array", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-spanner/src/main/java/com/google/cloud/spanner/Value.java#L238-L240
apereo/cas
core/cas-server-core-services-api/src/main/java/org/apereo/cas/services/RegisteredServiceAccessStrategyUtils.java
RegisteredServiceAccessStrategyUtils.ensurePrincipalAccessIsAllowedForService
static void ensurePrincipalAccessIsAllowedForService(final Service service, final RegisteredService registeredService, final String principalId, final Map<String, Object> attributes) { """ Ensure principal access is allowed for service. @param service the service @param registeredService the registered service @param principalId the principal id @param attributes the attributes """ ensureServiceAccessIsAllowed(service, registeredService); if (!registeredService.getAccessStrategy().doPrincipalAttributesAllowServiceAccess(principalId, attributes)) { LOGGER.warn("Cannot grant access to service [{}] because it is not authorized for use by [{}].", service.getId(), principalId); val handlerErrors = new HashMap<String, Throwable>(); val message = String.format("Cannot grant service access to %s", principalId); val exception = new UnauthorizedServiceForPrincipalException(message, registeredService, principalId, attributes); handlerErrors.put(UnauthorizedServiceForPrincipalException.class.getSimpleName(), exception); throw new PrincipalException(UnauthorizedServiceForPrincipalException.CODE_UNAUTHZ_SERVICE, handlerErrors, new HashMap<>()); } }
java
static void ensurePrincipalAccessIsAllowedForService(final Service service, final RegisteredService registeredService, final String principalId, final Map<String, Object> attributes) { ensureServiceAccessIsAllowed(service, registeredService); if (!registeredService.getAccessStrategy().doPrincipalAttributesAllowServiceAccess(principalId, attributes)) { LOGGER.warn("Cannot grant access to service [{}] because it is not authorized for use by [{}].", service.getId(), principalId); val handlerErrors = new HashMap<String, Throwable>(); val message = String.format("Cannot grant service access to %s", principalId); val exception = new UnauthorizedServiceForPrincipalException(message, registeredService, principalId, attributes); handlerErrors.put(UnauthorizedServiceForPrincipalException.class.getSimpleName(), exception); throw new PrincipalException(UnauthorizedServiceForPrincipalException.CODE_UNAUTHZ_SERVICE, handlerErrors, new HashMap<>()); } }
[ "static", "void", "ensurePrincipalAccessIsAllowedForService", "(", "final", "Service", "service", ",", "final", "RegisteredService", "registeredService", ",", "final", "String", "principalId", ",", "final", "Map", "<", "String", ",", "Object", ">", "attributes", ")", "{", "ensureServiceAccessIsAllowed", "(", "service", ",", "registeredService", ")", ";", "if", "(", "!", "registeredService", ".", "getAccessStrategy", "(", ")", ".", "doPrincipalAttributesAllowServiceAccess", "(", "principalId", ",", "attributes", ")", ")", "{", "LOGGER", ".", "warn", "(", "\"Cannot grant access to service [{}] because it is not authorized for use by [{}].\"", ",", "service", ".", "getId", "(", ")", ",", "principalId", ")", ";", "val", "handlerErrors", "=", "new", "HashMap", "<", "String", ",", "Throwable", ">", "(", ")", ";", "val", "message", "=", "String", ".", "format", "(", "\"Cannot grant service access to %s\"", ",", "principalId", ")", ";", "val", "exception", "=", "new", "UnauthorizedServiceForPrincipalException", "(", "message", ",", "registeredService", ",", "principalId", ",", "attributes", ")", ";", "handlerErrors", ".", "put", "(", "UnauthorizedServiceForPrincipalException", ".", "class", ".", "getSimpleName", "(", ")", ",", "exception", ")", ";", "throw", "new", "PrincipalException", "(", "UnauthorizedServiceForPrincipalException", ".", "CODE_UNAUTHZ_SERVICE", ",", "handlerErrors", ",", "new", "HashMap", "<>", "(", ")", ")", ";", "}", "}" ]
Ensure principal access is allowed for service. @param service the service @param registeredService the registered service @param principalId the principal id @param attributes the attributes
[ "Ensure", "principal", "access", "is", "allowed", "for", "service", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/core/cas-server-core-services-api/src/main/java/org/apereo/cas/services/RegisteredServiceAccessStrategyUtils.java#L96-L110
threerings/nenya
core/src/main/java/com/threerings/cast/ComponentClass.java
ComponentClass.getRenderPriority
public int getRenderPriority (String action, String component, int orientation) { """ Returns the render priority appropriate for the specified action, orientation and component. """ // because we expect there to be relatively few priority overrides, we simply search // linearly through the list for the closest match int ocount = (_overrides != null) ? _overrides.size() : 0; for (int ii = 0; ii < ocount; ii++) { PriorityOverride over = _overrides.get(ii); // based on the way the overrides are sorted, the first match // is the most specific and the one we want if (over.matches(action, component, orientation)) { return over.renderPriority; } } return renderPriority; }
java
public int getRenderPriority (String action, String component, int orientation) { // because we expect there to be relatively few priority overrides, we simply search // linearly through the list for the closest match int ocount = (_overrides != null) ? _overrides.size() : 0; for (int ii = 0; ii < ocount; ii++) { PriorityOverride over = _overrides.get(ii); // based on the way the overrides are sorted, the first match // is the most specific and the one we want if (over.matches(action, component, orientation)) { return over.renderPriority; } } return renderPriority; }
[ "public", "int", "getRenderPriority", "(", "String", "action", ",", "String", "component", ",", "int", "orientation", ")", "{", "// because we expect there to be relatively few priority overrides, we simply search", "// linearly through the list for the closest match", "int", "ocount", "=", "(", "_overrides", "!=", "null", ")", "?", "_overrides", ".", "size", "(", ")", ":", "0", ";", "for", "(", "int", "ii", "=", "0", ";", "ii", "<", "ocount", ";", "ii", "++", ")", "{", "PriorityOverride", "over", "=", "_overrides", ".", "get", "(", "ii", ")", ";", "// based on the way the overrides are sorted, the first match", "// is the most specific and the one we want", "if", "(", "over", ".", "matches", "(", "action", ",", "component", ",", "orientation", ")", ")", "{", "return", "over", ".", "renderPriority", ";", "}", "}", "return", "renderPriority", ";", "}" ]
Returns the render priority appropriate for the specified action, orientation and component.
[ "Returns", "the", "render", "priority", "appropriate", "for", "the", "specified", "action", "orientation", "and", "component", "." ]
train
https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/cast/ComponentClass.java#L159-L174
OpenLiberty/open-liberty
dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/shared/util/WebConfigParamUtils.java
WebConfigParamUtils.getLongInitParameter
public static long getLongInitParameter(ExternalContext context, String[] names, long defaultValue) { """ Gets the long init parameter value from the specified context. If the parameter was not specified, the default value is used instead. @param context the application's external context @param names the init parameter's names @param defaultValue the default value to return in case the parameter was not set @return the init parameter value as a long @throws NullPointerException if context or name is <code>null</code> """ if (names == null) { throw new NullPointerException(); } String param = null; for (String name : names) { if (name == null) { throw new NullPointerException(); } param = getStringInitParameter(context, name); if (param != null) { break; } } if (param == null) { return defaultValue; } else { return Long.parseLong(param.toLowerCase()); } }
java
public static long getLongInitParameter(ExternalContext context, String[] names, long defaultValue) { if (names == null) { throw new NullPointerException(); } String param = null; for (String name : names) { if (name == null) { throw new NullPointerException(); } param = getStringInitParameter(context, name); if (param != null) { break; } } if (param == null) { return defaultValue; } else { return Long.parseLong(param.toLowerCase()); } }
[ "public", "static", "long", "getLongInitParameter", "(", "ExternalContext", "context", ",", "String", "[", "]", "names", ",", "long", "defaultValue", ")", "{", "if", "(", "names", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", ")", ";", "}", "String", "param", "=", "null", ";", "for", "(", "String", "name", ":", "names", ")", "{", "if", "(", "name", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", ")", ";", "}", "param", "=", "getStringInitParameter", "(", "context", ",", "name", ")", ";", "if", "(", "param", "!=", "null", ")", "{", "break", ";", "}", "}", "if", "(", "param", "==", "null", ")", "{", "return", "defaultValue", ";", "}", "else", "{", "return", "Long", ".", "parseLong", "(", "param", ".", "toLowerCase", "(", ")", ")", ";", "}", "}" ]
Gets the long init parameter value from the specified context. If the parameter was not specified, the default value is used instead. @param context the application's external context @param names the init parameter's names @param defaultValue the default value to return in case the parameter was not set @return the init parameter value as a long @throws NullPointerException if context or name is <code>null</code>
[ "Gets", "the", "long", "init", "parameter", "value", "from", "the", "specified", "context", ".", "If", "the", "parameter", "was", "not", "specified", "the", "default", "value", "is", "used", "instead", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/shared/util/WebConfigParamUtils.java#L638-L667
google/error-prone-javac
src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/util/Utils.java
Utils.makeComparatorForIndexUse
public Comparator<Doc> makeComparatorForIndexUse() { """ A comparator for index file presentations, and are sorted as follows: 1. sort on simple names of entities 2. if equal, then compare the DocKind ex: Package, Interface etc. 3a. if equal and if the type is of ExecutableMemberDoc(Constructor, Methods), a case insensitive comparison of parameter the type signatures 3b. if equal, case sensitive comparison of the type signatures 4. finally, if equal, compare the FQNs of the entities @return a comparator for index file use """ return new Utils.DocComparator<Doc>() { /** * Compare two given Doc entities, first sort on names, then on the kinds, * then on the parameters only if the type is an instance of ExecutableMemberDocs, * the parameters are compared and finally the fully qualified names. * * @param d1 - a Doc element. * @param d2 - a Doc element. * @return a negative integer, zero, or a positive integer as the first * argument is less than, equal to, or greater than the second. */ public int compare(Doc d1, Doc d2) { int result = compareNames(d1, d2); if (result != 0) { return result; } result = compareDocKinds(d1, d2); if (result != 0) { return result; } if (hasParameters(d1)) { Parameter[] param1 = ((ExecutableMemberDoc) d1).parameters(); Parameter[] param2 = ((ExecutableMemberDoc) d2).parameters(); result = compareParameters(false, param1, param2); if (result != 0) { return result; } result = compareParameters(true, param1, param2); if (result != 0) { return result; } } return compareFullyQualifiedNames(d1, d2); } }; }
java
public Comparator<Doc> makeComparatorForIndexUse() { return new Utils.DocComparator<Doc>() { /** * Compare two given Doc entities, first sort on names, then on the kinds, * then on the parameters only if the type is an instance of ExecutableMemberDocs, * the parameters are compared and finally the fully qualified names. * * @param d1 - a Doc element. * @param d2 - a Doc element. * @return a negative integer, zero, or a positive integer as the first * argument is less than, equal to, or greater than the second. */ public int compare(Doc d1, Doc d2) { int result = compareNames(d1, d2); if (result != 0) { return result; } result = compareDocKinds(d1, d2); if (result != 0) { return result; } if (hasParameters(d1)) { Parameter[] param1 = ((ExecutableMemberDoc) d1).parameters(); Parameter[] param2 = ((ExecutableMemberDoc) d2).parameters(); result = compareParameters(false, param1, param2); if (result != 0) { return result; } result = compareParameters(true, param1, param2); if (result != 0) { return result; } } return compareFullyQualifiedNames(d1, d2); } }; }
[ "public", "Comparator", "<", "Doc", ">", "makeComparatorForIndexUse", "(", ")", "{", "return", "new", "Utils", ".", "DocComparator", "<", "Doc", ">", "(", ")", "{", "/**\n * Compare two given Doc entities, first sort on names, then on the kinds,\n * then on the parameters only if the type is an instance of ExecutableMemberDocs,\n * the parameters are compared and finally the fully qualified names.\n *\n * @param d1 - a Doc element.\n * @param d2 - a Doc element.\n * @return a negative integer, zero, or a positive integer as the first\n * argument is less than, equal to, or greater than the second.\n */", "public", "int", "compare", "(", "Doc", "d1", ",", "Doc", "d2", ")", "{", "int", "result", "=", "compareNames", "(", "d1", ",", "d2", ")", ";", "if", "(", "result", "!=", "0", ")", "{", "return", "result", ";", "}", "result", "=", "compareDocKinds", "(", "d1", ",", "d2", ")", ";", "if", "(", "result", "!=", "0", ")", "{", "return", "result", ";", "}", "if", "(", "hasParameters", "(", "d1", ")", ")", "{", "Parameter", "[", "]", "param1", "=", "(", "(", "ExecutableMemberDoc", ")", "d1", ")", ".", "parameters", "(", ")", ";", "Parameter", "[", "]", "param2", "=", "(", "(", "ExecutableMemberDoc", ")", "d2", ")", ".", "parameters", "(", ")", ";", "result", "=", "compareParameters", "(", "false", ",", "param1", ",", "param2", ")", ";", "if", "(", "result", "!=", "0", ")", "{", "return", "result", ";", "}", "result", "=", "compareParameters", "(", "true", ",", "param1", ",", "param2", ")", ";", "if", "(", "result", "!=", "0", ")", "{", "return", "result", ";", "}", "}", "return", "compareFullyQualifiedNames", "(", "d1", ",", "d2", ")", ";", "}", "}", ";", "}" ]
A comparator for index file presentations, and are sorted as follows: 1. sort on simple names of entities 2. if equal, then compare the DocKind ex: Package, Interface etc. 3a. if equal and if the type is of ExecutableMemberDoc(Constructor, Methods), a case insensitive comparison of parameter the type signatures 3b. if equal, case sensitive comparison of the type signatures 4. finally, if equal, compare the FQNs of the entities @return a comparator for index file use
[ "A", "comparator", "for", "index", "file", "presentations", "and", "are", "sorted", "as", "follows", ":", "1", ".", "sort", "on", "simple", "names", "of", "entities", "2", ".", "if", "equal", "then", "compare", "the", "DocKind", "ex", ":", "Package", "Interface", "etc", ".", "3a", ".", "if", "equal", "and", "if", "the", "type", "is", "of", "ExecutableMemberDoc", "(", "Constructor", "Methods", ")", "a", "case", "insensitive", "comparison", "of", "parameter", "the", "type", "signatures", "3b", ".", "if", "equal", "case", "sensitive", "comparison", "of", "the", "type", "signatures", "4", ".", "finally", "if", "equal", "compare", "the", "FQNs", "of", "the", "entities" ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/util/Utils.java#L840-L876
moparisthebest/beehive
beehive-netui-core/src/main/java/org/apache/beehive/netui/util/Bundle.java
Bundle.getString
public static String getString(String aKey, Object arg) { """ Returns the string specified by aKey from the errors.properties bundle. @param aKey The key for the message pattern in the bundle. @param arg The arg to use in the message format. """ return getString(aKey,new Object[]{arg}); }
java
public static String getString(String aKey, Object arg) { return getString(aKey,new Object[]{arg}); }
[ "public", "static", "String", "getString", "(", "String", "aKey", ",", "Object", "arg", ")", "{", "return", "getString", "(", "aKey", ",", "new", "Object", "[", "]", "{", "arg", "}", ")", ";", "}" ]
Returns the string specified by aKey from the errors.properties bundle. @param aKey The key for the message pattern in the bundle. @param arg The arg to use in the message format.
[ "Returns", "the", "string", "specified", "by", "aKey", "from", "the", "errors", ".", "properties", "bundle", "." ]
train
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-core/src/main/java/org/apache/beehive/netui/util/Bundle.java#L66-L69
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/utils/files/FileUtilities.java
FileUtilities.writeFile
public static void writeFile( List<String> lines, File file ) throws IOException { """ Write a list of lines to a file. @param lines the list of lines to write. @param file the file to write to. @throws IOException """ try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) { for( String line : lines ) { bw.write(line); bw.write("\n"); //$NON-NLS-1$ } } }
java
public static void writeFile( List<String> lines, File file ) throws IOException { try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) { for( String line : lines ) { bw.write(line); bw.write("\n"); //$NON-NLS-1$ } } }
[ "public", "static", "void", "writeFile", "(", "List", "<", "String", ">", "lines", ",", "File", "file", ")", "throws", "IOException", "{", "try", "(", "BufferedWriter", "bw", "=", "new", "BufferedWriter", "(", "new", "FileWriter", "(", "file", ")", ")", ")", "{", "for", "(", "String", "line", ":", "lines", ")", "{", "bw", ".", "write", "(", "line", ")", ";", "bw", ".", "write", "(", "\"\\n\"", ")", ";", "//$NON-NLS-1$", "}", "}", "}" ]
Write a list of lines to a file. @param lines the list of lines to write. @param file the file to write to. @throws IOException
[ "Write", "a", "list", "of", "lines", "to", "a", "file", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/files/FileUtilities.java#L245-L252
apereo/cas
support/cas-server-support-saml-mdui/src/main/java/org/apereo/cas/support/saml/mdui/web/flow/SamlMetadataUIParserAction.java
SamlMetadataUIParserAction.loadSamlMetadataIntoRequestContext
protected void loadSamlMetadataIntoRequestContext(final RequestContext requestContext, final String entityId, final RegisteredService registeredService) { """ Load saml metadata into request context. @param requestContext the request context @param entityId the entity id @param registeredService the registered service """ LOGGER.debug("Locating SAML MDUI for entity [{}]", entityId); val mdui = MetadataUIUtils.locateMetadataUserInterfaceForEntityId( this.metadataAdapter, entityId, registeredService, WebUtils.getHttpServletRequestFromExternalWebflowContext(requestContext)); LOGGER.debug("Located SAML MDUI for entity [{}] as [{}]", entityId, mdui); WebUtils.putServiceUserInterfaceMetadata(requestContext, mdui); }
java
protected void loadSamlMetadataIntoRequestContext(final RequestContext requestContext, final String entityId, final RegisteredService registeredService) { LOGGER.debug("Locating SAML MDUI for entity [{}]", entityId); val mdui = MetadataUIUtils.locateMetadataUserInterfaceForEntityId( this.metadataAdapter, entityId, registeredService, WebUtils.getHttpServletRequestFromExternalWebflowContext(requestContext)); LOGGER.debug("Located SAML MDUI for entity [{}] as [{}]", entityId, mdui); WebUtils.putServiceUserInterfaceMetadata(requestContext, mdui); }
[ "protected", "void", "loadSamlMetadataIntoRequestContext", "(", "final", "RequestContext", "requestContext", ",", "final", "String", "entityId", ",", "final", "RegisteredService", "registeredService", ")", "{", "LOGGER", ".", "debug", "(", "\"Locating SAML MDUI for entity [{}]\"", ",", "entityId", ")", ";", "val", "mdui", "=", "MetadataUIUtils", ".", "locateMetadataUserInterfaceForEntityId", "(", "this", ".", "metadataAdapter", ",", "entityId", ",", "registeredService", ",", "WebUtils", ".", "getHttpServletRequestFromExternalWebflowContext", "(", "requestContext", ")", ")", ";", "LOGGER", ".", "debug", "(", "\"Located SAML MDUI for entity [{}] as [{}]\"", ",", "entityId", ",", "mdui", ")", ";", "WebUtils", ".", "putServiceUserInterfaceMetadata", "(", "requestContext", ",", "mdui", ")", ";", "}" ]
Load saml metadata into request context. @param requestContext the request context @param entityId the entity id @param registeredService the registered service
[ "Load", "saml", "metadata", "into", "request", "context", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-saml-mdui/src/main/java/org/apereo/cas/support/saml/mdui/web/flow/SamlMetadataUIParserAction.java#L75-L81
andriusvelykis/reflow-maven-skin
reflow-velocity-tools/src/main/java/lt/velykis/maven/skins/reflow/HtmlTool.java
HtmlTool.adaptSlug
private static String adaptSlug(String input, String separator) { """ Creates a slug but does not change capitalization. @param input @param separator @return """ String nowhitespace = WHITESPACE.matcher(input).replaceAll(separator); String normalized = Normalizer.normalize(nowhitespace, Form.NFD); return NONLATIN.matcher(normalized).replaceAll(""); }
java
private static String adaptSlug(String input, String separator) { String nowhitespace = WHITESPACE.matcher(input).replaceAll(separator); String normalized = Normalizer.normalize(nowhitespace, Form.NFD); return NONLATIN.matcher(normalized).replaceAll(""); }
[ "private", "static", "String", "adaptSlug", "(", "String", "input", ",", "String", "separator", ")", "{", "String", "nowhitespace", "=", "WHITESPACE", ".", "matcher", "(", "input", ")", ".", "replaceAll", "(", "separator", ")", ";", "String", "normalized", "=", "Normalizer", ".", "normalize", "(", "nowhitespace", ",", "Form", ".", "NFD", ")", ";", "return", "NONLATIN", ".", "matcher", "(", "normalized", ")", ".", "replaceAll", "(", "\"\"", ")", ";", "}" ]
Creates a slug but does not change capitalization. @param input @param separator @return
[ "Creates", "a", "slug", "but", "does", "not", "change", "capitalization", "." ]
train
https://github.com/andriusvelykis/reflow-maven-skin/blob/01170ae1426a1adfe7cc9c199e77aaa2ecb37ef2/reflow-velocity-tools/src/main/java/lt/velykis/maven/skins/reflow/HtmlTool.java#L1157-L1161
symphonyoss/messageml-utils
src/main/java/org/symphonyoss/symphony/messageml/util/XmlPrintStream.java
XmlPrintStream.printElement
public void printElement(String name, String value, String... attributes) { """ Output an element with the given content (value). The opening and closing tags are output in a single operation. @param name Name of the element. @param value Contents of the element. @param attributes Alternate names and values of attributes for the element. """ startElement(name, attributes); if (value != null) { println(">" + escape(value) + "</" + name + ">"); } else { println("/>"); } outdent(); }
java
public void printElement(String name, String value, String... attributes) { startElement(name, attributes); if (value != null) { println(">" + escape(value) + "</" + name + ">"); } else { println("/>"); } outdent(); }
[ "public", "void", "printElement", "(", "String", "name", ",", "String", "value", ",", "String", "...", "attributes", ")", "{", "startElement", "(", "name", ",", "attributes", ")", ";", "if", "(", "value", "!=", "null", ")", "{", "println", "(", "\">\"", "+", "escape", "(", "value", ")", "+", "\"</\"", "+", "name", "+", "\">\"", ")", ";", "}", "else", "{", "println", "(", "\"/>\"", ")", ";", "}", "outdent", "(", ")", ";", "}" ]
Output an element with the given content (value). The opening and closing tags are output in a single operation. @param name Name of the element. @param value Contents of the element. @param attributes Alternate names and values of attributes for the element.
[ "Output", "an", "element", "with", "the", "given", "content", "(", "value", ")", ".", "The", "opening", "and", "closing", "tags", "are", "output", "in", "a", "single", "operation", "." ]
train
https://github.com/symphonyoss/messageml-utils/blob/68daed66267062d144a05b3ee9a9bf4b715e3f95/src/main/java/org/symphonyoss/symphony/messageml/util/XmlPrintStream.java#L120-L124
doanduyhai/Achilles
achilles-core/src/main/java/info/archinnov/achilles/internals/dsl/raw/TypedQuery.java
TypedQuery.withResultSetAsyncListener
public TypedQuery<ENTITY> withResultSetAsyncListener(Function<ResultSet, ResultSet> resultSetAsyncListener) { """ Add the given async listener on the {@link com.datastax.driver.core.ResultSet} object. Example of usage: <pre class="code"><code class="java"> .withResultSetAsyncListener(resultSet -> { //Do something with the resultSet object here }) </code></pre> Remark: <strong>it is not allowed to consume the ResultSet values. It is strongly advised to read only meta data</strong> """ this.options.setResultSetAsyncListeners(Optional.of(asList(resultSetAsyncListener))); return this; }
java
public TypedQuery<ENTITY> withResultSetAsyncListener(Function<ResultSet, ResultSet> resultSetAsyncListener) { this.options.setResultSetAsyncListeners(Optional.of(asList(resultSetAsyncListener))); return this; }
[ "public", "TypedQuery", "<", "ENTITY", ">", "withResultSetAsyncListener", "(", "Function", "<", "ResultSet", ",", "ResultSet", ">", "resultSetAsyncListener", ")", "{", "this", ".", "options", ".", "setResultSetAsyncListeners", "(", "Optional", ".", "of", "(", "asList", "(", "resultSetAsyncListener", ")", ")", ")", ";", "return", "this", ";", "}" ]
Add the given async listener on the {@link com.datastax.driver.core.ResultSet} object. Example of usage: <pre class="code"><code class="java"> .withResultSetAsyncListener(resultSet -> { //Do something with the resultSet object here }) </code></pre> Remark: <strong>it is not allowed to consume the ResultSet values. It is strongly advised to read only meta data</strong>
[ "Add", "the", "given", "async", "listener", "on", "the", "{", "@link", "com", ".", "datastax", ".", "driver", ".", "core", ".", "ResultSet", "}", "object", ".", "Example", "of", "usage", ":", "<pre", "class", "=", "code", ">", "<code", "class", "=", "java", ">" ]
train
https://github.com/doanduyhai/Achilles/blob/8281c33100e72c993e570592ae1a5306afac6813/achilles-core/src/main/java/info/archinnov/achilles/internals/dsl/raw/TypedQuery.java#L101-L104
diffplug/durian
src/com/diffplug/common/base/Either.java
Either.acceptBoth
public final void acceptBoth(Consumer<? super L> left, Consumer<? super R> right, L defaultLeft, R defaultRight) { """ Accepts both the left and right consumers, using the default values to set the empty side. """ left.accept(isLeft() ? getLeft() : defaultLeft); right.accept(isRight() ? getRight() : defaultRight); }
java
public final void acceptBoth(Consumer<? super L> left, Consumer<? super R> right, L defaultLeft, R defaultRight) { left.accept(isLeft() ? getLeft() : defaultLeft); right.accept(isRight() ? getRight() : defaultRight); }
[ "public", "final", "void", "acceptBoth", "(", "Consumer", "<", "?", "super", "L", ">", "left", ",", "Consumer", "<", "?", "super", "R", ">", "right", ",", "L", "defaultLeft", ",", "R", "defaultRight", ")", "{", "left", ".", "accept", "(", "isLeft", "(", ")", "?", "getLeft", "(", ")", ":", "defaultLeft", ")", ";", "right", ".", "accept", "(", "isRight", "(", ")", "?", "getRight", "(", ")", ":", "defaultRight", ")", ";", "}" ]
Accepts both the left and right consumers, using the default values to set the empty side.
[ "Accepts", "both", "the", "left", "and", "right", "consumers", "using", "the", "default", "values", "to", "set", "the", "empty", "side", "." ]
train
https://github.com/diffplug/durian/blob/10631a3480e5491eb6eb6ee06e752d8596914232/src/com/diffplug/common/base/Either.java#L104-L107
grails/grails-core
grails-core/src/main/groovy/org/grails/transaction/TransactionManagerPostProcessor.java
TransactionManagerPostProcessor.postProcessAfterInstantiation
@Override public boolean postProcessAfterInstantiation(Object bean, String name) throws BeansException { """ Injects the platform transaction manager into the given bean if that bean implements the {@link grails.transaction.TransactionManagerAware} interface. @param bean The bean to process. @param name The name of the bean. @return The bean after the transaction manager has been injected. @throws BeansException """ if (bean instanceof TransactionManagerAware) { initialize(); if(transactionManager != null) { TransactionManagerAware tma = (TransactionManagerAware) bean; tma.setTransactionManager(transactionManager); } } return true; }
java
@Override public boolean postProcessAfterInstantiation(Object bean, String name) throws BeansException { if (bean instanceof TransactionManagerAware) { initialize(); if(transactionManager != null) { TransactionManagerAware tma = (TransactionManagerAware) bean; tma.setTransactionManager(transactionManager); } } return true; }
[ "@", "Override", "public", "boolean", "postProcessAfterInstantiation", "(", "Object", "bean", ",", "String", "name", ")", "throws", "BeansException", "{", "if", "(", "bean", "instanceof", "TransactionManagerAware", ")", "{", "initialize", "(", ")", ";", "if", "(", "transactionManager", "!=", "null", ")", "{", "TransactionManagerAware", "tma", "=", "(", "TransactionManagerAware", ")", "bean", ";", "tma", ".", "setTransactionManager", "(", "transactionManager", ")", ";", "}", "}", "return", "true", ";", "}" ]
Injects the platform transaction manager into the given bean if that bean implements the {@link grails.transaction.TransactionManagerAware} interface. @param bean The bean to process. @param name The name of the bean. @return The bean after the transaction manager has been injected. @throws BeansException
[ "Injects", "the", "platform", "transaction", "manager", "into", "the", "given", "bean", "if", "that", "bean", "implements", "the", "{" ]
train
https://github.com/grails/grails-core/blob/c0b08aa995b0297143b75d05642abba8cb7b4122/grails-core/src/main/groovy/org/grails/transaction/TransactionManagerPostProcessor.java#L64-L74
ManfredTremmel/gwt-bean-validators
gwtp-spring-integration/src/main/super/de/knightsoftnet/gwtp/spring/supersource/org/springframework/data/domain/Sort.java
Sort.withDirection
private Sort withDirection(final Direction direction) { """ Creates a new {@link Sort} with the current setup but the given order direction. @param direction @return """ return Sort.by(orders.stream().map(it -> new Order(direction, it.getProperty())) .collect(Collectors.toList())); }
java
private Sort withDirection(final Direction direction) { return Sort.by(orders.stream().map(it -> new Order(direction, it.getProperty())) .collect(Collectors.toList())); }
[ "private", "Sort", "withDirection", "(", "final", "Direction", "direction", ")", "{", "return", "Sort", ".", "by", "(", "orders", ".", "stream", "(", ")", ".", "map", "(", "it", "->", "new", "Order", "(", "direction", ",", "it", ".", "getProperty", "(", ")", ")", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ")", ";", "}" ]
Creates a new {@link Sort} with the current setup but the given order direction. @param direction @return
[ "Creates", "a", "new", "{", "@link", "Sort", "}", "with", "the", "current", "setup", "but", "the", "given", "order", "direction", "." ]
train
https://github.com/ManfredTremmel/gwt-bean-validators/blob/cff7a2c3d68c2d17bf9d3cc57c79cc16fa8b4d5c/gwtp-spring-integration/src/main/super/de/knightsoftnet/gwtp/spring/supersource/org/springframework/data/domain/Sort.java#L328-L332
hawkular/hawkular-commons
hawkular-command-gateway/hawkular-command-gateway-war/src/main/java/org/hawkular/cmdgw/command/ws/server/AbstractGatewayWebSocket.java
AbstractGatewayWebSocket.onMessage
@OnMessage public void onMessage(String nameAndJsonStr, Session session) { """ When a message is received from a WebSocket client, this method will lookup the {@link WsCommand} for the given request class and execute it. @param nameAndJsonStr the name of the API request followed by "=" followed then by the request's JSON data @param session the client session making the request """ String requestClassName = "?"; try { // parse the JSON and get its message POJO BasicMessageWithExtraData<BasicMessage> request = new ApiDeserializer().deserialize(nameAndJsonStr); requestClassName = request.getBasicMessage().getClass().getName(); log.infoReceivedWsMessage(requestClassName, session.getId(), endpoint); handleRequest(session, request); } catch (Throwable t) { log.errorWsCommandExecutionFailure(requestClassName, session.getId(), endpoint, t); String errorMessage = "Failed to process message [" + requestClassName + "]"; sendErrorResponse(session, errorMessage, t); } }
java
@OnMessage public void onMessage(String nameAndJsonStr, Session session) { String requestClassName = "?"; try { // parse the JSON and get its message POJO BasicMessageWithExtraData<BasicMessage> request = new ApiDeserializer().deserialize(nameAndJsonStr); requestClassName = request.getBasicMessage().getClass().getName(); log.infoReceivedWsMessage(requestClassName, session.getId(), endpoint); handleRequest(session, request); } catch (Throwable t) { log.errorWsCommandExecutionFailure(requestClassName, session.getId(), endpoint, t); String errorMessage = "Failed to process message [" + requestClassName + "]"; sendErrorResponse(session, errorMessage, t); } }
[ "@", "OnMessage", "public", "void", "onMessage", "(", "String", "nameAndJsonStr", ",", "Session", "session", ")", "{", "String", "requestClassName", "=", "\"?\"", ";", "try", "{", "// parse the JSON and get its message POJO", "BasicMessageWithExtraData", "<", "BasicMessage", ">", "request", "=", "new", "ApiDeserializer", "(", ")", ".", "deserialize", "(", "nameAndJsonStr", ")", ";", "requestClassName", "=", "request", ".", "getBasicMessage", "(", ")", ".", "getClass", "(", ")", ".", "getName", "(", ")", ";", "log", ".", "infoReceivedWsMessage", "(", "requestClassName", ",", "session", ".", "getId", "(", ")", ",", "endpoint", ")", ";", "handleRequest", "(", "session", ",", "request", ")", ";", "}", "catch", "(", "Throwable", "t", ")", "{", "log", ".", "errorWsCommandExecutionFailure", "(", "requestClassName", ",", "session", ".", "getId", "(", ")", ",", "endpoint", ",", "t", ")", ";", "String", "errorMessage", "=", "\"Failed to process message [\"", "+", "requestClassName", "+", "\"]\"", ";", "sendErrorResponse", "(", "session", ",", "errorMessage", ",", "t", ")", ";", "}", "}" ]
When a message is received from a WebSocket client, this method will lookup the {@link WsCommand} for the given request class and execute it. @param nameAndJsonStr the name of the API request followed by "=" followed then by the request's JSON data @param session the client session making the request
[ "When", "a", "message", "is", "received", "from", "a", "WebSocket", "client", "this", "method", "will", "lookup", "the", "{", "@link", "WsCommand", "}", "for", "the", "given", "request", "class", "and", "execute", "it", "." ]
train
https://github.com/hawkular/hawkular-commons/blob/e4a832862b3446d7f4d629bb05790f2df578e035/hawkular-command-gateway/hawkular-command-gateway-war/src/main/java/org/hawkular/cmdgw/command/ws/server/AbstractGatewayWebSocket.java#L140-L156
elki-project/elki
elki-core/src/main/java/de/lmu/ifi/dbs/elki/result/ResultUtil.java
ResultUtil.removeRecursive
public static void removeRecursive(ResultHierarchy hierarchy, Result child) { """ Recursively remove a result and its children. @param hierarchy Result hierarchy @param child Result to remove """ for(It<Result> iter = hierarchy.iterParents(child); iter.valid(); iter.advance()) { hierarchy.remove(iter.get(), child); } for(It<Result> iter = hierarchy.iterChildren(child); iter.valid(); iter.advance()) { removeRecursive(hierarchy, iter.get()); } }
java
public static void removeRecursive(ResultHierarchy hierarchy, Result child) { for(It<Result> iter = hierarchy.iterParents(child); iter.valid(); iter.advance()) { hierarchy.remove(iter.get(), child); } for(It<Result> iter = hierarchy.iterChildren(child); iter.valid(); iter.advance()) { removeRecursive(hierarchy, iter.get()); } }
[ "public", "static", "void", "removeRecursive", "(", "ResultHierarchy", "hierarchy", ",", "Result", "child", ")", "{", "for", "(", "It", "<", "Result", ">", "iter", "=", "hierarchy", ".", "iterParents", "(", "child", ")", ";", "iter", ".", "valid", "(", ")", ";", "iter", ".", "advance", "(", ")", ")", "{", "hierarchy", ".", "remove", "(", "iter", ".", "get", "(", ")", ",", "child", ")", ";", "}", "for", "(", "It", "<", "Result", ">", "iter", "=", "hierarchy", ".", "iterChildren", "(", "child", ")", ";", "iter", ".", "valid", "(", ")", ";", "iter", ".", "advance", "(", ")", ")", "{", "removeRecursive", "(", "hierarchy", ",", "iter", ".", "get", "(", ")", ")", ";", "}", "}" ]
Recursively remove a result and its children. @param hierarchy Result hierarchy @param child Result to remove
[ "Recursively", "remove", "a", "result", "and", "its", "children", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core/src/main/java/de/lmu/ifi/dbs/elki/result/ResultUtil.java#L188-L195
twilio/authy-java
src/main/java/com/authy/AuthyUtil.java
AuthyUtil.validateSignatureForPost
public static boolean validateSignatureForPost(String body, Map<String, String> headers, String url, String apiKey) throws OneTouchException, UnsupportedEncodingException { """ Validates the request information to @param body The body of the request in case of a POST method @param headers The headers of the request @param url The url of the request. @param apiKey the security token from the authy library @return true if the signature ios valid, false otherwise @throws com.authy.OneTouchException @throws UnsupportedEncodingException if the string parameters have problems with UTF-8 encoding. """ HashMap<String, String> params = new HashMap<>(); if (body == null || body.isEmpty()) throw new OneTouchException("'PARAMS' are missing."); extract("", new JSONObject(body), params); return validateSignature(params, headers, "POST", url, apiKey); }
java
public static boolean validateSignatureForPost(String body, Map<String, String> headers, String url, String apiKey) throws OneTouchException, UnsupportedEncodingException { HashMap<String, String> params = new HashMap<>(); if (body == null || body.isEmpty()) throw new OneTouchException("'PARAMS' are missing."); extract("", new JSONObject(body), params); return validateSignature(params, headers, "POST", url, apiKey); }
[ "public", "static", "boolean", "validateSignatureForPost", "(", "String", "body", ",", "Map", "<", "String", ",", "String", ">", "headers", ",", "String", "url", ",", "String", "apiKey", ")", "throws", "OneTouchException", ",", "UnsupportedEncodingException", "{", "HashMap", "<", "String", ",", "String", ">", "params", "=", "new", "HashMap", "<>", "(", ")", ";", "if", "(", "body", "==", "null", "||", "body", ".", "isEmpty", "(", ")", ")", "throw", "new", "OneTouchException", "(", "\"'PARAMS' are missing.\"", ")", ";", "extract", "(", "\"\"", ",", "new", "JSONObject", "(", "body", ")", ",", "params", ")", ";", "return", "validateSignature", "(", "params", ",", "headers", ",", "\"POST\"", ",", "url", ",", "apiKey", ")", ";", "}" ]
Validates the request information to @param body The body of the request in case of a POST method @param headers The headers of the request @param url The url of the request. @param apiKey the security token from the authy library @return true if the signature ios valid, false otherwise @throws com.authy.OneTouchException @throws UnsupportedEncodingException if the string parameters have problems with UTF-8 encoding.
[ "Validates", "the", "request", "information", "to" ]
train
https://github.com/twilio/authy-java/blob/55e3a5ff57a93b3eb36f5b59e8824e60af2b8b91/src/main/java/com/authy/AuthyUtil.java#L183-L189
beihaifeiwu/dolphin
dolphin-common/src/main/java/com/freetmp/common/annotation/AnnotationUtils.java
AnnotationUtils.isAnnotationDeclaredLocally
public static boolean isAnnotationDeclaredLocally(Class<? extends Annotation> annotationType, Class<?> clazz) { """ Determine whether an annotation for the specified {@code annotationType} is declared locally on the supplied {@code clazz}. The supplied {@link Class} may represent any type. <p>Note: This method does <strong>not</strong> determine if the annotation is {@linkplain java.lang.annotation.Inherited inherited}. For greater clarity regarding inherited annotations, consider using {@link #isAnnotationInherited(Class, Class)} instead. @param annotationType the Class object corresponding to the annotation type @param clazz the Class object corresponding to the class on which to check for the annotation @return {@code true} if an annotation for the specified {@code annotationType} is declared locally on the supplied {@code clazz} @see Class#getDeclaredAnnotations() @see #isAnnotationInherited(Class, Class) """ Assert.notNull(annotationType, "Annotation type must not be null"); Assert.notNull(clazz, "Class must not be null"); boolean declaredLocally = false; try { for (Annotation ann : clazz.getDeclaredAnnotations()) { if (ann.annotationType().equals(annotationType)) { declaredLocally = true; break; } } } catch (Exception ex) { // Assuming nested Class values not resolvable within annotation attributes... logIntrospectionFailure(clazz, ex); } return declaredLocally; }
java
public static boolean isAnnotationDeclaredLocally(Class<? extends Annotation> annotationType, Class<?> clazz) { Assert.notNull(annotationType, "Annotation type must not be null"); Assert.notNull(clazz, "Class must not be null"); boolean declaredLocally = false; try { for (Annotation ann : clazz.getDeclaredAnnotations()) { if (ann.annotationType().equals(annotationType)) { declaredLocally = true; break; } } } catch (Exception ex) { // Assuming nested Class values not resolvable within annotation attributes... logIntrospectionFailure(clazz, ex); } return declaredLocally; }
[ "public", "static", "boolean", "isAnnotationDeclaredLocally", "(", "Class", "<", "?", "extends", "Annotation", ">", "annotationType", ",", "Class", "<", "?", ">", "clazz", ")", "{", "Assert", ".", "notNull", "(", "annotationType", ",", "\"Annotation type must not be null\"", ")", ";", "Assert", ".", "notNull", "(", "clazz", ",", "\"Class must not be null\"", ")", ";", "boolean", "declaredLocally", "=", "false", ";", "try", "{", "for", "(", "Annotation", "ann", ":", "clazz", ".", "getDeclaredAnnotations", "(", ")", ")", "{", "if", "(", "ann", ".", "annotationType", "(", ")", ".", "equals", "(", "annotationType", ")", ")", "{", "declaredLocally", "=", "true", ";", "break", ";", "}", "}", "}", "catch", "(", "Exception", "ex", ")", "{", "// Assuming nested Class values not resolvable within annotation attributes...", "logIntrospectionFailure", "(", "clazz", ",", "ex", ")", ";", "}", "return", "declaredLocally", ";", "}" ]
Determine whether an annotation for the specified {@code annotationType} is declared locally on the supplied {@code clazz}. The supplied {@link Class} may represent any type. <p>Note: This method does <strong>not</strong> determine if the annotation is {@linkplain java.lang.annotation.Inherited inherited}. For greater clarity regarding inherited annotations, consider using {@link #isAnnotationInherited(Class, Class)} instead. @param annotationType the Class object corresponding to the annotation type @param clazz the Class object corresponding to the class on which to check for the annotation @return {@code true} if an annotation for the specified {@code annotationType} is declared locally on the supplied {@code clazz} @see Class#getDeclaredAnnotations() @see #isAnnotationInherited(Class, Class)
[ "Determine", "whether", "an", "annotation", "for", "the", "specified", "{" ]
train
https://github.com/beihaifeiwu/dolphin/blob/b100579cc6986dce5eba5593ebb5fbae7bad9d1a/dolphin-common/src/main/java/com/freetmp/common/annotation/AnnotationUtils.java#L471-L488
Azure/azure-sdk-for-java
iothub/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/iothub/v2018_04_01/implementation/IotHubResourcesInner.java
IotHubResourcesInner.getKeysForKeyName
public SharedAccessSignatureAuthorizationRuleInner getKeysForKeyName(String resourceGroupName, String resourceName, String keyName) { """ Get a shared access policy by name from an IoT hub. For more information, see: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-security. Get a shared access policy by name from an IoT hub. For more information, see: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-security. @param resourceGroupName The name of the resource group that contains the IoT hub. @param resourceName The name of the IoT hub. @param keyName The name of the shared access policy. @throws IllegalArgumentException thrown if parameters fail the validation @throws ErrorDetailsException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the SharedAccessSignatureAuthorizationRuleInner object if successful. """ return getKeysForKeyNameWithServiceResponseAsync(resourceGroupName, resourceName, keyName).toBlocking().single().body(); }
java
public SharedAccessSignatureAuthorizationRuleInner getKeysForKeyName(String resourceGroupName, String resourceName, String keyName) { return getKeysForKeyNameWithServiceResponseAsync(resourceGroupName, resourceName, keyName).toBlocking().single().body(); }
[ "public", "SharedAccessSignatureAuthorizationRuleInner", "getKeysForKeyName", "(", "String", "resourceGroupName", ",", "String", "resourceName", ",", "String", "keyName", ")", "{", "return", "getKeysForKeyNameWithServiceResponseAsync", "(", "resourceGroupName", ",", "resourceName", ",", "keyName", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Get a shared access policy by name from an IoT hub. For more information, see: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-security. Get a shared access policy by name from an IoT hub. For more information, see: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-security. @param resourceGroupName The name of the resource group that contains the IoT hub. @param resourceName The name of the IoT hub. @param keyName The name of the shared access policy. @throws IllegalArgumentException thrown if parameters fail the validation @throws ErrorDetailsException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the SharedAccessSignatureAuthorizationRuleInner object if successful.
[ "Get", "a", "shared", "access", "policy", "by", "name", "from", "an", "IoT", "hub", ".", "For", "more", "information", "see", ":", "https", ":", "//", "docs", ".", "microsoft", ".", "com", "/", "azure", "/", "iot", "-", "hub", "/", "iot", "-", "hub", "-", "devguide", "-", "security", ".", "Get", "a", "shared", "access", "policy", "by", "name", "from", "an", "IoT", "hub", ".", "For", "more", "information", "see", ":", "https", ":", "//", "docs", ".", "microsoft", ".", "com", "/", "azure", "/", "iot", "-", "hub", "/", "iot", "-", "hub", "-", "devguide", "-", "security", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/iothub/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/iothub/v2018_04_01/implementation/IotHubResourcesInner.java#L2970-L2972
ralscha/extclassgenerator
src/main/java/ch/rasc/extclassgenerator/ModelGenerator.java
ModelGenerator.createModel
public static ModelBean createModel(Class<?> clazz, IncludeValidation includeValidation) { """ Instrospects the provided class and creates a {@link ModelBean} instance. A program could customize this and call {@link #generateJavascript(ModelBean, OutputFormat, boolean)} or {@link #writeModel(HttpServletRequest, HttpServletResponse, ModelBean, OutputFormat)} to create the JS code. Models are being cached. A second call with the same parameters will return the model from the cache. @param clazz the model will be created based on this class. @param includeValidation specifies what validation configuration should be added @return a instance of {@link ModelBean} that describes the provided class and can be used for Javascript generation. """ OutputConfig outputConfig = new OutputConfig(); outputConfig.setIncludeValidation(includeValidation); return createModel(clazz, outputConfig); }
java
public static ModelBean createModel(Class<?> clazz, IncludeValidation includeValidation) { OutputConfig outputConfig = new OutputConfig(); outputConfig.setIncludeValidation(includeValidation); return createModel(clazz, outputConfig); }
[ "public", "static", "ModelBean", "createModel", "(", "Class", "<", "?", ">", "clazz", ",", "IncludeValidation", "includeValidation", ")", "{", "OutputConfig", "outputConfig", "=", "new", "OutputConfig", "(", ")", ";", "outputConfig", ".", "setIncludeValidation", "(", "includeValidation", ")", ";", "return", "createModel", "(", "clazz", ",", "outputConfig", ")", ";", "}" ]
Instrospects the provided class and creates a {@link ModelBean} instance. A program could customize this and call {@link #generateJavascript(ModelBean, OutputFormat, boolean)} or {@link #writeModel(HttpServletRequest, HttpServletResponse, ModelBean, OutputFormat)} to create the JS code. Models are being cached. A second call with the same parameters will return the model from the cache. @param clazz the model will be created based on this class. @param includeValidation specifies what validation configuration should be added @return a instance of {@link ModelBean} that describes the provided class and can be used for Javascript generation.
[ "Instrospects", "the", "provided", "class", "and", "creates", "a", "{", "@link", "ModelBean", "}", "instance", ".", "A", "program", "could", "customize", "this", "and", "call", "{", "@link", "#generateJavascript", "(", "ModelBean", "OutputFormat", "boolean", ")", "}", "or", "{", "@link", "#writeModel", "(", "HttpServletRequest", "HttpServletResponse", "ModelBean", "OutputFormat", ")", "}", "to", "create", "the", "JS", "code", ".", "Models", "are", "being", "cached", ".", "A", "second", "call", "with", "the", "same", "parameters", "will", "return", "the", "model", "from", "the", "cache", "." ]
train
https://github.com/ralscha/extclassgenerator/blob/6f106cf5ca83ef004225a3512e2291dfd028cf07/src/main/java/ch/rasc/extclassgenerator/ModelGenerator.java#L212-L217
Bandwidth/java-bandwidth
src/main/java/com/bandwidth/sdk/model/Error.java
Error.get
public static Error get(final BandwidthClient client, final String id) throws Exception { """ Factory method for Error. Returns Error object from id. @param client the client @param id error id @return information about one user error @throws IOException unexpected error. """ final String errorsUri = client.getUserResourceInstanceUri(BandwidthConstants.ERRORS_URI_PATH, id); final JSONObject jsonObject = toJSONObject(client.get(errorsUri, null)); return new Error(client, errorsUri, jsonObject); }
java
public static Error get(final BandwidthClient client, final String id) throws Exception { final String errorsUri = client.getUserResourceInstanceUri(BandwidthConstants.ERRORS_URI_PATH, id); final JSONObject jsonObject = toJSONObject(client.get(errorsUri, null)); return new Error(client, errorsUri, jsonObject); }
[ "public", "static", "Error", "get", "(", "final", "BandwidthClient", "client", ",", "final", "String", "id", ")", "throws", "Exception", "{", "final", "String", "errorsUri", "=", "client", ".", "getUserResourceInstanceUri", "(", "BandwidthConstants", ".", "ERRORS_URI_PATH", ",", "id", ")", ";", "final", "JSONObject", "jsonObject", "=", "toJSONObject", "(", "client", ".", "get", "(", "errorsUri", ",", "null", ")", ")", ";", "return", "new", "Error", "(", "client", ",", "errorsUri", ",", "jsonObject", ")", ";", "}" ]
Factory method for Error. Returns Error object from id. @param client the client @param id error id @return information about one user error @throws IOException unexpected error.
[ "Factory", "method", "for", "Error", ".", "Returns", "Error", "object", "from", "id", "." ]
train
https://github.com/Bandwidth/java-bandwidth/blob/2124c85148ad6a54d2f2949cb952eb3985830e2a/src/main/java/com/bandwidth/sdk/model/Error.java#L38-L43
UrielCh/ovh-java-sdk
ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java
ApiOvhTelephony.billingAccount_outplanNotification_POST
public OvhConsumptionThreshold billingAccount_outplanNotification_POST(String billingAccount, OvhOutplanNotificationBlockEnum block, String notifyEmail, Double percentage) throws IOException { """ Add an outplan notification on the billing account REST: POST /telephony/{billingAccount}/outplanNotification @param percentage [required] The notification percentage of maximum outplan @param block [required] The blocking type of the associate lines @param notifyEmail [required] Override the nichandle email for this notification @param billingAccount [required] The name of your billingAccount """ String qPath = "/telephony/{billingAccount}/outplanNotification"; StringBuilder sb = path(qPath, billingAccount); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "block", block); addBody(o, "notifyEmail", notifyEmail); addBody(o, "percentage", percentage); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhConsumptionThreshold.class); }
java
public OvhConsumptionThreshold billingAccount_outplanNotification_POST(String billingAccount, OvhOutplanNotificationBlockEnum block, String notifyEmail, Double percentage) throws IOException { String qPath = "/telephony/{billingAccount}/outplanNotification"; StringBuilder sb = path(qPath, billingAccount); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "block", block); addBody(o, "notifyEmail", notifyEmail); addBody(o, "percentage", percentage); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhConsumptionThreshold.class); }
[ "public", "OvhConsumptionThreshold", "billingAccount_outplanNotification_POST", "(", "String", "billingAccount", ",", "OvhOutplanNotificationBlockEnum", "block", ",", "String", "notifyEmail", ",", "Double", "percentage", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/telephony/{billingAccount}/outplanNotification\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "billingAccount", ")", ";", "HashMap", "<", "String", ",", "Object", ">", "o", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "addBody", "(", "o", ",", "\"block\"", ",", "block", ")", ";", "addBody", "(", "o", ",", "\"notifyEmail\"", ",", "notifyEmail", ")", ";", "addBody", "(", "o", ",", "\"percentage\"", ",", "percentage", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"POST\"", ",", "sb", ".", "toString", "(", ")", ",", "o", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhConsumptionThreshold", ".", "class", ")", ";", "}" ]
Add an outplan notification on the billing account REST: POST /telephony/{billingAccount}/outplanNotification @param percentage [required] The notification percentage of maximum outplan @param block [required] The blocking type of the associate lines @param notifyEmail [required] Override the nichandle email for this notification @param billingAccount [required] The name of your billingAccount
[ "Add", "an", "outplan", "notification", "on", "the", "billing", "account" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java#L8328-L8337
GenesysPureEngage/provisioning-client-java
src/main/java/com/genesys/internal/provisioning/api/UsersApi.java
UsersApi.updateUserWithHttpInfo
public ApiResponse<ApiSuccessResponse> updateUserWithHttpInfo(String dbid, UpdateUserData updateUserData) throws ApiException { """ Update a user. Update a user ([CfgPerson](https://docs.genesys.com/Documentation/PSDK/latest/ConfigLayerRef/CfgPerson)) with the specified attributes. @param dbid The user&#39;s DBID. (required) @param updateUserData Update user data (required) @return ApiResponse&lt;ApiSuccessResponse&gt; @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body """ com.squareup.okhttp.Call call = updateUserValidateBeforeCall(dbid, updateUserData, null, null); Type localVarReturnType = new TypeToken<ApiSuccessResponse>(){}.getType(); return apiClient.execute(call, localVarReturnType); }
java
public ApiResponse<ApiSuccessResponse> updateUserWithHttpInfo(String dbid, UpdateUserData updateUserData) throws ApiException { com.squareup.okhttp.Call call = updateUserValidateBeforeCall(dbid, updateUserData, null, null); Type localVarReturnType = new TypeToken<ApiSuccessResponse>(){}.getType(); return apiClient.execute(call, localVarReturnType); }
[ "public", "ApiResponse", "<", "ApiSuccessResponse", ">", "updateUserWithHttpInfo", "(", "String", "dbid", ",", "UpdateUserData", "updateUserData", ")", "throws", "ApiException", "{", "com", ".", "squareup", ".", "okhttp", ".", "Call", "call", "=", "updateUserValidateBeforeCall", "(", "dbid", ",", "updateUserData", ",", "null", ",", "null", ")", ";", "Type", "localVarReturnType", "=", "new", "TypeToken", "<", "ApiSuccessResponse", ">", "(", ")", "{", "}", ".", "getType", "(", ")", ";", "return", "apiClient", ".", "execute", "(", "call", ",", "localVarReturnType", ")", ";", "}" ]
Update a user. Update a user ([CfgPerson](https://docs.genesys.com/Documentation/PSDK/latest/ConfigLayerRef/CfgPerson)) with the specified attributes. @param dbid The user&#39;s DBID. (required) @param updateUserData Update user data (required) @return ApiResponse&lt;ApiSuccessResponse&gt; @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
[ "Update", "a", "user", ".", "Update", "a", "user", "(", "[", "CfgPerson", "]", "(", "https", ":", "//", "docs", ".", "genesys", ".", "com", "/", "Documentation", "/", "PSDK", "/", "latest", "/", "ConfigLayerRef", "/", "CfgPerson", "))", "with", "the", "specified", "attributes", "." ]
train
https://github.com/GenesysPureEngage/provisioning-client-java/blob/1ad594c3767cec83052168e350994f922a26f75e/src/main/java/com/genesys/internal/provisioning/api/UsersApi.java#L813-L817
gosu-lang/gosu-lang
gosu-core-api/src/main/java/gw/util/GosuStringUtil.java
GosuStringUtil.getNestedString
public static String getNestedString(String str, String open, String close) { """ <p>Gets the String that is nested in between two Strings. Only the first match is returned.</p> <p>A <code>null</code> input String returns <code>null</code>. A <code>null</code> open/close returns <code>null</code> (no match). An empty ("") open/close returns an empty string.</p> <pre> GosuStringUtil.getNestedString(null, *, *) = null GosuStringUtil.getNestedString("", "", "") = "" GosuStringUtil.getNestedString("", "", "tag") = null GosuStringUtil.getNestedString("", "tag", "tag") = null GosuStringUtil.getNestedString("yabcz", null, null) = null GosuStringUtil.getNestedString("yabcz", "", "") = "" GosuStringUtil.getNestedString("yabcz", "y", "z") = "abc" GosuStringUtil.getNestedString("yabczyabcz", "y", "z") = "abc" </pre> @param str the String containing nested-string, may be null @param open the String before nested-string, may be null @param close the String after nested-string, may be null @return the nested String, <code>null</code> if no match @deprecated Use the better named {@link #substringBetween(String, String, String)}. Method will be removed in Commons Lang 3.0. """ return substringBetween(str, open, close); }
java
public static String getNestedString(String str, String open, String close) { return substringBetween(str, open, close); }
[ "public", "static", "String", "getNestedString", "(", "String", "str", ",", "String", "open", ",", "String", "close", ")", "{", "return", "substringBetween", "(", "str", ",", "open", ",", "close", ")", ";", "}" ]
<p>Gets the String that is nested in between two Strings. Only the first match is returned.</p> <p>A <code>null</code> input String returns <code>null</code>. A <code>null</code> open/close returns <code>null</code> (no match). An empty ("") open/close returns an empty string.</p> <pre> GosuStringUtil.getNestedString(null, *, *) = null GosuStringUtil.getNestedString("", "", "") = "" GosuStringUtil.getNestedString("", "", "tag") = null GosuStringUtil.getNestedString("", "tag", "tag") = null GosuStringUtil.getNestedString("yabcz", null, null) = null GosuStringUtil.getNestedString("yabcz", "", "") = "" GosuStringUtil.getNestedString("yabcz", "y", "z") = "abc" GosuStringUtil.getNestedString("yabczyabcz", "y", "z") = "abc" </pre> @param str the String containing nested-string, may be null @param open the String before nested-string, may be null @param close the String after nested-string, may be null @return the nested String, <code>null</code> if no match @deprecated Use the better named {@link #substringBetween(String, String, String)}. Method will be removed in Commons Lang 3.0.
[ "<p", ">", "Gets", "the", "String", "that", "is", "nested", "in", "between", "two", "Strings", ".", "Only", "the", "first", "match", "is", "returned", ".", "<", "/", "p", ">" ]
train
https://github.com/gosu-lang/gosu-lang/blob/d6e9261b137ce66fef3726cabe7826d4a1f946b7/gosu-core-api/src/main/java/gw/util/GosuStringUtil.java#L2051-L2053
3redronin/mu-server
src/main/java/io/muserver/MediaTypeParser.java
MediaTypeParser.fromString
public static MediaType fromString(String value) { """ Converts a string such as "text/plain" into a MediaType object. @param value The value to parse @return A MediaType object """ if (value == null) { throw new NullPointerException("value"); } List<ParameterizedHeaderWithValue> headerValues = ParameterizedHeaderWithValue.fromString(value); if (headerValues.isEmpty()) { throw new IllegalArgumentException("The value '" + value + "' did not contain a valid header value"); } ParameterizedHeaderWithValue v = headerValues.get(0); String[] split = v.value().split("/"); if (split.length != 2) { throw new IllegalArgumentException("Media types must be in the format 'type/subtype'; this is inavlid: '" + v.value() + "'"); } return new MediaType(split[0], split[1], v.parameters()); }
java
public static MediaType fromString(String value) { if (value == null) { throw new NullPointerException("value"); } List<ParameterizedHeaderWithValue> headerValues = ParameterizedHeaderWithValue.fromString(value); if (headerValues.isEmpty()) { throw new IllegalArgumentException("The value '" + value + "' did not contain a valid header value"); } ParameterizedHeaderWithValue v = headerValues.get(0); String[] split = v.value().split("/"); if (split.length != 2) { throw new IllegalArgumentException("Media types must be in the format 'type/subtype'; this is inavlid: '" + v.value() + "'"); } return new MediaType(split[0], split[1], v.parameters()); }
[ "public", "static", "MediaType", "fromString", "(", "String", "value", ")", "{", "if", "(", "value", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"value\"", ")", ";", "}", "List", "<", "ParameterizedHeaderWithValue", ">", "headerValues", "=", "ParameterizedHeaderWithValue", ".", "fromString", "(", "value", ")", ";", "if", "(", "headerValues", ".", "isEmpty", "(", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"The value '\"", "+", "value", "+", "\"' did not contain a valid header value\"", ")", ";", "}", "ParameterizedHeaderWithValue", "v", "=", "headerValues", ".", "get", "(", "0", ")", ";", "String", "[", "]", "split", "=", "v", ".", "value", "(", ")", ".", "split", "(", "\"/\"", ")", ";", "if", "(", "split", ".", "length", "!=", "2", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Media types must be in the format 'type/subtype'; this is inavlid: '\"", "+", "v", ".", "value", "(", ")", "+", "\"'\"", ")", ";", "}", "return", "new", "MediaType", "(", "split", "[", "0", "]", ",", "split", "[", "1", "]", ",", "v", ".", "parameters", "(", ")", ")", ";", "}" ]
Converts a string such as "text/plain" into a MediaType object. @param value The value to parse @return A MediaType object
[ "Converts", "a", "string", "such", "as", "text", "/", "plain", "into", "a", "MediaType", "object", "." ]
train
https://github.com/3redronin/mu-server/blob/51598606a3082a121fbd785348ee9770b40308e6/src/main/java/io/muserver/MediaTypeParser.java#L22-L36
DDTH/ddth-dlock
ddth-dlock-core/src/main/java/com/github/ddth/dlock/impl/AbstractDLockFactory.java
AbstractDLockFactory.createAndInitLockInstance
protected AbstractDLock createAndInitLockInstance(String name, Properties lockProps) { """ Create and initializes an {@link IDLock} instance, ready for use. @param name @param lockProps @return """ AbstractDLock lock = createLockInternal(name, lockProps); lock.init(); return lock; }
java
protected AbstractDLock createAndInitLockInstance(String name, Properties lockProps) { AbstractDLock lock = createLockInternal(name, lockProps); lock.init(); return lock; }
[ "protected", "AbstractDLock", "createAndInitLockInstance", "(", "String", "name", ",", "Properties", "lockProps", ")", "{", "AbstractDLock", "lock", "=", "createLockInternal", "(", "name", ",", "lockProps", ")", ";", "lock", ".", "init", "(", ")", ";", "return", "lock", ";", "}" ]
Create and initializes an {@link IDLock} instance, ready for use. @param name @param lockProps @return
[ "Create", "and", "initializes", "an", "{", "@link", "IDLock", "}", "instance", "ready", "for", "use", "." ]
train
https://github.com/DDTH/ddth-dlock/blob/56786c61a04fe505556a834133b3de36562c6cb6/ddth-dlock-core/src/main/java/com/github/ddth/dlock/impl/AbstractDLockFactory.java#L141-L145
Azure/azure-sdk-for-java
eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/EventProcessorHost.java
EventProcessorHost.registerEventProcessorFactory
public CompletableFuture<Void> registerEventProcessorFactory(IEventProcessorFactory<?> factory, EventProcessorOptions processorOptions) { """ Register user-supplied event processor factory and start processing. <p> This overload takes user-specified options. <p> The returned CompletableFuture completes when host initialization is finished. Initialization failures are reported by completing the future with an exception, so it is important to call get() on the future and handle any exceptions thrown. @param factory User-supplied event processor factory object. @param processorOptions Options for the processor host and event processor(s). @return Future that completes when initialization is finished. """ if (this.unregistered != null) { throw new IllegalStateException("Register cannot be called on an EventProcessorHost after unregister. Please create a new EventProcessorHost instance."); } if (this.hostContext.getEventProcessorFactory() != null) { throw new IllegalStateException("Register has already been called on this EventProcessorHost"); } this.hostContext.setEventProcessorFactory(factory); this.hostContext.setEventProcessorOptions(processorOptions); if (this.executorService.isShutdown() || this.executorService.isTerminated()) { TRACE_LOGGER.warn(this.hostContext.withHost("Calling registerEventProcessor/Factory after executor service has been shut down.")); throw new RejectedExecutionException("EventProcessorHost executor service has been shut down"); } if (this.initializeLeaseManager) { try { ((AzureStorageCheckpointLeaseManager) this.hostContext.getLeaseManager()).initialize(this.hostContext); } catch (InvalidKeyException | URISyntaxException | StorageException e) { TRACE_LOGGER.error(this.hostContext.withHost("Failure initializing default lease and checkpoint manager.")); throw new RuntimeException("Failure initializing Storage lease manager", e); } } TRACE_LOGGER.info(this.hostContext.withHost("Starting event processing.")); return this.partitionManager.initialize(); }
java
public CompletableFuture<Void> registerEventProcessorFactory(IEventProcessorFactory<?> factory, EventProcessorOptions processorOptions) { if (this.unregistered != null) { throw new IllegalStateException("Register cannot be called on an EventProcessorHost after unregister. Please create a new EventProcessorHost instance."); } if (this.hostContext.getEventProcessorFactory() != null) { throw new IllegalStateException("Register has already been called on this EventProcessorHost"); } this.hostContext.setEventProcessorFactory(factory); this.hostContext.setEventProcessorOptions(processorOptions); if (this.executorService.isShutdown() || this.executorService.isTerminated()) { TRACE_LOGGER.warn(this.hostContext.withHost("Calling registerEventProcessor/Factory after executor service has been shut down.")); throw new RejectedExecutionException("EventProcessorHost executor service has been shut down"); } if (this.initializeLeaseManager) { try { ((AzureStorageCheckpointLeaseManager) this.hostContext.getLeaseManager()).initialize(this.hostContext); } catch (InvalidKeyException | URISyntaxException | StorageException e) { TRACE_LOGGER.error(this.hostContext.withHost("Failure initializing default lease and checkpoint manager.")); throw new RuntimeException("Failure initializing Storage lease manager", e); } } TRACE_LOGGER.info(this.hostContext.withHost("Starting event processing.")); return this.partitionManager.initialize(); }
[ "public", "CompletableFuture", "<", "Void", ">", "registerEventProcessorFactory", "(", "IEventProcessorFactory", "<", "?", ">", "factory", ",", "EventProcessorOptions", "processorOptions", ")", "{", "if", "(", "this", ".", "unregistered", "!=", "null", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Register cannot be called on an EventProcessorHost after unregister. Please create a new EventProcessorHost instance.\"", ")", ";", "}", "if", "(", "this", ".", "hostContext", ".", "getEventProcessorFactory", "(", ")", "!=", "null", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Register has already been called on this EventProcessorHost\"", ")", ";", "}", "this", ".", "hostContext", ".", "setEventProcessorFactory", "(", "factory", ")", ";", "this", ".", "hostContext", ".", "setEventProcessorOptions", "(", "processorOptions", ")", ";", "if", "(", "this", ".", "executorService", ".", "isShutdown", "(", ")", "||", "this", ".", "executorService", ".", "isTerminated", "(", ")", ")", "{", "TRACE_LOGGER", ".", "warn", "(", "this", ".", "hostContext", ".", "withHost", "(", "\"Calling registerEventProcessor/Factory after executor service has been shut down.\"", ")", ")", ";", "throw", "new", "RejectedExecutionException", "(", "\"EventProcessorHost executor service has been shut down\"", ")", ";", "}", "if", "(", "this", ".", "initializeLeaseManager", ")", "{", "try", "{", "(", "(", "AzureStorageCheckpointLeaseManager", ")", "this", ".", "hostContext", ".", "getLeaseManager", "(", ")", ")", ".", "initialize", "(", "this", ".", "hostContext", ")", ";", "}", "catch", "(", "InvalidKeyException", "|", "URISyntaxException", "|", "StorageException", "e", ")", "{", "TRACE_LOGGER", ".", "error", "(", "this", ".", "hostContext", ".", "withHost", "(", "\"Failure initializing default lease and checkpoint manager.\"", ")", ")", ";", "throw", "new", "RuntimeException", "(", "\"Failure initializing Storage lease manager\"", ",", "e", ")", ";", "}", "}", "TRACE_LOGGER", ".", "info", "(", "this", ".", "hostContext", ".", "withHost", "(", "\"Starting event processing.\"", ")", ")", ";", "return", "this", ".", "partitionManager", ".", "initialize", "(", ")", ";", "}" ]
Register user-supplied event processor factory and start processing. <p> This overload takes user-specified options. <p> The returned CompletableFuture completes when host initialization is finished. Initialization failures are reported by completing the future with an exception, so it is important to call get() on the future and handle any exceptions thrown. @param factory User-supplied event processor factory object. @param processorOptions Options for the processor host and event processor(s). @return Future that completes when initialization is finished.
[ "Register", "user", "-", "supplied", "event", "processor", "factory", "and", "start", "processing", ".", "<p", ">", "This", "overload", "takes", "user", "-", "specified", "options", ".", "<p", ">", "The", "returned", "CompletableFuture", "completes", "when", "host", "initialization", "is", "finished", ".", "Initialization", "failures", "are", "reported", "by", "completing", "the", "future", "with", "an", "exception", "so", "it", "is", "important", "to", "call", "get", "()", "on", "the", "future", "and", "handle", "any", "exceptions", "thrown", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/EventProcessorHost.java#L464-L492
DataSketches/sketches-core
src/main/java/com/yahoo/sketches/quantiles/DoublesUpdateImpl.java
DoublesUpdateImpl.getRequiredItemCapacity
static int getRequiredItemCapacity(final int k, final long newN) { """ This only increases the size and does not touch or move any data. """ final int numLevelsNeeded = Util.computeNumLevelsNeeded(k, newN); if (numLevelsNeeded == 0) { // don't need any levels yet, and might have small base buffer; this can happen during a merge return 2 * k; } // from here on we need a full-size base buffer and at least one level assert newN >= (2L * k); assert numLevelsNeeded > 0; final int spaceNeeded = (2 + numLevelsNeeded) * k; return spaceNeeded; }
java
static int getRequiredItemCapacity(final int k, final long newN) { final int numLevelsNeeded = Util.computeNumLevelsNeeded(k, newN); if (numLevelsNeeded == 0) { // don't need any levels yet, and might have small base buffer; this can happen during a merge return 2 * k; } // from here on we need a full-size base buffer and at least one level assert newN >= (2L * k); assert numLevelsNeeded > 0; final int spaceNeeded = (2 + numLevelsNeeded) * k; return spaceNeeded; }
[ "static", "int", "getRequiredItemCapacity", "(", "final", "int", "k", ",", "final", "long", "newN", ")", "{", "final", "int", "numLevelsNeeded", "=", "Util", ".", "computeNumLevelsNeeded", "(", "k", ",", "newN", ")", ";", "if", "(", "numLevelsNeeded", "==", "0", ")", "{", "// don't need any levels yet, and might have small base buffer; this can happen during a merge", "return", "2", "*", "k", ";", "}", "// from here on we need a full-size base buffer and at least one level", "assert", "newN", ">=", "(", "2L", "*", "k", ")", ";", "assert", "numLevelsNeeded", ">", "0", ";", "final", "int", "spaceNeeded", "=", "(", "2", "+", "numLevelsNeeded", ")", "*", "k", ";", "return", "spaceNeeded", ";", "}" ]
This only increases the size and does not touch or move any data.
[ "This", "only", "increases", "the", "size", "and", "does", "not", "touch", "or", "move", "any", "data", "." ]
train
https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/quantiles/DoublesUpdateImpl.java#L27-L38
Azure/azure-sdk-for-java
batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/TasksImpl.java
TasksImpl.listNextAsync
public ServiceFuture<List<CloudTask>> listNextAsync(final String nextPageLink, final ServiceFuture<List<CloudTask>> serviceFuture, final ListOperationCallback<CloudTask> serviceCallback) { """ Lists all of the tasks that are associated with the specified job. For multi-instance tasks, information such as affinityId, executionInfo and nodeInfo refer to the primary task. Use the list subtasks API to retrieve information about subtasks. @param nextPageLink The NextLink from the previous successful call to List operation. @param serviceFuture the ServiceFuture object tracking the Retrofit calls @param serviceCallback the async ServiceCallback to handle successful and failed responses. @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceFuture} object """ return AzureServiceFuture.fromHeaderPageResponse( listNextSinglePageAsync(nextPageLink), new Func1<String, Observable<ServiceResponseWithHeaders<Page<CloudTask>, TaskListHeaders>>>() { @Override public Observable<ServiceResponseWithHeaders<Page<CloudTask>, TaskListHeaders>> call(String nextPageLink) { return listNextSinglePageAsync(nextPageLink, null); } }, serviceCallback); }
java
public ServiceFuture<List<CloudTask>> listNextAsync(final String nextPageLink, final ServiceFuture<List<CloudTask>> serviceFuture, final ListOperationCallback<CloudTask> serviceCallback) { return AzureServiceFuture.fromHeaderPageResponse( listNextSinglePageAsync(nextPageLink), new Func1<String, Observable<ServiceResponseWithHeaders<Page<CloudTask>, TaskListHeaders>>>() { @Override public Observable<ServiceResponseWithHeaders<Page<CloudTask>, TaskListHeaders>> call(String nextPageLink) { return listNextSinglePageAsync(nextPageLink, null); } }, serviceCallback); }
[ "public", "ServiceFuture", "<", "List", "<", "CloudTask", ">", ">", "listNextAsync", "(", "final", "String", "nextPageLink", ",", "final", "ServiceFuture", "<", "List", "<", "CloudTask", ">", ">", "serviceFuture", ",", "final", "ListOperationCallback", "<", "CloudTask", ">", "serviceCallback", ")", "{", "return", "AzureServiceFuture", ".", "fromHeaderPageResponse", "(", "listNextSinglePageAsync", "(", "nextPageLink", ")", ",", "new", "Func1", "<", "String", ",", "Observable", "<", "ServiceResponseWithHeaders", "<", "Page", "<", "CloudTask", ">", ",", "TaskListHeaders", ">", ">", ">", "(", ")", "{", "@", "Override", "public", "Observable", "<", "ServiceResponseWithHeaders", "<", "Page", "<", "CloudTask", ">", ",", "TaskListHeaders", ">", ">", "call", "(", "String", "nextPageLink", ")", "{", "return", "listNextSinglePageAsync", "(", "nextPageLink", ",", "null", ")", ";", "}", "}", ",", "serviceCallback", ")", ";", "}" ]
Lists all of the tasks that are associated with the specified job. For multi-instance tasks, information such as affinityId, executionInfo and nodeInfo refer to the primary task. Use the list subtasks API to retrieve information about subtasks. @param nextPageLink The NextLink from the previous successful call to List operation. @param serviceFuture the ServiceFuture object tracking the Retrofit calls @param serviceCallback the async ServiceCallback to handle successful and failed responses. @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceFuture} object
[ "Lists", "all", "of", "the", "tasks", "that", "are", "associated", "with", "the", "specified", "job", ".", "For", "multi", "-", "instance", "tasks", "information", "such", "as", "affinityId", "executionInfo", "and", "nodeInfo", "refer", "to", "the", "primary", "task", ".", "Use", "the", "list", "subtasks", "API", "to", "retrieve", "information", "about", "subtasks", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/TasksImpl.java#L2343-L2353
deeplearning4j/deeplearning4j
datavec/datavec-arrow/src/main/java/org/datavec/arrow/ArrowConverter.java
ArrowConverter.fromEntry
public static Writable fromEntry(int item,FieldVector from,ColumnType columnType) { """ Based on an input {@link ColumnType} get an entry from a {@link FieldVector} @param item the row of the item to get from the column vector @param from the column vector from @param columnType the column type @return the resulting writable """ if(from.getValueCount() < item) { throw new IllegalArgumentException("Index specified greater than the number of items in the vector with length " + from.getValueCount()); } switch(columnType) { case Integer: return new IntWritable(getIntFromFieldVector(item,from)); case Long: return new LongWritable(getLongFromFieldVector(item,from)); case Float: return new FloatWritable(getFloatFromFieldVector(item,from)); case Double: return new DoubleWritable(getDoubleFromFieldVector(item,from)); case Boolean: BitVector bitVector = (BitVector) from; return new BooleanWritable(bitVector.get(item) > 0); case Categorical: VarCharVector varCharVector = (VarCharVector) from; return new Text(varCharVector.get(item)); case String: VarCharVector varCharVector2 = (VarCharVector) from; return new Text(varCharVector2.get(item)); case Time: //TODO: need to look at closer return new LongWritable(getLongFromFieldVector(item,from)); case NDArray: VarBinaryVector valueVector = (VarBinaryVector) from; byte[] bytes = valueVector.get(item); ByteBuffer direct = ByteBuffer.allocateDirect(bytes.length); direct.put(bytes); INDArray fromTensor = BinarySerde.toArray(direct); return new NDArrayWritable(fromTensor); default: throw new IllegalArgumentException("Illegal type " + from.getClass().getName()); } }
java
public static Writable fromEntry(int item,FieldVector from,ColumnType columnType) { if(from.getValueCount() < item) { throw new IllegalArgumentException("Index specified greater than the number of items in the vector with length " + from.getValueCount()); } switch(columnType) { case Integer: return new IntWritable(getIntFromFieldVector(item,from)); case Long: return new LongWritable(getLongFromFieldVector(item,from)); case Float: return new FloatWritable(getFloatFromFieldVector(item,from)); case Double: return new DoubleWritable(getDoubleFromFieldVector(item,from)); case Boolean: BitVector bitVector = (BitVector) from; return new BooleanWritable(bitVector.get(item) > 0); case Categorical: VarCharVector varCharVector = (VarCharVector) from; return new Text(varCharVector.get(item)); case String: VarCharVector varCharVector2 = (VarCharVector) from; return new Text(varCharVector2.get(item)); case Time: //TODO: need to look at closer return new LongWritable(getLongFromFieldVector(item,from)); case NDArray: VarBinaryVector valueVector = (VarBinaryVector) from; byte[] bytes = valueVector.get(item); ByteBuffer direct = ByteBuffer.allocateDirect(bytes.length); direct.put(bytes); INDArray fromTensor = BinarySerde.toArray(direct); return new NDArrayWritable(fromTensor); default: throw new IllegalArgumentException("Illegal type " + from.getClass().getName()); } }
[ "public", "static", "Writable", "fromEntry", "(", "int", "item", ",", "FieldVector", "from", ",", "ColumnType", "columnType", ")", "{", "if", "(", "from", ".", "getValueCount", "(", ")", "<", "item", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Index specified greater than the number of items in the vector with length \"", "+", "from", ".", "getValueCount", "(", ")", ")", ";", "}", "switch", "(", "columnType", ")", "{", "case", "Integer", ":", "return", "new", "IntWritable", "(", "getIntFromFieldVector", "(", "item", ",", "from", ")", ")", ";", "case", "Long", ":", "return", "new", "LongWritable", "(", "getLongFromFieldVector", "(", "item", ",", "from", ")", ")", ";", "case", "Float", ":", "return", "new", "FloatWritable", "(", "getFloatFromFieldVector", "(", "item", ",", "from", ")", ")", ";", "case", "Double", ":", "return", "new", "DoubleWritable", "(", "getDoubleFromFieldVector", "(", "item", ",", "from", ")", ")", ";", "case", "Boolean", ":", "BitVector", "bitVector", "=", "(", "BitVector", ")", "from", ";", "return", "new", "BooleanWritable", "(", "bitVector", ".", "get", "(", "item", ")", ">", "0", ")", ";", "case", "Categorical", ":", "VarCharVector", "varCharVector", "=", "(", "VarCharVector", ")", "from", ";", "return", "new", "Text", "(", "varCharVector", ".", "get", "(", "item", ")", ")", ";", "case", "String", ":", "VarCharVector", "varCharVector2", "=", "(", "VarCharVector", ")", "from", ";", "return", "new", "Text", "(", "varCharVector2", ".", "get", "(", "item", ")", ")", ";", "case", "Time", ":", "//TODO: need to look at closer", "return", "new", "LongWritable", "(", "getLongFromFieldVector", "(", "item", ",", "from", ")", ")", ";", "case", "NDArray", ":", "VarBinaryVector", "valueVector", "=", "(", "VarBinaryVector", ")", "from", ";", "byte", "[", "]", "bytes", "=", "valueVector", ".", "get", "(", "item", ")", ";", "ByteBuffer", "direct", "=", "ByteBuffer", ".", "allocateDirect", "(", "bytes", ".", "length", ")", ";", "direct", ".", "put", "(", "bytes", ")", ";", "INDArray", "fromTensor", "=", "BinarySerde", ".", "toArray", "(", "direct", ")", ";", "return", "new", "NDArrayWritable", "(", "fromTensor", ")", ";", "default", ":", "throw", "new", "IllegalArgumentException", "(", "\"Illegal type \"", "+", "from", ".", "getClass", "(", ")", ".", "getName", "(", ")", ")", ";", "}", "}" ]
Based on an input {@link ColumnType} get an entry from a {@link FieldVector} @param item the row of the item to get from the column vector @param from the column vector from @param columnType the column type @return the resulting writable
[ "Based", "on", "an", "input", "{", "@link", "ColumnType", "}", "get", "an", "entry", "from", "a", "{", "@link", "FieldVector", "}" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/datavec/datavec-arrow/src/main/java/org/datavec/arrow/ArrowConverter.java#L1193-L1229
openengsb/openengsb
api/ekb/src/main/java/org/openengsb/core/ekb/api/transformation/TransformationDescription.java
TransformationDescription.replaceField
public void replaceField(String sourceField, String targetField, String oldString, String newString) { """ Adds a replace step to the transformation description. The source and the target field need to be of String type. Performs standard string replacement on the string of the source field and writes the result to the target field. """ TransformationStep step = new TransformationStep(); step.setSourceFields(sourceField); step.setTargetField(targetField); step.setOperationParameter(TransformationConstants.REPLACE_OLD_PARAM, oldString); step.setOperationParameter(TransformationConstants.REPLACE_NEW_PARAM, newString); step.setOperationName("replace"); steps.add(step); }
java
public void replaceField(String sourceField, String targetField, String oldString, String newString) { TransformationStep step = new TransformationStep(); step.setSourceFields(sourceField); step.setTargetField(targetField); step.setOperationParameter(TransformationConstants.REPLACE_OLD_PARAM, oldString); step.setOperationParameter(TransformationConstants.REPLACE_NEW_PARAM, newString); step.setOperationName("replace"); steps.add(step); }
[ "public", "void", "replaceField", "(", "String", "sourceField", ",", "String", "targetField", ",", "String", "oldString", ",", "String", "newString", ")", "{", "TransformationStep", "step", "=", "new", "TransformationStep", "(", ")", ";", "step", ".", "setSourceFields", "(", "sourceField", ")", ";", "step", ".", "setTargetField", "(", "targetField", ")", ";", "step", ".", "setOperationParameter", "(", "TransformationConstants", ".", "REPLACE_OLD_PARAM", ",", "oldString", ")", ";", "step", ".", "setOperationParameter", "(", "TransformationConstants", ".", "REPLACE_NEW_PARAM", ",", "newString", ")", ";", "step", ".", "setOperationName", "(", "\"replace\"", ")", ";", "steps", ".", "add", "(", "step", ")", ";", "}" ]
Adds a replace step to the transformation description. The source and the target field need to be of String type. Performs standard string replacement on the string of the source field and writes the result to the target field.
[ "Adds", "a", "replace", "step", "to", "the", "transformation", "description", ".", "The", "source", "and", "the", "target", "field", "need", "to", "be", "of", "String", "type", ".", "Performs", "standard", "string", "replacement", "on", "the", "string", "of", "the", "source", "field", "and", "writes", "the", "result", "to", "the", "target", "field", "." ]
train
https://github.com/openengsb/openengsb/blob/d39058000707f617cd405629f9bc7f17da7b414a/api/ekb/src/main/java/org/openengsb/core/ekb/api/transformation/TransformationDescription.java#L215-L223
fuinorg/objects4j
src/main/java/org/fuin/objects4j/ui/TableColumnInfo.java
TableColumnInfo.create
public static TableColumnInfo create(@NotNull final Field field, @NotNull final Locale locale) { """ Return the table column information for a given field. @param field Field to check for <code>@TableColumn</code> and <code>@Label</code> annotations. @param locale Locale to use. @return Information or <code>null</code>. """ Contract.requireArgNotNull("field", field); Contract.requireArgNotNull("locale", locale); final TableColumn tableColumn = field.getAnnotation(TableColumn.class); if (tableColumn == null) { return null; } final AnnotationAnalyzer analyzer = new AnnotationAnalyzer(); final FieldTextInfo labelInfo = analyzer.createFieldInfo(field, locale, Label.class); final FieldTextInfo shortLabelInfo = analyzer.createFieldInfo(field, locale, ShortLabel.class); final FieldTextInfo tooltipInfo = analyzer.createFieldInfo(field, locale, Tooltip.class); final int pos = tableColumn.pos(); final FontSize fontSize = new FontSize(tableColumn.width(), tableColumn.unit()); final String getter = getGetter(tableColumn, field.getName()); final String labelText; if (labelInfo == null) { labelText = null; } else { labelText = labelInfo.getTextOrField(); } final String shortLabelText; if (shortLabelInfo == null) { shortLabelText = null; } else { shortLabelText = shortLabelInfo.getText(); } final String tooltipText; if (tooltipInfo == null) { tooltipText = null; } else { tooltipText = tooltipInfo.getText(); } return new TableColumnInfo(field, labelText, shortLabelText, tooltipText, pos, fontSize, getter); }
java
public static TableColumnInfo create(@NotNull final Field field, @NotNull final Locale locale) { Contract.requireArgNotNull("field", field); Contract.requireArgNotNull("locale", locale); final TableColumn tableColumn = field.getAnnotation(TableColumn.class); if (tableColumn == null) { return null; } final AnnotationAnalyzer analyzer = new AnnotationAnalyzer(); final FieldTextInfo labelInfo = analyzer.createFieldInfo(field, locale, Label.class); final FieldTextInfo shortLabelInfo = analyzer.createFieldInfo(field, locale, ShortLabel.class); final FieldTextInfo tooltipInfo = analyzer.createFieldInfo(field, locale, Tooltip.class); final int pos = tableColumn.pos(); final FontSize fontSize = new FontSize(tableColumn.width(), tableColumn.unit()); final String getter = getGetter(tableColumn, field.getName()); final String labelText; if (labelInfo == null) { labelText = null; } else { labelText = labelInfo.getTextOrField(); } final String shortLabelText; if (shortLabelInfo == null) { shortLabelText = null; } else { shortLabelText = shortLabelInfo.getText(); } final String tooltipText; if (tooltipInfo == null) { tooltipText = null; } else { tooltipText = tooltipInfo.getText(); } return new TableColumnInfo(field, labelText, shortLabelText, tooltipText, pos, fontSize, getter); }
[ "public", "static", "TableColumnInfo", "create", "(", "@", "NotNull", "final", "Field", "field", ",", "@", "NotNull", "final", "Locale", "locale", ")", "{", "Contract", ".", "requireArgNotNull", "(", "\"field\"", ",", "field", ")", ";", "Contract", ".", "requireArgNotNull", "(", "\"locale\"", ",", "locale", ")", ";", "final", "TableColumn", "tableColumn", "=", "field", ".", "getAnnotation", "(", "TableColumn", ".", "class", ")", ";", "if", "(", "tableColumn", "==", "null", ")", "{", "return", "null", ";", "}", "final", "AnnotationAnalyzer", "analyzer", "=", "new", "AnnotationAnalyzer", "(", ")", ";", "final", "FieldTextInfo", "labelInfo", "=", "analyzer", ".", "createFieldInfo", "(", "field", ",", "locale", ",", "Label", ".", "class", ")", ";", "final", "FieldTextInfo", "shortLabelInfo", "=", "analyzer", ".", "createFieldInfo", "(", "field", ",", "locale", ",", "ShortLabel", ".", "class", ")", ";", "final", "FieldTextInfo", "tooltipInfo", "=", "analyzer", ".", "createFieldInfo", "(", "field", ",", "locale", ",", "Tooltip", ".", "class", ")", ";", "final", "int", "pos", "=", "tableColumn", ".", "pos", "(", ")", ";", "final", "FontSize", "fontSize", "=", "new", "FontSize", "(", "tableColumn", ".", "width", "(", ")", ",", "tableColumn", ".", "unit", "(", ")", ")", ";", "final", "String", "getter", "=", "getGetter", "(", "tableColumn", ",", "field", ".", "getName", "(", ")", ")", ";", "final", "String", "labelText", ";", "if", "(", "labelInfo", "==", "null", ")", "{", "labelText", "=", "null", ";", "}", "else", "{", "labelText", "=", "labelInfo", ".", "getTextOrField", "(", ")", ";", "}", "final", "String", "shortLabelText", ";", "if", "(", "shortLabelInfo", "==", "null", ")", "{", "shortLabelText", "=", "null", ";", "}", "else", "{", "shortLabelText", "=", "shortLabelInfo", ".", "getText", "(", ")", ";", "}", "final", "String", "tooltipText", ";", "if", "(", "tooltipInfo", "==", "null", ")", "{", "tooltipText", "=", "null", ";", "}", "else", "{", "tooltipText", "=", "tooltipInfo", ".", "getText", "(", ")", ";", "}", "return", "new", "TableColumnInfo", "(", "field", ",", "labelText", ",", "shortLabelText", ",", "tooltipText", ",", "pos", ",", "fontSize", ",", "getter", ")", ";", "}" ]
Return the table column information for a given field. @param field Field to check for <code>@TableColumn</code> and <code>@Label</code> annotations. @param locale Locale to use. @return Information or <code>null</code>.
[ "Return", "the", "table", "column", "information", "for", "a", "given", "field", "." ]
train
https://github.com/fuinorg/objects4j/blob/e7f278b5bae073ebb6a76053650571c718f36246/src/main/java/org/fuin/objects4j/ui/TableColumnInfo.java#L241-L281
logic-ng/LogicNG
src/main/java/org/logicng/solvers/maxsat/encodings/Encoding.java
Encoding.addBinaryClause
void addBinaryClause(final MiniSatStyleSolver s, int a, int b) { """ Adds a binary clause to the given SAT solver. @param s the sat solver @param a the first literal @param b the second literal """ this.addBinaryClause(s, a, b, LIT_UNDEF); }
java
void addBinaryClause(final MiniSatStyleSolver s, int a, int b) { this.addBinaryClause(s, a, b, LIT_UNDEF); }
[ "void", "addBinaryClause", "(", "final", "MiniSatStyleSolver", "s", ",", "int", "a", ",", "int", "b", ")", "{", "this", ".", "addBinaryClause", "(", "s", ",", "a", ",", "b", ",", "LIT_UNDEF", ")", ";", "}" ]
Adds a binary clause to the given SAT solver. @param s the sat solver @param a the first literal @param b the second literal
[ "Adds", "a", "binary", "clause", "to", "the", "given", "SAT", "solver", "." ]
train
https://github.com/logic-ng/LogicNG/blob/bb9eb88a768be4be8e02a76cfc4a59e6c3fb7f2e/src/main/java/org/logicng/solvers/maxsat/encodings/Encoding.java#L107-L109
Azure/azure-sdk-for-java
appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/implementation/AppServiceEnvironmentsInner.java
AppServiceEnvironmentsInner.listWorkerPoolSkusWithServiceResponseAsync
public Observable<ServiceResponse<Page<SkuInfoInner>>> listWorkerPoolSkusWithServiceResponseAsync(final String resourceGroupName, final String name, final String workerPoolName) { """ Get available SKUs for scaling a worker pool. Get available SKUs for scaling a worker pool. @param resourceGroupName Name of the resource group to which the resource belongs. @param name Name of the App Service Environment. @param workerPoolName Name of the worker pool. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;SkuInfoInner&gt; object """ return listWorkerPoolSkusSinglePageAsync(resourceGroupName, name, workerPoolName) .concatMap(new Func1<ServiceResponse<Page<SkuInfoInner>>, Observable<ServiceResponse<Page<SkuInfoInner>>>>() { @Override public Observable<ServiceResponse<Page<SkuInfoInner>>> call(ServiceResponse<Page<SkuInfoInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listWorkerPoolSkusNextWithServiceResponseAsync(nextPageLink)); } }); }
java
public Observable<ServiceResponse<Page<SkuInfoInner>>> listWorkerPoolSkusWithServiceResponseAsync(final String resourceGroupName, final String name, final String workerPoolName) { return listWorkerPoolSkusSinglePageAsync(resourceGroupName, name, workerPoolName) .concatMap(new Func1<ServiceResponse<Page<SkuInfoInner>>, Observable<ServiceResponse<Page<SkuInfoInner>>>>() { @Override public Observable<ServiceResponse<Page<SkuInfoInner>>> call(ServiceResponse<Page<SkuInfoInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listWorkerPoolSkusNextWithServiceResponseAsync(nextPageLink)); } }); }
[ "public", "Observable", "<", "ServiceResponse", "<", "Page", "<", "SkuInfoInner", ">", ">", ">", "listWorkerPoolSkusWithServiceResponseAsync", "(", "final", "String", "resourceGroupName", ",", "final", "String", "name", ",", "final", "String", "workerPoolName", ")", "{", "return", "listWorkerPoolSkusSinglePageAsync", "(", "resourceGroupName", ",", "name", ",", "workerPoolName", ")", ".", "concatMap", "(", "new", "Func1", "<", "ServiceResponse", "<", "Page", "<", "SkuInfoInner", ">", ">", ",", "Observable", "<", "ServiceResponse", "<", "Page", "<", "SkuInfoInner", ">", ">", ">", ">", "(", ")", "{", "@", "Override", "public", "Observable", "<", "ServiceResponse", "<", "Page", "<", "SkuInfoInner", ">", ">", ">", "call", "(", "ServiceResponse", "<", "Page", "<", "SkuInfoInner", ">", ">", "page", ")", "{", "String", "nextPageLink", "=", "page", ".", "body", "(", ")", ".", "nextPageLink", "(", ")", ";", "if", "(", "nextPageLink", "==", "null", ")", "{", "return", "Observable", ".", "just", "(", "page", ")", ";", "}", "return", "Observable", ".", "just", "(", "page", ")", ".", "concatWith", "(", "listWorkerPoolSkusNextWithServiceResponseAsync", "(", "nextPageLink", ")", ")", ";", "}", "}", ")", ";", "}" ]
Get available SKUs for scaling a worker pool. Get available SKUs for scaling a worker pool. @param resourceGroupName Name of the resource group to which the resource belongs. @param name Name of the App Service Environment. @param workerPoolName Name of the worker pool. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;SkuInfoInner&gt; object
[ "Get", "available", "SKUs", "for", "scaling", "a", "worker", "pool", ".", "Get", "available", "SKUs", "for", "scaling", "a", "worker", "pool", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/implementation/AppServiceEnvironmentsInner.java#L6408-L6420
soi-toolkit/soi-toolkit-mule
tools/soitoolkit-generator/soitoolkit-generator-eclipse-plugin/soitoolkit-generator-plugin/src/soi_toolkit_generator_plugin/preferences/SoiToolkiGeneratorPreferencePage.java
SoiToolkiGeneratorPreferencePage.createFieldEditors
public void createFieldEditors() { """ Creates the field editors. Field editors are abstractions of the common GUI blocks needed to manipulate various types of preferences. Each field editor knows how to save and restore itself. """ addField(new DirectoryFieldEditor(PreferenceConstants.P_MAVEN_HOME, "&Maven home folder:", getFieldEditorParent())); addField(new DirectoryFieldEditor(PreferenceConstants.P_DEFAULT_ROOT_FOLDER, "Default root folder:", getFieldEditorParent())); // addField(new RadioGroupFieldEditor(PreferenceConstants.P_ECLIPSE_GOAL, "Maven Eclipse goal", 1, // new String[][] { { "eclipse:eclipse", "eclipse:eclipse" }, {"eclipse:m2eclipse", "eclipse:m2eclipse" } // }, getFieldEditorParent())); addField(new StringFieldEditor(PreferenceConstants.P_GROOVY_MODEL, "Custom Groovy model:", getFieldEditorParent())); addField(new StringFieldEditor(PreferenceConstants.P_SFTP_ROOT_FOLDER, "Default SFTP root folder:", getFieldEditorParent())); // addField( // new BooleanFieldEditor( // PreferenceConstants.P_BOOLEAN, // "&An example of a boolean preference", // getFieldEditorParent())); }
java
public void createFieldEditors() { addField(new DirectoryFieldEditor(PreferenceConstants.P_MAVEN_HOME, "&Maven home folder:", getFieldEditorParent())); addField(new DirectoryFieldEditor(PreferenceConstants.P_DEFAULT_ROOT_FOLDER, "Default root folder:", getFieldEditorParent())); // addField(new RadioGroupFieldEditor(PreferenceConstants.P_ECLIPSE_GOAL, "Maven Eclipse goal", 1, // new String[][] { { "eclipse:eclipse", "eclipse:eclipse" }, {"eclipse:m2eclipse", "eclipse:m2eclipse" } // }, getFieldEditorParent())); addField(new StringFieldEditor(PreferenceConstants.P_GROOVY_MODEL, "Custom Groovy model:", getFieldEditorParent())); addField(new StringFieldEditor(PreferenceConstants.P_SFTP_ROOT_FOLDER, "Default SFTP root folder:", getFieldEditorParent())); // addField( // new BooleanFieldEditor( // PreferenceConstants.P_BOOLEAN, // "&An example of a boolean preference", // getFieldEditorParent())); }
[ "public", "void", "createFieldEditors", "(", ")", "{", "addField", "(", "new", "DirectoryFieldEditor", "(", "PreferenceConstants", ".", "P_MAVEN_HOME", ",", "\"&Maven home folder:\"", ",", "getFieldEditorParent", "(", ")", ")", ")", ";", "addField", "(", "new", "DirectoryFieldEditor", "(", "PreferenceConstants", ".", "P_DEFAULT_ROOT_FOLDER", ",", "\"Default root folder:\"", ",", "getFieldEditorParent", "(", ")", ")", ")", ";", "//\t\taddField(new RadioGroupFieldEditor(PreferenceConstants.P_ECLIPSE_GOAL, \"Maven Eclipse goal\", 1,", "//\t\t\tnew String[][] { { \"eclipse:eclipse\", \"eclipse:eclipse\" }, {\"eclipse:m2eclipse\", \"eclipse:m2eclipse\" }", "//\t\t}, getFieldEditorParent()));", "addField", "(", "new", "StringFieldEditor", "(", "PreferenceConstants", ".", "P_GROOVY_MODEL", ",", "\"Custom Groovy model:\"", ",", "getFieldEditorParent", "(", ")", ")", ")", ";", "addField", "(", "new", "StringFieldEditor", "(", "PreferenceConstants", ".", "P_SFTP_ROOT_FOLDER", ",", "\"Default SFTP root folder:\"", ",", "getFieldEditorParent", "(", ")", ")", ")", ";", "//\t\taddField(", "//\t\t\tnew BooleanFieldEditor(", "//\t\t\t\tPreferenceConstants.P_BOOLEAN,", "//\t\t\t\t\"&An example of a boolean preference\",", "//\t\t\t\tgetFieldEditorParent()));", "}" ]
Creates the field editors. Field editors are abstractions of the common GUI blocks needed to manipulate various types of preferences. Each field editor knows how to save and restore itself.
[ "Creates", "the", "field", "editors", ".", "Field", "editors", "are", "abstractions", "of", "the", "common", "GUI", "blocks", "needed", "to", "manipulate", "various", "types", "of", "preferences", ".", "Each", "field", "editor", "knows", "how", "to", "save", "and", "restore", "itself", "." ]
train
https://github.com/soi-toolkit/soi-toolkit-mule/blob/e891350dbf55e6307be94d193d056bdb785b37d3/tools/soitoolkit-generator/soitoolkit-generator-eclipse-plugin/soitoolkit-generator-plugin/src/soi_toolkit_generator_plugin/preferences/SoiToolkiGeneratorPreferencePage.java#L58-L77
facebookarchive/hadoop-20
src/hdfs/org/apache/hadoop/hdfs/server/namenode/NameNode.java
NameNode.stopRPC
protected void stopRPC(boolean interruptClientHandlers) throws IOException, InterruptedException { """ Quiescess all communication to namenode cleanly. Ensures all RPC handlers have exited. @param interruptClientHandlers should the handlers be interrupted """ // stop client handlers stopRPCInternal(server, "client", interruptClientHandlers); // stop datanode handlers stopRPCInternal(dnProtocolServer, "datanode", interruptClientHandlers); // waiting for the ongoing requests to complete stopWaitRPCInternal(server, "client"); stopWaitRPCInternal(dnProtocolServer, "datanode"); }
java
protected void stopRPC(boolean interruptClientHandlers) throws IOException, InterruptedException { // stop client handlers stopRPCInternal(server, "client", interruptClientHandlers); // stop datanode handlers stopRPCInternal(dnProtocolServer, "datanode", interruptClientHandlers); // waiting for the ongoing requests to complete stopWaitRPCInternal(server, "client"); stopWaitRPCInternal(dnProtocolServer, "datanode"); }
[ "protected", "void", "stopRPC", "(", "boolean", "interruptClientHandlers", ")", "throws", "IOException", ",", "InterruptedException", "{", "// stop client handlers", "stopRPCInternal", "(", "server", ",", "\"client\"", ",", "interruptClientHandlers", ")", ";", "// stop datanode handlers", "stopRPCInternal", "(", "dnProtocolServer", ",", "\"datanode\"", ",", "interruptClientHandlers", ")", ";", "// waiting for the ongoing requests to complete", "stopWaitRPCInternal", "(", "server", ",", "\"client\"", ")", ";", "stopWaitRPCInternal", "(", "dnProtocolServer", ",", "\"datanode\"", ")", ";", "}" ]
Quiescess all communication to namenode cleanly. Ensures all RPC handlers have exited. @param interruptClientHandlers should the handlers be interrupted
[ "Quiescess", "all", "communication", "to", "namenode", "cleanly", ".", "Ensures", "all", "RPC", "handlers", "have", "exited", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/server/namenode/NameNode.java#L674-L685
Grasia/phatsim
phat-core/src/main/java/phat/util/SpatialFactory.java
SpatialFactory.attachAName
public static BitmapText attachAName(Node node, String name) { """ Creates a geometry with the same name of the given node. It adds a controller called BillboardControl that turns the name of the node in order to look at the camera. Letter's size can be changed using setSize() method, the text with setText() method and the color using setColor() method. @param node @return """ checkInit(); BitmapFont guiFont = assetManager.loadFont("Interface/Fonts/Default.fnt"); BitmapText ch = new BitmapText(guiFont, false); ch.setName("BitmapText"); ch.setSize(guiFont.getCharSet().getRenderedSize() * 0.02f); ch.setText(name); // crosshairs ch.setColor(new ColorRGBA(0f, 0f, 0f, 1f)); ch.getLocalScale().divideLocal(node.getLocalScale()); // controlador para que los objetos miren a la cámara. BillboardControl control = new BillboardControl(); ch.addControl(control); node.attachChild(ch); return ch; }
java
public static BitmapText attachAName(Node node, String name) { checkInit(); BitmapFont guiFont = assetManager.loadFont("Interface/Fonts/Default.fnt"); BitmapText ch = new BitmapText(guiFont, false); ch.setName("BitmapText"); ch.setSize(guiFont.getCharSet().getRenderedSize() * 0.02f); ch.setText(name); // crosshairs ch.setColor(new ColorRGBA(0f, 0f, 0f, 1f)); ch.getLocalScale().divideLocal(node.getLocalScale()); // controlador para que los objetos miren a la cámara. BillboardControl control = new BillboardControl(); ch.addControl(control); node.attachChild(ch); return ch; }
[ "public", "static", "BitmapText", "attachAName", "(", "Node", "node", ",", "String", "name", ")", "{", "checkInit", "(", ")", ";", "BitmapFont", "guiFont", "=", "assetManager", ".", "loadFont", "(", "\"Interface/Fonts/Default.fnt\"", ")", ";", "BitmapText", "ch", "=", "new", "BitmapText", "(", "guiFont", ",", "false", ")", ";", "ch", ".", "setName", "(", "\"BitmapText\"", ")", ";", "ch", ".", "setSize", "(", "guiFont", ".", "getCharSet", "(", ")", ".", "getRenderedSize", "(", ")", "*", "0.02f", ")", ";", "ch", ".", "setText", "(", "name", ")", ";", "// crosshairs", "ch", ".", "setColor", "(", "new", "ColorRGBA", "(", "0f", ",", "0f", ",", "0f", ",", "1f", ")", ")", ";", "ch", ".", "getLocalScale", "(", ")", ".", "divideLocal", "(", "node", ".", "getLocalScale", "(", ")", ")", ";", "// controlador para que los objetos miren a la cámara.", "BillboardControl", "control", "=", "new", "BillboardControl", "(", ")", ";", "ch", ".", "addControl", "(", "control", ")", ";", "node", ".", "attachChild", "(", "ch", ")", ";", "return", "ch", ";", "}" ]
Creates a geometry with the same name of the given node. It adds a controller called BillboardControl that turns the name of the node in order to look at the camera. Letter's size can be changed using setSize() method, the text with setText() method and the color using setColor() method. @param node @return
[ "Creates", "a", "geometry", "with", "the", "same", "name", "of", "the", "given", "node", ".", "It", "adds", "a", "controller", "called", "BillboardControl", "that", "turns", "the", "name", "of", "the", "node", "in", "order", "to", "look", "at", "the", "camera", "." ]
train
https://github.com/Grasia/phatsim/blob/2d4fc8189be9730b34c8e3e1a08fb4800e01c5df/phat-core/src/main/java/phat/util/SpatialFactory.java#L153-L168
camunda/camunda-xml-model
src/main/java/org/camunda/bpm/model/xml/impl/ModelImpl.java
ModelImpl.declareAlternativeNamespace
public void declareAlternativeNamespace(String alternativeNs, String actualNs) { """ Declares an alternative namespace for an actual so that during lookup of elements/attributes both will be considered. This can be used if a newer namespaces replaces an older one but XML files with the old one should still be parseable. @param alternativeNs @param actualNs @throws IllegalArgumentException if the alternative is already used or if the actual namespace has an alternative """ if(actualNsToAlternative.containsKey(actualNs) || alternativeNsToActual.containsKey(alternativeNs)){ throw new IllegalArgumentException("Cannot register two alternatives for one namespace! Actual Ns: " + actualNs + " second alternative: " + alternativeNs); } actualNsToAlternative.put(actualNs, alternativeNs); alternativeNsToActual.put(alternativeNs, actualNs); }
java
public void declareAlternativeNamespace(String alternativeNs, String actualNs) { if(actualNsToAlternative.containsKey(actualNs) || alternativeNsToActual.containsKey(alternativeNs)){ throw new IllegalArgumentException("Cannot register two alternatives for one namespace! Actual Ns: " + actualNs + " second alternative: " + alternativeNs); } actualNsToAlternative.put(actualNs, alternativeNs); alternativeNsToActual.put(alternativeNs, actualNs); }
[ "public", "void", "declareAlternativeNamespace", "(", "String", "alternativeNs", ",", "String", "actualNs", ")", "{", "if", "(", "actualNsToAlternative", ".", "containsKey", "(", "actualNs", ")", "||", "alternativeNsToActual", ".", "containsKey", "(", "alternativeNs", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Cannot register two alternatives for one namespace! Actual Ns: \"", "+", "actualNs", "+", "\" second alternative: \"", "+", "alternativeNs", ")", ";", "}", "actualNsToAlternative", ".", "put", "(", "actualNs", ",", "alternativeNs", ")", ";", "alternativeNsToActual", ".", "put", "(", "alternativeNs", ",", "actualNs", ")", ";", "}" ]
Declares an alternative namespace for an actual so that during lookup of elements/attributes both will be considered. This can be used if a newer namespaces replaces an older one but XML files with the old one should still be parseable. @param alternativeNs @param actualNs @throws IllegalArgumentException if the alternative is already used or if the actual namespace has an alternative
[ "Declares", "an", "alternative", "namespace", "for", "an", "actual", "so", "that", "during", "lookup", "of", "elements", "/", "attributes", "both", "will", "be", "considered", ".", "This", "can", "be", "used", "if", "a", "newer", "namespaces", "replaces", "an", "older", "one", "but", "XML", "files", "with", "the", "old", "one", "should", "still", "be", "parseable", "." ]
train
https://github.com/camunda/camunda-xml-model/blob/85b3f879e26d063f71c94cfd21ac17d9ff6baf4d/src/main/java/org/camunda/bpm/model/xml/impl/ModelImpl.java#L60-L66
paymill/paymill-java
src/main/java/com/paymill/services/TransactionService.java
TransactionService.createWithPreauthorization
public Transaction createWithPreauthorization( String preauthorizationId, Integer amount, String currency ) { """ Executes a {@link Transaction} with {@link Preauthorization} for the given amount in the given currency. @param preauthorizationId The Id of a {@link Preauthorization}, which has reserved some money from the client’s credit card. @param amount Amount (in cents) which will be charged. @param currency ISO 4217 formatted currency code. @return {@link Transaction} object indicating whether a the call was successful or not. """ return this.createWithPreauthorization( preauthorizationId, amount, currency, null ); }
java
public Transaction createWithPreauthorization( String preauthorizationId, Integer amount, String currency ) { return this.createWithPreauthorization( preauthorizationId, amount, currency, null ); }
[ "public", "Transaction", "createWithPreauthorization", "(", "String", "preauthorizationId", ",", "Integer", "amount", ",", "String", "currency", ")", "{", "return", "this", ".", "createWithPreauthorization", "(", "preauthorizationId", ",", "amount", ",", "currency", ",", "null", ")", ";", "}" ]
Executes a {@link Transaction} with {@link Preauthorization} for the given amount in the given currency. @param preauthorizationId The Id of a {@link Preauthorization}, which has reserved some money from the client’s credit card. @param amount Amount (in cents) which will be charged. @param currency ISO 4217 formatted currency code. @return {@link Transaction} object indicating whether a the call was successful or not.
[ "Executes", "a", "{" ]
train
https://github.com/paymill/paymill-java/blob/17281a0d4376c76f1711af9f09bfc138c90ba65a/src/main/java/com/paymill/services/TransactionService.java#L353-L355
pietermartin/sqlg
sqlg-core/src/main/java/org/umlg/sqlg/structure/topology/Schema.java
Schema.removeEdgeLabel
void removeEdgeLabel(EdgeLabel edgeLabel, boolean preserveData) { """ remove a given edge label @param edgeLabel the edge label @param preserveData should we keep the SQL data """ getTopology().lock(); String fn = this.name + "." + EDGE_PREFIX + edgeLabel.getName(); if (!uncommittedRemovedEdgeLabels.contains(fn)) { uncommittedRemovedEdgeLabels.add(fn); TopologyManager.removeEdgeLabel(this.sqlgGraph, edgeLabel); for (VertexLabel lbl : edgeLabel.getOutVertexLabels()) { lbl.removeOutEdge(edgeLabel); } for (VertexLabel lbl : edgeLabel.getInVertexLabels()) { lbl.removeInEdge(edgeLabel); } if (!preserveData) { edgeLabel.delete(); } getTopology().fire(edgeLabel, "", TopologyChangeAction.DELETE); } }
java
void removeEdgeLabel(EdgeLabel edgeLabel, boolean preserveData) { getTopology().lock(); String fn = this.name + "." + EDGE_PREFIX + edgeLabel.getName(); if (!uncommittedRemovedEdgeLabels.contains(fn)) { uncommittedRemovedEdgeLabels.add(fn); TopologyManager.removeEdgeLabel(this.sqlgGraph, edgeLabel); for (VertexLabel lbl : edgeLabel.getOutVertexLabels()) { lbl.removeOutEdge(edgeLabel); } for (VertexLabel lbl : edgeLabel.getInVertexLabels()) { lbl.removeInEdge(edgeLabel); } if (!preserveData) { edgeLabel.delete(); } getTopology().fire(edgeLabel, "", TopologyChangeAction.DELETE); } }
[ "void", "removeEdgeLabel", "(", "EdgeLabel", "edgeLabel", ",", "boolean", "preserveData", ")", "{", "getTopology", "(", ")", ".", "lock", "(", ")", ";", "String", "fn", "=", "this", ".", "name", "+", "\".\"", "+", "EDGE_PREFIX", "+", "edgeLabel", ".", "getName", "(", ")", ";", "if", "(", "!", "uncommittedRemovedEdgeLabels", ".", "contains", "(", "fn", ")", ")", "{", "uncommittedRemovedEdgeLabels", ".", "add", "(", "fn", ")", ";", "TopologyManager", ".", "removeEdgeLabel", "(", "this", ".", "sqlgGraph", ",", "edgeLabel", ")", ";", "for", "(", "VertexLabel", "lbl", ":", "edgeLabel", ".", "getOutVertexLabels", "(", ")", ")", "{", "lbl", ".", "removeOutEdge", "(", "edgeLabel", ")", ";", "}", "for", "(", "VertexLabel", "lbl", ":", "edgeLabel", ".", "getInVertexLabels", "(", ")", ")", "{", "lbl", ".", "removeInEdge", "(", "edgeLabel", ")", ";", "}", "if", "(", "!", "preserveData", ")", "{", "edgeLabel", ".", "delete", "(", ")", ";", "}", "getTopology", "(", ")", ".", "fire", "(", "edgeLabel", ",", "\"\"", ",", "TopologyChangeAction", ".", "DELETE", ")", ";", "}", "}" ]
remove a given edge label @param edgeLabel the edge label @param preserveData should we keep the SQL data
[ "remove", "a", "given", "edge", "label" ]
train
https://github.com/pietermartin/sqlg/blob/c1845a1b31328a5ffda646873b0369ee72af56a7/sqlg-core/src/main/java/org/umlg/sqlg/structure/topology/Schema.java#L1757-L1776
Azure/azure-sdk-for-java
containerregistry/resource-manager/v2018_09_01/src/main/java/com/microsoft/azure/management/containerregistry/v2018_09_01/implementation/TasksInner.java
TasksInner.updateAsync
public Observable<TaskInner> updateAsync(String resourceGroupName, String registryName, String taskName, TaskUpdateParameters taskUpdateParameters) { """ Updates a task with the specified parameters. @param resourceGroupName The name of the resource group to which the container registry belongs. @param registryName The name of the container registry. @param taskName The name of the container registry task. @param taskUpdateParameters The parameters for updating a task. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request """ return updateWithServiceResponseAsync(resourceGroupName, registryName, taskName, taskUpdateParameters).map(new Func1<ServiceResponse<TaskInner>, TaskInner>() { @Override public TaskInner call(ServiceResponse<TaskInner> response) { return response.body(); } }); }
java
public Observable<TaskInner> updateAsync(String resourceGroupName, String registryName, String taskName, TaskUpdateParameters taskUpdateParameters) { return updateWithServiceResponseAsync(resourceGroupName, registryName, taskName, taskUpdateParameters).map(new Func1<ServiceResponse<TaskInner>, TaskInner>() { @Override public TaskInner call(ServiceResponse<TaskInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "TaskInner", ">", "updateAsync", "(", "String", "resourceGroupName", ",", "String", "registryName", ",", "String", "taskName", ",", "TaskUpdateParameters", "taskUpdateParameters", ")", "{", "return", "updateWithServiceResponseAsync", "(", "resourceGroupName", ",", "registryName", ",", "taskName", ",", "taskUpdateParameters", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "TaskInner", ">", ",", "TaskInner", ">", "(", ")", "{", "@", "Override", "public", "TaskInner", "call", "(", "ServiceResponse", "<", "TaskInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Updates a task with the specified parameters. @param resourceGroupName The name of the resource group to which the container registry belongs. @param registryName The name of the container registry. @param taskName The name of the container registry task. @param taskUpdateParameters The parameters for updating a task. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request
[ "Updates", "a", "task", "with", "the", "specified", "parameters", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/containerregistry/resource-manager/v2018_09_01/src/main/java/com/microsoft/azure/management/containerregistry/v2018_09_01/implementation/TasksInner.java#L709-L716
autermann/yaml
src/main/java/com/github/autermann/yaml/nodes/YamlMappingNode.java
YamlMappingNode.put
public T put(YamlNode key, byte value) { """ Adds the specified {@code key}/{@code value} pair to this mapping. @param key the key @param value the value @return {@code this} """ return put(key, getNodeFactory().byteNode(value)); }
java
public T put(YamlNode key, byte value) { return put(key, getNodeFactory().byteNode(value)); }
[ "public", "T", "put", "(", "YamlNode", "key", ",", "byte", "value", ")", "{", "return", "put", "(", "key", ",", "getNodeFactory", "(", ")", ".", "byteNode", "(", "value", ")", ")", ";", "}" ]
Adds the specified {@code key}/{@code value} pair to this mapping. @param key the key @param value the value @return {@code this}
[ "Adds", "the", "specified", "{", "@code", "key", "}", "/", "{", "@code", "value", "}", "pair", "to", "this", "mapping", "." ]
train
https://github.com/autermann/yaml/blob/5f8ab03e4fec3a2abe72c03561cdaa3a3936634d/src/main/java/com/github/autermann/yaml/nodes/YamlMappingNode.java#L420-L422
joniles/mpxj
src/main/java/net/sf/mpxj/mspdi/MSPDIReader.java
MSPDIReader.updateBaseCalendarNames
private static void updateBaseCalendarNames(List<Pair<ProjectCalendar, BigInteger>> baseCalendars, HashMap<BigInteger, ProjectCalendar> map) { """ The way calendars are stored in an MSPDI file means that there can be forward references between the base calendar unique ID for a derived calendar, and the base calendar itself. To get around this, we initially populate the base calendar name attribute with the base calendar unique ID, and now in this method we can convert those ID values into the correct names. @param baseCalendars list of calendars and base calendar IDs @param map map of calendar ID values and calendar objects """ for (Pair<ProjectCalendar, BigInteger> pair : baseCalendars) { ProjectCalendar cal = pair.getFirst(); BigInteger baseCalendarID = pair.getSecond(); ProjectCalendar baseCal = map.get(baseCalendarID); if (baseCal != null) { cal.setParent(baseCal); } } }
java
private static void updateBaseCalendarNames(List<Pair<ProjectCalendar, BigInteger>> baseCalendars, HashMap<BigInteger, ProjectCalendar> map) { for (Pair<ProjectCalendar, BigInteger> pair : baseCalendars) { ProjectCalendar cal = pair.getFirst(); BigInteger baseCalendarID = pair.getSecond(); ProjectCalendar baseCal = map.get(baseCalendarID); if (baseCal != null) { cal.setParent(baseCal); } } }
[ "private", "static", "void", "updateBaseCalendarNames", "(", "List", "<", "Pair", "<", "ProjectCalendar", ",", "BigInteger", ">", ">", "baseCalendars", ",", "HashMap", "<", "BigInteger", ",", "ProjectCalendar", ">", "map", ")", "{", "for", "(", "Pair", "<", "ProjectCalendar", ",", "BigInteger", ">", "pair", ":", "baseCalendars", ")", "{", "ProjectCalendar", "cal", "=", "pair", ".", "getFirst", "(", ")", ";", "BigInteger", "baseCalendarID", "=", "pair", ".", "getSecond", "(", ")", ";", "ProjectCalendar", "baseCal", "=", "map", ".", "get", "(", "baseCalendarID", ")", ";", "if", "(", "baseCal", "!=", "null", ")", "{", "cal", ".", "setParent", "(", "baseCal", ")", ";", "}", "}", "}" ]
The way calendars are stored in an MSPDI file means that there can be forward references between the base calendar unique ID for a derived calendar, and the base calendar itself. To get around this, we initially populate the base calendar name attribute with the base calendar unique ID, and now in this method we can convert those ID values into the correct names. @param baseCalendars list of calendars and base calendar IDs @param map map of calendar ID values and calendar objects
[ "The", "way", "calendars", "are", "stored", "in", "an", "MSPDI", "file", "means", "that", "there", "can", "be", "forward", "references", "between", "the", "base", "calendar", "unique", "ID", "for", "a", "derived", "calendar", "and", "the", "base", "calendar", "itself", ".", "To", "get", "around", "this", "we", "initially", "populate", "the", "base", "calendar", "name", "attribute", "with", "the", "base", "calendar", "unique", "ID", "and", "now", "in", "this", "method", "we", "can", "convert", "those", "ID", "values", "into", "the", "correct", "names", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mspdi/MSPDIReader.java#L422-L435
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/sql/Date.java
Date.valueOf
public static Date valueOf(String s) { """ Converts a string in JDBC date escape format to a <code>Date</code> value. @param s a <code>String</code> object representing a date in in the format "yyyy-[m]m-[d]d". The leading zero for <code>mm</code> and <code>dd</code> may also be omitted. @return a <code>java.sql.Date</code> object representing the given date @throws IllegalArgumentException if the date given is not in the JDBC date escape format (yyyy-[m]m-[d]d) """ final int YEAR_LENGTH = 4; final int MONTH_LENGTH = 2; final int DAY_LENGTH = 2; final int MAX_MONTH = 12; final int MAX_DAY = 31; int firstDash; int secondDash; Date d = null; if (s == null) { throw new java.lang.IllegalArgumentException(); } firstDash = s.indexOf('-'); secondDash = s.indexOf('-', firstDash + 1); if ((firstDash > 0) && (secondDash > 0) && (secondDash < s.length() - 1)) { String yyyy = s.substring(0, firstDash); String mm = s.substring(firstDash + 1, secondDash); String dd = s.substring(secondDash + 1); if (yyyy.length() == YEAR_LENGTH && (mm.length() >= 1 && mm.length() <= MONTH_LENGTH) && (dd.length() >= 1 && dd.length() <= DAY_LENGTH)) { int year = Integer.parseInt(yyyy); int month = Integer.parseInt(mm); int day = Integer.parseInt(dd); if ((month >= 1 && month <= MAX_MONTH) && (day >= 1 && day <= MAX_DAY)) { d = new Date(year - 1900, month - 1, day); } } } if (d == null) { throw new java.lang.IllegalArgumentException(); } return d; }
java
public static Date valueOf(String s) { final int YEAR_LENGTH = 4; final int MONTH_LENGTH = 2; final int DAY_LENGTH = 2; final int MAX_MONTH = 12; final int MAX_DAY = 31; int firstDash; int secondDash; Date d = null; if (s == null) { throw new java.lang.IllegalArgumentException(); } firstDash = s.indexOf('-'); secondDash = s.indexOf('-', firstDash + 1); if ((firstDash > 0) && (secondDash > 0) && (secondDash < s.length() - 1)) { String yyyy = s.substring(0, firstDash); String mm = s.substring(firstDash + 1, secondDash); String dd = s.substring(secondDash + 1); if (yyyy.length() == YEAR_LENGTH && (mm.length() >= 1 && mm.length() <= MONTH_LENGTH) && (dd.length() >= 1 && dd.length() <= DAY_LENGTH)) { int year = Integer.parseInt(yyyy); int month = Integer.parseInt(mm); int day = Integer.parseInt(dd); if ((month >= 1 && month <= MAX_MONTH) && (day >= 1 && day <= MAX_DAY)) { d = new Date(year - 1900, month - 1, day); } } } if (d == null) { throw new java.lang.IllegalArgumentException(); } return d; }
[ "public", "static", "Date", "valueOf", "(", "String", "s", ")", "{", "final", "int", "YEAR_LENGTH", "=", "4", ";", "final", "int", "MONTH_LENGTH", "=", "2", ";", "final", "int", "DAY_LENGTH", "=", "2", ";", "final", "int", "MAX_MONTH", "=", "12", ";", "final", "int", "MAX_DAY", "=", "31", ";", "int", "firstDash", ";", "int", "secondDash", ";", "Date", "d", "=", "null", ";", "if", "(", "s", "==", "null", ")", "{", "throw", "new", "java", ".", "lang", ".", "IllegalArgumentException", "(", ")", ";", "}", "firstDash", "=", "s", ".", "indexOf", "(", "'", "'", ")", ";", "secondDash", "=", "s", ".", "indexOf", "(", "'", "'", ",", "firstDash", "+", "1", ")", ";", "if", "(", "(", "firstDash", ">", "0", ")", "&&", "(", "secondDash", ">", "0", ")", "&&", "(", "secondDash", "<", "s", ".", "length", "(", ")", "-", "1", ")", ")", "{", "String", "yyyy", "=", "s", ".", "substring", "(", "0", ",", "firstDash", ")", ";", "String", "mm", "=", "s", ".", "substring", "(", "firstDash", "+", "1", ",", "secondDash", ")", ";", "String", "dd", "=", "s", ".", "substring", "(", "secondDash", "+", "1", ")", ";", "if", "(", "yyyy", ".", "length", "(", ")", "==", "YEAR_LENGTH", "&&", "(", "mm", ".", "length", "(", ")", ">=", "1", "&&", "mm", ".", "length", "(", ")", "<=", "MONTH_LENGTH", ")", "&&", "(", "dd", ".", "length", "(", ")", ">=", "1", "&&", "dd", ".", "length", "(", ")", "<=", "DAY_LENGTH", ")", ")", "{", "int", "year", "=", "Integer", ".", "parseInt", "(", "yyyy", ")", ";", "int", "month", "=", "Integer", ".", "parseInt", "(", "mm", ")", ";", "int", "day", "=", "Integer", ".", "parseInt", "(", "dd", ")", ";", "if", "(", "(", "month", ">=", "1", "&&", "month", "<=", "MAX_MONTH", ")", "&&", "(", "day", ">=", "1", "&&", "day", "<=", "MAX_DAY", ")", ")", "{", "d", "=", "new", "Date", "(", "year", "-", "1900", ",", "month", "-", "1", ",", "day", ")", ";", "}", "}", "}", "if", "(", "d", "==", "null", ")", "{", "throw", "new", "java", ".", "lang", ".", "IllegalArgumentException", "(", ")", ";", "}", "return", "d", ";", "}" ]
Converts a string in JDBC date escape format to a <code>Date</code> value. @param s a <code>String</code> object representing a date in in the format "yyyy-[m]m-[d]d". The leading zero for <code>mm</code> and <code>dd</code> may also be omitted. @return a <code>java.sql.Date</code> object representing the given date @throws IllegalArgumentException if the date given is not in the JDBC date escape format (yyyy-[m]m-[d]d)
[ "Converts", "a", "string", "in", "JDBC", "date", "escape", "format", "to", "a", "<code", ">", "Date<", "/", "code", ">", "value", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/sql/Date.java#L108-L147
threerings/nenya
core/src/main/java/com/threerings/media/util/MathUtil.java
MathUtil.floorDiv
public static int floorDiv (int dividend, int divisor) { """ Computes the floored division <code>dividend/divisor</code> which is useful when dividing potentially negative numbers into bins. <p> For example, the following numbers floorDiv 10 are: <pre> -15 -10 -8 -2 0 2 8 10 15 -2 -1 -1 -1 0 0 0 1 1 </pre> """ return ((dividend >= 0) == (divisor >= 0)) ? dividend / divisor : (divisor >= 0 ? (dividend - divisor + 1) / divisor : (dividend - divisor - 1) / divisor); }
java
public static int floorDiv (int dividend, int divisor) { return ((dividend >= 0) == (divisor >= 0)) ? dividend / divisor : (divisor >= 0 ? (dividend - divisor + 1) / divisor : (dividend - divisor - 1) / divisor); }
[ "public", "static", "int", "floorDiv", "(", "int", "dividend", ",", "int", "divisor", ")", "{", "return", "(", "(", "dividend", ">=", "0", ")", "==", "(", "divisor", ">=", "0", ")", ")", "?", "dividend", "/", "divisor", ":", "(", "divisor", ">=", "0", "?", "(", "dividend", "-", "divisor", "+", "1", ")", "/", "divisor", ":", "(", "dividend", "-", "divisor", "-", "1", ")", "/", "divisor", ")", ";", "}" ]
Computes the floored division <code>dividend/divisor</code> which is useful when dividing potentially negative numbers into bins. <p> For example, the following numbers floorDiv 10 are: <pre> -15 -10 -8 -2 0 2 8 10 15 -2 -1 -1 -1 0 0 0 1 1 </pre>
[ "Computes", "the", "floored", "division", "<code", ">", "dividend", "/", "divisor<", "/", "code", ">", "which", "is", "useful", "when", "dividing", "potentially", "negative", "numbers", "into", "bins", "." ]
train
https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/media/util/MathUtil.java#L109-L114
lessthanoptimal/ejml
main/ejml-ddense/src/org/ejml/dense/row/CommonOps_DDRM.java
CommonOps_DDRM.multTransAB
public static void multTransAB(double alpha , DMatrix1Row a , DMatrix1Row b , DMatrix1Row c ) { """ <p> Performs the following operation:<br> <br> c = &alpha; * a<sup>T</sup> * b<sup>T</sup><br> c<sub>ij</sub> = &alpha; &sum;<sub>k=1:n</sub> { a<sub>ki</sub> * b<sub>jk</sub>} </p> @param alpha Scaling factor. @param a The left matrix in the multiplication operation. Not modified. @param b The right matrix in the multiplication operation. Not modified. @param c Where the results of the operation are stored. Modified. """ // TODO add a matrix vectory multiply here if( a.numCols >= EjmlParameters.MULT_TRANAB_COLUMN_SWITCH ) { MatrixMatrixMult_DDRM.multTransAB_aux(alpha, a, b, c, null); } else { MatrixMatrixMult_DDRM.multTransAB(alpha, a, b, c); } }
java
public static void multTransAB(double alpha , DMatrix1Row a , DMatrix1Row b , DMatrix1Row c ) { // TODO add a matrix vectory multiply here if( a.numCols >= EjmlParameters.MULT_TRANAB_COLUMN_SWITCH ) { MatrixMatrixMult_DDRM.multTransAB_aux(alpha, a, b, c, null); } else { MatrixMatrixMult_DDRM.multTransAB(alpha, a, b, c); } }
[ "public", "static", "void", "multTransAB", "(", "double", "alpha", ",", "DMatrix1Row", "a", ",", "DMatrix1Row", "b", ",", "DMatrix1Row", "c", ")", "{", "// TODO add a matrix vectory multiply here", "if", "(", "a", ".", "numCols", ">=", "EjmlParameters", ".", "MULT_TRANAB_COLUMN_SWITCH", ")", "{", "MatrixMatrixMult_DDRM", ".", "multTransAB_aux", "(", "alpha", ",", "a", ",", "b", ",", "c", ",", "null", ")", ";", "}", "else", "{", "MatrixMatrixMult_DDRM", ".", "multTransAB", "(", "alpha", ",", "a", ",", "b", ",", "c", ")", ";", "}", "}" ]
<p> Performs the following operation:<br> <br> c = &alpha; * a<sup>T</sup> * b<sup>T</sup><br> c<sub>ij</sub> = &alpha; &sum;<sub>k=1:n</sub> { a<sub>ki</sub> * b<sub>jk</sub>} </p> @param alpha Scaling factor. @param a The left matrix in the multiplication operation. Not modified. @param b The right matrix in the multiplication operation. Not modified. @param c Where the results of the operation are stored. Modified.
[ "<p", ">", "Performs", "the", "following", "operation", ":", "<br", ">", "<br", ">", "c", "=", "&alpha", ";", "*", "a<sup", ">", "T<", "/", "sup", ">", "*", "b<sup", ">", "T<", "/", "sup", ">", "<br", ">", "c<sub", ">", "ij<", "/", "sub", ">", "=", "&alpha", ";", "&sum", ";", "<sub", ">", "k", "=", "1", ":", "n<", "/", "sub", ">", "{", "a<sub", ">", "ki<", "/", "sub", ">", "*", "b<sub", ">", "jk<", "/", "sub", ">", "}", "<", "/", "p", ">" ]
train
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/row/CommonOps_DDRM.java#L244-L252
ops4j/org.ops4j.pax.wicket
spi/blueprint/src/main/java/org/ops4j/pax/wicket/spi/blueprint/injection/blueprint/AbstractBlueprintBeanDefinitionParser.java
AbstractBlueprintBeanDefinitionParser.createStringValue
protected ValueMetadata createStringValue(ParserContext context, String str) { """ <p>createStringValue.</p> @param context a {@link org.apache.aries.blueprint.ParserContext} object. @param str a {@link java.lang.String} object. @return a {@link org.osgi.service.blueprint.reflect.ValueMetadata} object. """ MutableValueMetadata value = context.createMetadata(MutableValueMetadata.class); value.setStringValue(str); return value; }
java
protected ValueMetadata createStringValue(ParserContext context, String str) { MutableValueMetadata value = context.createMetadata(MutableValueMetadata.class); value.setStringValue(str); return value; }
[ "protected", "ValueMetadata", "createStringValue", "(", "ParserContext", "context", ",", "String", "str", ")", "{", "MutableValueMetadata", "value", "=", "context", ".", "createMetadata", "(", "MutableValueMetadata", ".", "class", ")", ";", "value", ".", "setStringValue", "(", "str", ")", ";", "return", "value", ";", "}" ]
<p>createStringValue.</p> @param context a {@link org.apache.aries.blueprint.ParserContext} object. @param str a {@link java.lang.String} object. @return a {@link org.osgi.service.blueprint.reflect.ValueMetadata} object.
[ "<p", ">", "createStringValue", ".", "<", "/", "p", ">" ]
train
https://github.com/ops4j/org.ops4j.pax.wicket/blob/ef7cb4bdf918e9e61ec69789b9c690567616faa9/spi/blueprint/src/main/java/org/ops4j/pax/wicket/spi/blueprint/injection/blueprint/AbstractBlueprintBeanDefinitionParser.java#L174-L178
tango-controls/JTango
server/src/main/java/org/tango/server/servant/DeviceImpl.java
DeviceImpl.read_attribute_history_5
@Override public DevAttrHistory_5 read_attribute_history_5(final String attributeName, final int maxSize) throws DevFailed { """ read an attribute history. IDL 5 version. The history is filled only be attribute polling @param attributeName The attribute to retrieve @param maxSize The history maximum size returned @throws DevFailed """ MDC.setContextMap(contextMap); xlogger.entry(); checkInitialization(); deviceMonitoring.startRequest("read_attribute_history_5"); DevAttrHistory_5 result = null; try { final AttributeImpl attr = AttributeGetterSetter.getAttribute(attributeName, attributeList); if (attr.getBehavior() instanceof ForwardedAttribute) { final ForwardedAttribute fwdAttr = (ForwardedAttribute) attr.getBehavior(); result = fwdAttr.getAttributeHistory(maxSize); } else { if (!attr.isPolled()) { throw DevFailedUtils.newDevFailed(ExceptionMessages.ATTR_NOT_POLLED, attr.getName() + " is not polled"); } result = attr.getHistory().getAttrHistory5(maxSize); } } catch (final Exception e) { deviceMonitoring.addError(); if (e instanceof DevFailed) { throw (DevFailed) e; } else { // with CORBA, the stack trace is not visible by the client if // not inserted in DevFailed. throw DevFailedUtils.newDevFailed(e); } } return result; }
java
@Override public DevAttrHistory_5 read_attribute_history_5(final String attributeName, final int maxSize) throws DevFailed { MDC.setContextMap(contextMap); xlogger.entry(); checkInitialization(); deviceMonitoring.startRequest("read_attribute_history_5"); DevAttrHistory_5 result = null; try { final AttributeImpl attr = AttributeGetterSetter.getAttribute(attributeName, attributeList); if (attr.getBehavior() instanceof ForwardedAttribute) { final ForwardedAttribute fwdAttr = (ForwardedAttribute) attr.getBehavior(); result = fwdAttr.getAttributeHistory(maxSize); } else { if (!attr.isPolled()) { throw DevFailedUtils.newDevFailed(ExceptionMessages.ATTR_NOT_POLLED, attr.getName() + " is not polled"); } result = attr.getHistory().getAttrHistory5(maxSize); } } catch (final Exception e) { deviceMonitoring.addError(); if (e instanceof DevFailed) { throw (DevFailed) e; } else { // with CORBA, the stack trace is not visible by the client if // not inserted in DevFailed. throw DevFailedUtils.newDevFailed(e); } } return result; }
[ "@", "Override", "public", "DevAttrHistory_5", "read_attribute_history_5", "(", "final", "String", "attributeName", ",", "final", "int", "maxSize", ")", "throws", "DevFailed", "{", "MDC", ".", "setContextMap", "(", "contextMap", ")", ";", "xlogger", ".", "entry", "(", ")", ";", "checkInitialization", "(", ")", ";", "deviceMonitoring", ".", "startRequest", "(", "\"read_attribute_history_5\"", ")", ";", "DevAttrHistory_5", "result", "=", "null", ";", "try", "{", "final", "AttributeImpl", "attr", "=", "AttributeGetterSetter", ".", "getAttribute", "(", "attributeName", ",", "attributeList", ")", ";", "if", "(", "attr", ".", "getBehavior", "(", ")", "instanceof", "ForwardedAttribute", ")", "{", "final", "ForwardedAttribute", "fwdAttr", "=", "(", "ForwardedAttribute", ")", "attr", ".", "getBehavior", "(", ")", ";", "result", "=", "fwdAttr", ".", "getAttributeHistory", "(", "maxSize", ")", ";", "}", "else", "{", "if", "(", "!", "attr", ".", "isPolled", "(", ")", ")", "{", "throw", "DevFailedUtils", ".", "newDevFailed", "(", "ExceptionMessages", ".", "ATTR_NOT_POLLED", ",", "attr", ".", "getName", "(", ")", "+", "\" is not polled\"", ")", ";", "}", "result", "=", "attr", ".", "getHistory", "(", ")", ".", "getAttrHistory5", "(", "maxSize", ")", ";", "}", "}", "catch", "(", "final", "Exception", "e", ")", "{", "deviceMonitoring", ".", "addError", "(", ")", ";", "if", "(", "e", "instanceof", "DevFailed", ")", "{", "throw", "(", "DevFailed", ")", "e", ";", "}", "else", "{", "// with CORBA, the stack trace is not visible by the client if", "// not inserted in DevFailed.", "throw", "DevFailedUtils", ".", "newDevFailed", "(", "e", ")", ";", "}", "}", "return", "result", ";", "}" ]
read an attribute history. IDL 5 version. The history is filled only be attribute polling @param attributeName The attribute to retrieve @param maxSize The history maximum size returned @throws DevFailed
[ "read", "an", "attribute", "history", ".", "IDL", "5", "version", ".", "The", "history", "is", "filled", "only", "be", "attribute", "polling" ]
train
https://github.com/tango-controls/JTango/blob/1ccc9dcb83e6de2359a9f1906d170571cacf1345/server/src/main/java/org/tango/server/servant/DeviceImpl.java#L2540-L2571
OpenLiberty/open-liberty
dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ws/ejbcontainer/jitdeploy/JIT_Tie.java
JIT_Tie.initializeStaticFields
private static void initializeStaticFields(ClassWriter cw, String tieClassName, Class<?> remoteInterface) { """ Initializes the static variables common to all Tie classes. <p> _type_ids = { "RMI:<remote interface name>:0000000000000000", "RMI:<remote interface parent>:0000000000000000", etc... }; Note: unlike a Tie generated with RMIC from the generated wrapper, the _type_ids field for JIT Deploy Ties do NOT include CSIServant or TransactionalObject. These are WebSphere implementation details that should NOT be exposed through the Tie/Stub. <p> @param cw ASM ClassWriter to add the fields to. @param tieClassName fully qualified name of the Tie class with '/' as the separator character (i.e. internal name). @param remoteInterface remote business or component interface represented by this Tie. """ GeneratorAdapter mg; final boolean isTraceOn = TraceComponent.isAnyTracingEnabled(); // d576626 // ----------------------------------------------------------------------- // Static fields are initialized in a class constructor method // ----------------------------------------------------------------------- if (isTraceOn && tc.isDebugEnabled()) Tr.debug(tc, INDENT + "adding method : <clinit> ()V"); org.objectweb.asm.commons.Method m = new org.objectweb.asm.commons.Method ("<clinit>", VOID_TYPE, new Type[0]); mg = new GeneratorAdapter(ACC_STATIC, m, null, null, cw); mg.visitCode(); // ----------------------------------------------------------------------- // Initialize Static Fields // // _type_ids = { "RMI:<remote interface name>:0000000000000000", // "RMI:<remote interface parent>:0000000000000000", // etc... }; // ----------------------------------------------------------------------- String[] remoteTypes = getRemoteTypeIds(remoteInterface); mg.push(remoteTypes.length); mg.visitTypeInsn(ANEWARRAY, "java/lang/String"); for (int i = 0; i < remoteTypes.length; ++i) { if (isTraceOn && tc.isDebugEnabled()) Tr.debug(tc, INDENT + " _type_ids = " + remoteTypes[i]); mg.visitInsn(DUP); mg.push(i); mg.visitLdcInsn(remoteTypes[i]); mg.visitInsn(AASTORE); } mg.visitFieldInsn(PUTSTATIC, tieClassName, "_type_ids", "[Ljava/lang/String;"); // ----------------------------------------------------------------------- // End Method Code... // ----------------------------------------------------------------------- mg.visitInsn(RETURN); mg.endMethod(); // GeneratorAdapter accounts for visitMaxs(x,y) mg.visitEnd(); }
java
private static void initializeStaticFields(ClassWriter cw, String tieClassName, Class<?> remoteInterface) { GeneratorAdapter mg; final boolean isTraceOn = TraceComponent.isAnyTracingEnabled(); // d576626 // ----------------------------------------------------------------------- // Static fields are initialized in a class constructor method // ----------------------------------------------------------------------- if (isTraceOn && tc.isDebugEnabled()) Tr.debug(tc, INDENT + "adding method : <clinit> ()V"); org.objectweb.asm.commons.Method m = new org.objectweb.asm.commons.Method ("<clinit>", VOID_TYPE, new Type[0]); mg = new GeneratorAdapter(ACC_STATIC, m, null, null, cw); mg.visitCode(); // ----------------------------------------------------------------------- // Initialize Static Fields // // _type_ids = { "RMI:<remote interface name>:0000000000000000", // "RMI:<remote interface parent>:0000000000000000", // etc... }; // ----------------------------------------------------------------------- String[] remoteTypes = getRemoteTypeIds(remoteInterface); mg.push(remoteTypes.length); mg.visitTypeInsn(ANEWARRAY, "java/lang/String"); for (int i = 0; i < remoteTypes.length; ++i) { if (isTraceOn && tc.isDebugEnabled()) Tr.debug(tc, INDENT + " _type_ids = " + remoteTypes[i]); mg.visitInsn(DUP); mg.push(i); mg.visitLdcInsn(remoteTypes[i]); mg.visitInsn(AASTORE); } mg.visitFieldInsn(PUTSTATIC, tieClassName, "_type_ids", "[Ljava/lang/String;"); // ----------------------------------------------------------------------- // End Method Code... // ----------------------------------------------------------------------- mg.visitInsn(RETURN); mg.endMethod(); // GeneratorAdapter accounts for visitMaxs(x,y) mg.visitEnd(); }
[ "private", "static", "void", "initializeStaticFields", "(", "ClassWriter", "cw", ",", "String", "tieClassName", ",", "Class", "<", "?", ">", "remoteInterface", ")", "{", "GeneratorAdapter", "mg", ";", "final", "boolean", "isTraceOn", "=", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", ";", "// d576626", "// -----------------------------------------------------------------------", "// Static fields are initialized in a class constructor method", "// -----------------------------------------------------------------------", "if", "(", "isTraceOn", "&&", "tc", ".", "isDebugEnabled", "(", ")", ")", "Tr", ".", "debug", "(", "tc", ",", "INDENT", "+", "\"adding method : <clinit> ()V\"", ")", ";", "org", ".", "objectweb", ".", "asm", ".", "commons", ".", "Method", "m", "=", "new", "org", ".", "objectweb", ".", "asm", ".", "commons", ".", "Method", "(", "\"<clinit>\"", ",", "VOID_TYPE", ",", "new", "Type", "[", "0", "]", ")", ";", "mg", "=", "new", "GeneratorAdapter", "(", "ACC_STATIC", ",", "m", ",", "null", ",", "null", ",", "cw", ")", ";", "mg", ".", "visitCode", "(", ")", ";", "// -----------------------------------------------------------------------", "// Initialize Static Fields", "//", "// _type_ids = { \"RMI:<remote interface name>:0000000000000000\",", "// \"RMI:<remote interface parent>:0000000000000000\",", "// etc... };", "// -----------------------------------------------------------------------", "String", "[", "]", "remoteTypes", "=", "getRemoteTypeIds", "(", "remoteInterface", ")", ";", "mg", ".", "push", "(", "remoteTypes", ".", "length", ")", ";", "mg", ".", "visitTypeInsn", "(", "ANEWARRAY", ",", "\"java/lang/String\"", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "remoteTypes", ".", "length", ";", "++", "i", ")", "{", "if", "(", "isTraceOn", "&&", "tc", ".", "isDebugEnabled", "(", ")", ")", "Tr", ".", "debug", "(", "tc", ",", "INDENT", "+", "\" _type_ids = \"", "+", "remoteTypes", "[", "i", "]", ")", ";", "mg", ".", "visitInsn", "(", "DUP", ")", ";", "mg", ".", "push", "(", "i", ")", ";", "mg", ".", "visitLdcInsn", "(", "remoteTypes", "[", "i", "]", ")", ";", "mg", ".", "visitInsn", "(", "AASTORE", ")", ";", "}", "mg", ".", "visitFieldInsn", "(", "PUTSTATIC", ",", "tieClassName", ",", "\"_type_ids\"", ",", "\"[Ljava/lang/String;\"", ")", ";", "// -----------------------------------------------------------------------", "// End Method Code...", "// -----------------------------------------------------------------------", "mg", ".", "visitInsn", "(", "RETURN", ")", ";", "mg", ".", "endMethod", "(", ")", ";", "// GeneratorAdapter accounts for visitMaxs(x,y)", "mg", ".", "visitEnd", "(", ")", ";", "}" ]
Initializes the static variables common to all Tie classes. <p> _type_ids = { "RMI:<remote interface name>:0000000000000000", "RMI:<remote interface parent>:0000000000000000", etc... }; Note: unlike a Tie generated with RMIC from the generated wrapper, the _type_ids field for JIT Deploy Ties do NOT include CSIServant or TransactionalObject. These are WebSphere implementation details that should NOT be exposed through the Tie/Stub. <p> @param cw ASM ClassWriter to add the fields to. @param tieClassName fully qualified name of the Tie class with '/' as the separator character (i.e. internal name). @param remoteInterface remote business or component interface represented by this Tie.
[ "Initializes", "the", "static", "variables", "common", "to", "all", "Tie", "classes", ".", "<p", ">" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ws/ejbcontainer/jitdeploy/JIT_Tie.java#L313-L363
xdcrafts/flower
flower-tools/src/main/java/com/github/xdcrafts/flower/tools/ListApi.java
ListApi.getList
public static <T> Optional<List<T>> getList(final List list, final Class<T> clazz, final Integer... path) { """ Get list value by path. @param <T> list value type @param clazz type of value @param list subject @param path nodes to walk in map @return value """ return get(list, List.class, path).map(c -> (List<T>) c); }
java
public static <T> Optional<List<T>> getList(final List list, final Class<T> clazz, final Integer... path) { return get(list, List.class, path).map(c -> (List<T>) c); }
[ "public", "static", "<", "T", ">", "Optional", "<", "List", "<", "T", ">", ">", "getList", "(", "final", "List", "list", ",", "final", "Class", "<", "T", ">", "clazz", ",", "final", "Integer", "...", "path", ")", "{", "return", "get", "(", "list", ",", "List", ".", "class", ",", "path", ")", ".", "map", "(", "c", "->", "(", "List", "<", "T", ">", ")", "c", ")", ";", "}" ]
Get list value by path. @param <T> list value type @param clazz type of value @param list subject @param path nodes to walk in map @return value
[ "Get", "list", "value", "by", "path", "." ]
train
https://github.com/xdcrafts/flower/blob/96a8e49102fea434bd383a3c7852f0ee9545f999/flower-tools/src/main/java/com/github/xdcrafts/flower/tools/ListApi.java#L208-L210
apache/groovy
subprojects/groovy-nio/src/main/java/org/codehaus/groovy/runtime/NioGroovyMethods.java
NioGroovyMethods.eachDirRecurse
public static void eachDirRecurse(final Path self, @ClosureParams(value = SimpleType.class, options = "java.nio.file.Path") final Closure closure) throws IOException { """ Recursively processes each descendant subdirectory in this directory. Processing consists of calling <code>closure</code> passing it the current subdirectory and then recursively processing that subdirectory. Regular files are ignored during traversal. @param self a Path (that happens to be a folder/directory) @param closure a closure @throws java.io.FileNotFoundException if the given directory does not exist @throws IllegalArgumentException if the provided Path object does not represent a directory @see #eachFileRecurse(Path, groovy.io.FileType, groovy.lang.Closure) @since 2.3.0 """ //throws FileNotFoundException, IllegalArgumentException { eachFileRecurse(self, FileType.DIRECTORIES, closure); }
java
public static void eachDirRecurse(final Path self, @ClosureParams(value = SimpleType.class, options = "java.nio.file.Path") final Closure closure) throws IOException { //throws FileNotFoundException, IllegalArgumentException { eachFileRecurse(self, FileType.DIRECTORIES, closure); }
[ "public", "static", "void", "eachDirRecurse", "(", "final", "Path", "self", ",", "@", "ClosureParams", "(", "value", "=", "SimpleType", ".", "class", ",", "options", "=", "\"java.nio.file.Path\"", ")", "final", "Closure", "closure", ")", "throws", "IOException", "{", "//throws FileNotFoundException, IllegalArgumentException {", "eachFileRecurse", "(", "self", ",", "FileType", ".", "DIRECTORIES", ",", "closure", ")", ";", "}" ]
Recursively processes each descendant subdirectory in this directory. Processing consists of calling <code>closure</code> passing it the current subdirectory and then recursively processing that subdirectory. Regular files are ignored during traversal. @param self a Path (that happens to be a folder/directory) @param closure a closure @throws java.io.FileNotFoundException if the given directory does not exist @throws IllegalArgumentException if the provided Path object does not represent a directory @see #eachFileRecurse(Path, groovy.io.FileType, groovy.lang.Closure) @since 2.3.0
[ "Recursively", "processes", "each", "descendant", "subdirectory", "in", "this", "directory", ".", "Processing", "consists", "of", "calling", "<code", ">", "closure<", "/", "code", ">", "passing", "it", "the", "current", "subdirectory", "and", "then", "recursively", "processing", "that", "subdirectory", ".", "Regular", "files", "are", "ignored", "during", "traversal", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-nio/src/main/java/org/codehaus/groovy/runtime/NioGroovyMethods.java#L1186-L1188
PeterisP/LVTagger
src/main/java/edu/stanford/nlp/stats/Counters.java
Counters.subtractInPlace
public static <E> void subtractInPlace(double[] target, Counter<E> arg, Index<E> idx) { """ Sets each value of double[] target to be target[idx.indexOf(k)]-a.getCount(k) for all keys k in arg """ for (Map.Entry<E, Double> entry : arg.entrySet()) { target[idx.indexOf(entry.getKey())] -= entry.getValue(); } }
java
public static <E> void subtractInPlace(double[] target, Counter<E> arg, Index<E> idx) { for (Map.Entry<E, Double> entry : arg.entrySet()) { target[idx.indexOf(entry.getKey())] -= entry.getValue(); } }
[ "public", "static", "<", "E", ">", "void", "subtractInPlace", "(", "double", "[", "]", "target", ",", "Counter", "<", "E", ">", "arg", ",", "Index", "<", "E", ">", "idx", ")", "{", "for", "(", "Map", ".", "Entry", "<", "E", ",", "Double", ">", "entry", ":", "arg", ".", "entrySet", "(", ")", ")", "{", "target", "[", "idx", ".", "indexOf", "(", "entry", ".", "getKey", "(", ")", ")", "]", "-=", "entry", ".", "getValue", "(", ")", ";", "}", "}" ]
Sets each value of double[] target to be target[idx.indexOf(k)]-a.getCount(k) for all keys k in arg
[ "Sets", "each", "value", "of", "double", "[]", "target", "to", "be", "target", "[", "idx", ".", "indexOf", "(", "k", ")", "]", "-", "a", ".", "getCount", "(", "k", ")", "for", "all", "keys", "k", "in", "arg" ]
train
https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/stats/Counters.java#L402-L406
gallandarakhneorg/afc
core/text/src/main/java/org/arakhne/afc/text/TextUtil.java
TextUtil.equalsIgnoreAccents
@Pure @Inline(value = "TextUtil.removeAccents($1, $3).equals(TextUtil.removeAccents($2, $3))", imported = { """ Compares this <code>String</code> to another <code>String</code>, ignoring accent considerations. Two strings are considered equal ignoring accents if they are of the same length, and corresponding characters in the two strings are equal ignoring accents. <p>This method is equivalent to: <pre><code> TextUtil.removeAccents(s1,map).equals(TextUtil.removeAccents(s2,map)); </code></pre> @param s1 is the first string to compare. @param s2 is the second string to compare. @param map is the translation table from an accentuated character to an unaccentuated character. @return <code>true</code> if the argument is not <code>null</code> and the <code>String</code>s are equal, ignoring case; <code>false</code> otherwise. @see #removeAccents(String, Map) """TextUtil.class}) public static boolean equalsIgnoreAccents(String s1, String s2, Map<Character, String> map) { return removeAccents(s1, map).equals(removeAccents(s2, map)); }
java
@Pure @Inline(value = "TextUtil.removeAccents($1, $3).equals(TextUtil.removeAccents($2, $3))", imported = {TextUtil.class}) public static boolean equalsIgnoreAccents(String s1, String s2, Map<Character, String> map) { return removeAccents(s1, map).equals(removeAccents(s2, map)); }
[ "@", "Pure", "@", "Inline", "(", "value", "=", "\"TextUtil.removeAccents($1, $3).equals(TextUtil.removeAccents($2, $3))\"", ",", "imported", "=", "{", "TextUtil", ".", "class", "}", ")", "public", "static", "boolean", "equalsIgnoreAccents", "(", "String", "s1", ",", "String", "s2", ",", "Map", "<", "Character", ",", "String", ">", "map", ")", "{", "return", "removeAccents", "(", "s1", ",", "map", ")", ".", "equals", "(", "removeAccents", "(", "s2", ",", "map", ")", ")", ";", "}" ]
Compares this <code>String</code> to another <code>String</code>, ignoring accent considerations. Two strings are considered equal ignoring accents if they are of the same length, and corresponding characters in the two strings are equal ignoring accents. <p>This method is equivalent to: <pre><code> TextUtil.removeAccents(s1,map).equals(TextUtil.removeAccents(s2,map)); </code></pre> @param s1 is the first string to compare. @param s2 is the second string to compare. @param map is the translation table from an accentuated character to an unaccentuated character. @return <code>true</code> if the argument is not <code>null</code> and the <code>String</code>s are equal, ignoring case; <code>false</code> otherwise. @see #removeAccents(String, Map)
[ "Compares", "this", "<code", ">", "String<", "/", "code", ">", "to", "another", "<code", ">", "String<", "/", "code", ">", "ignoring", "accent", "considerations", ".", "Two", "strings", "are", "considered", "equal", "ignoring", "accents", "if", "they", "are", "of", "the", "same", "length", "and", "corresponding", "characters", "in", "the", "two", "strings", "are", "equal", "ignoring", "accents", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/text/src/main/java/org/arakhne/afc/text/TextUtil.java#L1350-L1354
netscaler/nitro
src/main/java/com/citrix/netscaler/nitro/resource/stat/dns/dns_stats.java
dns_stats.get_nitro_response
protected base_resource[] get_nitro_response(nitro_service service, String response) throws Exception { """ <pre> converts nitro response into object and returns the object array in case of get request. </pre> """ dns_stats[] resources = new dns_stats[1]; dns_response result = (dns_response) service.get_payload_formatter().string_to_resource(dns_response.class, response); if(result.errorcode != 0) { if (result.errorcode == 444) { service.clear_session(); } if(result.severity != null) { if (result.severity.equals("ERROR")) throw new nitro_exception(result.message,result.errorcode); } else { throw new nitro_exception(result.message,result.errorcode); } } resources[0] = result.dns; return resources; }
java
protected base_resource[] get_nitro_response(nitro_service service, String response) throws Exception { dns_stats[] resources = new dns_stats[1]; dns_response result = (dns_response) service.get_payload_formatter().string_to_resource(dns_response.class, response); if(result.errorcode != 0) { if (result.errorcode == 444) { service.clear_session(); } if(result.severity != null) { if (result.severity.equals("ERROR")) throw new nitro_exception(result.message,result.errorcode); } else { throw new nitro_exception(result.message,result.errorcode); } } resources[0] = result.dns; return resources; }
[ "protected", "base_resource", "[", "]", "get_nitro_response", "(", "nitro_service", "service", ",", "String", "response", ")", "throws", "Exception", "{", "dns_stats", "[", "]", "resources", "=", "new", "dns_stats", "[", "1", "]", ";", "dns_response", "result", "=", "(", "dns_response", ")", "service", ".", "get_payload_formatter", "(", ")", ".", "string_to_resource", "(", "dns_response", ".", "class", ",", "response", ")", ";", "if", "(", "result", ".", "errorcode", "!=", "0", ")", "{", "if", "(", "result", ".", "errorcode", "==", "444", ")", "{", "service", ".", "clear_session", "(", ")", ";", "}", "if", "(", "result", ".", "severity", "!=", "null", ")", "{", "if", "(", "result", ".", "severity", ".", "equals", "(", "\"ERROR\"", ")", ")", "throw", "new", "nitro_exception", "(", "result", ".", "message", ",", "result", ".", "errorcode", ")", ";", "}", "else", "{", "throw", "new", "nitro_exception", "(", "result", ".", "message", ",", "result", ".", "errorcode", ")", ";", "}", "}", "resources", "[", "0", "]", "=", "result", ".", "dns", ";", "return", "resources", ";", "}" ]
<pre> converts nitro response into object and returns the object array in case of get request. </pre>
[ "<pre", ">", "converts", "nitro", "response", "into", "object", "and", "returns", "the", "object", "array", "in", "case", "of", "get", "request", ".", "<", "/", "pre", ">" ]
train
https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/stat/dns/dns_stats.java#L1177-L1196
ModeShape/modeshape
modeshape-jcr/src/main/java/org/modeshape/jcr/AbstractJcrNode.java
AbstractJcrNode.setProperty
final AbstractJcrProperty setProperty( Name name, Value[] values, int jcrPropertyType, boolean skipReferenceValidation ) throws VersionException, LockException, ConstraintViolationException, RepositoryException { """ Sets a multi valued property, skipping over protected ones. @param name the name of the property; may not be null @param values the values of the property; may not be null @param jcrPropertyType the expected property type; may be {@link PropertyType#UNDEFINED} if the values should not be converted @param skipReferenceValidation indicates whether constraints on REFERENCE properties should be enforced @return the new JCR property object @throws VersionException if the node is checked out @throws LockException if the node is locked @throws ConstraintViolationException if the new value would violate the constraints on the property definition @throws RepositoryException if the named property does not exist, or if some other error occurred """ return setProperty(name, values, jcrPropertyType, false, skipReferenceValidation, false, false); }
java
final AbstractJcrProperty setProperty( Name name, Value[] values, int jcrPropertyType, boolean skipReferenceValidation ) throws VersionException, LockException, ConstraintViolationException, RepositoryException { return setProperty(name, values, jcrPropertyType, false, skipReferenceValidation, false, false); }
[ "final", "AbstractJcrProperty", "setProperty", "(", "Name", "name", ",", "Value", "[", "]", "values", ",", "int", "jcrPropertyType", ",", "boolean", "skipReferenceValidation", ")", "throws", "VersionException", ",", "LockException", ",", "ConstraintViolationException", ",", "RepositoryException", "{", "return", "setProperty", "(", "name", ",", "values", ",", "jcrPropertyType", ",", "false", ",", "skipReferenceValidation", ",", "false", ",", "false", ")", ";", "}" ]
Sets a multi valued property, skipping over protected ones. @param name the name of the property; may not be null @param values the values of the property; may not be null @param jcrPropertyType the expected property type; may be {@link PropertyType#UNDEFINED} if the values should not be converted @param skipReferenceValidation indicates whether constraints on REFERENCE properties should be enforced @return the new JCR property object @throws VersionException if the node is checked out @throws LockException if the node is locked @throws ConstraintViolationException if the new value would violate the constraints on the property definition @throws RepositoryException if the named property does not exist, or if some other error occurred
[ "Sets", "a", "multi", "valued", "property", "skipping", "over", "protected", "ones", "." ]
train
https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-jcr/src/main/java/org/modeshape/jcr/AbstractJcrNode.java#L1823-L1829
rzwitserloot/lombok
src/core/lombok/javac/handlers/JavacHandlerUtil.java
JavacHandlerUtil.createAnnotation
public static <A extends Annotation> AnnotationValues<A> createAnnotation(Class<A> type, final JavacNode node) { """ Creates an instance of {@code AnnotationValues} for the provided AST Node. @param type An annotation class type, such as {@code lombok.Getter.class}. @param node A Lombok AST node representing an annotation in source code. """ return createAnnotation(type, (JCAnnotation) node.get(), node); }
java
public static <A extends Annotation> AnnotationValues<A> createAnnotation(Class<A> type, final JavacNode node) { return createAnnotation(type, (JCAnnotation) node.get(), node); }
[ "public", "static", "<", "A", "extends", "Annotation", ">", "AnnotationValues", "<", "A", ">", "createAnnotation", "(", "Class", "<", "A", ">", "type", ",", "final", "JavacNode", "node", ")", "{", "return", "createAnnotation", "(", "type", ",", "(", "JCAnnotation", ")", "node", ".", "get", "(", ")", ",", "node", ")", ";", "}" ]
Creates an instance of {@code AnnotationValues} for the provided AST Node. @param type An annotation class type, such as {@code lombok.Getter.class}. @param node A Lombok AST node representing an annotation in source code.
[ "Creates", "an", "instance", "of", "{", "@code", "AnnotationValues", "}", "for", "the", "provided", "AST", "Node", "." ]
train
https://github.com/rzwitserloot/lombok/blob/75601240760bd81ff95fcde7a1b8185769ce64e8/src/core/lombok/javac/handlers/JavacHandlerUtil.java#L350-L352
jamesagnew/hapi-fhir
hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/SearchBuilder.java
SearchBuilder.calculateFuzzAmount
static BigDecimal calculateFuzzAmount(ParamPrefixEnum cmpValue, BigDecimal theValue) { """ Figures out the tolerance for a search. For example, if the user is searching for <code>4.00</code>, this method returns <code>0.005</code> because we shold actually match values which are <code>4 (+/-) 0.005</code> according to the FHIR specs. """ if (cmpValue == ParamPrefixEnum.APPROXIMATE) { return theValue.multiply(new BigDecimal(0.1)); } else { String plainString = theValue.toPlainString(); int dotIdx = plainString.indexOf('.'); if (dotIdx == -1) { return new BigDecimal(0.5); } int precision = plainString.length() - (dotIdx); double mul = Math.pow(10, -precision); double val = mul * 5.0d; return new BigDecimal(val); } }
java
static BigDecimal calculateFuzzAmount(ParamPrefixEnum cmpValue, BigDecimal theValue) { if (cmpValue == ParamPrefixEnum.APPROXIMATE) { return theValue.multiply(new BigDecimal(0.1)); } else { String plainString = theValue.toPlainString(); int dotIdx = plainString.indexOf('.'); if (dotIdx == -1) { return new BigDecimal(0.5); } int precision = plainString.length() - (dotIdx); double mul = Math.pow(10, -precision); double val = mul * 5.0d; return new BigDecimal(val); } }
[ "static", "BigDecimal", "calculateFuzzAmount", "(", "ParamPrefixEnum", "cmpValue", ",", "BigDecimal", "theValue", ")", "{", "if", "(", "cmpValue", "==", "ParamPrefixEnum", ".", "APPROXIMATE", ")", "{", "return", "theValue", ".", "multiply", "(", "new", "BigDecimal", "(", "0.1", ")", ")", ";", "}", "else", "{", "String", "plainString", "=", "theValue", ".", "toPlainString", "(", ")", ";", "int", "dotIdx", "=", "plainString", ".", "indexOf", "(", "'", "'", ")", ";", "if", "(", "dotIdx", "==", "-", "1", ")", "{", "return", "new", "BigDecimal", "(", "0.5", ")", ";", "}", "int", "precision", "=", "plainString", ".", "length", "(", ")", "-", "(", "dotIdx", ")", ";", "double", "mul", "=", "Math", ".", "pow", "(", "10", ",", "-", "precision", ")", ";", "double", "val", "=", "mul", "*", "5.0d", ";", "return", "new", "BigDecimal", "(", "val", ")", ";", "}", "}" ]
Figures out the tolerance for a search. For example, if the user is searching for <code>4.00</code>, this method returns <code>0.005</code> because we shold actually match values which are <code>4 (+/-) 0.005</code> according to the FHIR specs.
[ "Figures", "out", "the", "tolerance", "for", "a", "search", ".", "For", "example", "if", "the", "user", "is", "searching", "for", "<code", ">", "4", ".", "00<", "/", "code", ">", "this", "method", "returns", "<code", ">", "0", ".", "005<", "/", "code", ">", "because", "we", "shold", "actually", "match", "values", "which", "are", "<code", ">", "4", "(", "+", "/", "-", ")", "0", ".", "005<", "/", "code", ">", "according", "to", "the", "FHIR", "specs", "." ]
train
https://github.com/jamesagnew/hapi-fhir/blob/150a84d52fe691b7f48fcb28247c4bddb7aec352/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/SearchBuilder.java#L2695-L2710
rholder/moar-concurrent
src/main/java/com/github/rholder/moar/concurrent/StrategicExecutors.java
StrategicExecutors.newBalancingThreadPoolExecutor
public static BalancingThreadPoolExecutor newBalancingThreadPoolExecutor(ThreadPoolExecutor tpe, float targetUtilization, float smoothingWeight, int balanceAfter) { """ Return a {@link BalancingThreadPoolExecutor} with the given {@link ThreadPoolExecutor}, target utilization, smoothing weight, and balance after values. @param tpe the underlying executor to use for this instance @param targetUtilization a float between 0.0 and 1.0 representing the percentage of the total CPU time to be used by this pool @param smoothingWeight smooth out the averages of the CPU and wait time over time such that tasks aren't too heavily skewed with old or spiking data @param balanceAfter balance the thread pool after this many tasks have run """ ThreadProfiler tp = new MXBeanThreadProfiler(); return new BalancingThreadPoolExecutor(tpe, tp, targetUtilization, smoothingWeight, balanceAfter); }
java
public static BalancingThreadPoolExecutor newBalancingThreadPoolExecutor(ThreadPoolExecutor tpe, float targetUtilization, float smoothingWeight, int balanceAfter) { ThreadProfiler tp = new MXBeanThreadProfiler(); return new BalancingThreadPoolExecutor(tpe, tp, targetUtilization, smoothingWeight, balanceAfter); }
[ "public", "static", "BalancingThreadPoolExecutor", "newBalancingThreadPoolExecutor", "(", "ThreadPoolExecutor", "tpe", ",", "float", "targetUtilization", ",", "float", "smoothingWeight", ",", "int", "balanceAfter", ")", "{", "ThreadProfiler", "tp", "=", "new", "MXBeanThreadProfiler", "(", ")", ";", "return", "new", "BalancingThreadPoolExecutor", "(", "tpe", ",", "tp", ",", "targetUtilization", ",", "smoothingWeight", ",", "balanceAfter", ")", ";", "}" ]
Return a {@link BalancingThreadPoolExecutor} with the given {@link ThreadPoolExecutor}, target utilization, smoothing weight, and balance after values. @param tpe the underlying executor to use for this instance @param targetUtilization a float between 0.0 and 1.0 representing the percentage of the total CPU time to be used by this pool @param smoothingWeight smooth out the averages of the CPU and wait time over time such that tasks aren't too heavily skewed with old or spiking data @param balanceAfter balance the thread pool after this many tasks have run
[ "Return", "a", "{", "@link", "BalancingThreadPoolExecutor", "}", "with", "the", "given", "{", "@link", "ThreadPoolExecutor", "}", "target", "utilization", "smoothing", "weight", "and", "balance", "after", "values", "." ]
train
https://github.com/rholder/moar-concurrent/blob/c28facbf02e628cc37266c051c23d4a7654b4eba/src/main/java/com/github/rholder/moar/concurrent/StrategicExecutors.java#L90-L96
prestodb/presto
presto-raptor/src/main/java/com/facebook/presto/raptor/util/RebindSafeMBeanServer.java
RebindSafeMBeanServer.registerMBean
@Override public ObjectInstance registerMBean(Object object, ObjectName name) throws MBeanRegistrationException, NotCompliantMBeanException { """ Delegates to the wrapped mbean server, but if a mbean is already registered with the specified name, the existing instance is returned. """ while (true) { try { // try to register the mbean return mbeanServer.registerMBean(object, name); } catch (InstanceAlreadyExistsException ignored) { } try { // a mbean is already installed, try to return the already registered instance ObjectInstance objectInstance = mbeanServer.getObjectInstance(name); log.debug("%s already bound to %s", name, objectInstance); return objectInstance; } catch (InstanceNotFoundException ignored) { // the mbean was removed before we could get the reference // start the whole process over again } } }
java
@Override public ObjectInstance registerMBean(Object object, ObjectName name) throws MBeanRegistrationException, NotCompliantMBeanException { while (true) { try { // try to register the mbean return mbeanServer.registerMBean(object, name); } catch (InstanceAlreadyExistsException ignored) { } try { // a mbean is already installed, try to return the already registered instance ObjectInstance objectInstance = mbeanServer.getObjectInstance(name); log.debug("%s already bound to %s", name, objectInstance); return objectInstance; } catch (InstanceNotFoundException ignored) { // the mbean was removed before we could get the reference // start the whole process over again } } }
[ "@", "Override", "public", "ObjectInstance", "registerMBean", "(", "Object", "object", ",", "ObjectName", "name", ")", "throws", "MBeanRegistrationException", ",", "NotCompliantMBeanException", "{", "while", "(", "true", ")", "{", "try", "{", "// try to register the mbean", "return", "mbeanServer", ".", "registerMBean", "(", "object", ",", "name", ")", ";", "}", "catch", "(", "InstanceAlreadyExistsException", "ignored", ")", "{", "}", "try", "{", "// a mbean is already installed, try to return the already registered instance", "ObjectInstance", "objectInstance", "=", "mbeanServer", ".", "getObjectInstance", "(", "name", ")", ";", "log", ".", "debug", "(", "\"%s already bound to %s\"", ",", "name", ",", "objectInstance", ")", ";", "return", "objectInstance", ";", "}", "catch", "(", "InstanceNotFoundException", "ignored", ")", "{", "// the mbean was removed before we could get the reference", "// start the whole process over again", "}", "}", "}" ]
Delegates to the wrapped mbean server, but if a mbean is already registered with the specified name, the existing instance is returned.
[ "Delegates", "to", "the", "wrapped", "mbean", "server", "but", "if", "a", "mbean", "is", "already", "registered", "with", "the", "specified", "name", "the", "existing", "instance", "is", "returned", "." ]
train
https://github.com/prestodb/presto/blob/89de5e379d8f85e139d292b0add8c537a2a01a88/presto-raptor/src/main/java/com/facebook/presto/raptor/util/RebindSafeMBeanServer.java#L67-L90
albfernandez/itext2
src/main/java/com/lowagie/text/pdf/PdfDashPattern.java
PdfDashPattern.toPdf
public void toPdf(PdfWriter writer, OutputStream os) throws IOException { """ Returns the PDF representation of this <CODE>PdfArray</CODE>. """ os.write('['); if (dash >= 0) { new PdfNumber(dash).toPdf(writer, os); if (gap >= 0) { os.write(' '); new PdfNumber(gap).toPdf(writer, os); } } os.write(']'); if (phase >=0) { os.write(' '); new PdfNumber(phase).toPdf(writer, os); } }
java
public void toPdf(PdfWriter writer, OutputStream os) throws IOException { os.write('['); if (dash >= 0) { new PdfNumber(dash).toPdf(writer, os); if (gap >= 0) { os.write(' '); new PdfNumber(gap).toPdf(writer, os); } } os.write(']'); if (phase >=0) { os.write(' '); new PdfNumber(phase).toPdf(writer, os); } }
[ "public", "void", "toPdf", "(", "PdfWriter", "writer", ",", "OutputStream", "os", ")", "throws", "IOException", "{", "os", ".", "write", "(", "'", "'", ")", ";", "if", "(", "dash", ">=", "0", ")", "{", "new", "PdfNumber", "(", "dash", ")", ".", "toPdf", "(", "writer", ",", "os", ")", ";", "if", "(", "gap", ">=", "0", ")", "{", "os", ".", "write", "(", "'", "'", ")", ";", "new", "PdfNumber", "(", "gap", ")", ".", "toPdf", "(", "writer", ",", "os", ")", ";", "}", "}", "os", ".", "write", "(", "'", "'", ")", ";", "if", "(", "phase", ">=", "0", ")", "{", "os", ".", "write", "(", "'", "'", ")", ";", "new", "PdfNumber", "(", "phase", ")", ".", "toPdf", "(", "writer", ",", "os", ")", ";", "}", "}" ]
Returns the PDF representation of this <CODE>PdfArray</CODE>.
[ "Returns", "the", "PDF", "representation", "of", "this", "<CODE", ">", "PdfArray<", "/", "CODE", ">", "." ]
train
https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/PdfDashPattern.java#L125-L140
kaazing/gateway
util/src/main/java/org/kaazing/gateway/util/Utils.java
Utils.getShort
public static short getShort(ByteBuffer buf, int index) { """ Reads a short value from the buffer starting at the given index relative to the current position() of the buffer, without mutating the buffer in any way (so it's thread safe). """ return buf.order() == BIG_ENDIAN ? getShortB(buf, index) : getShortL(buf, index); }
java
public static short getShort(ByteBuffer buf, int index) { return buf.order() == BIG_ENDIAN ? getShortB(buf, index) : getShortL(buf, index); }
[ "public", "static", "short", "getShort", "(", "ByteBuffer", "buf", ",", "int", "index", ")", "{", "return", "buf", ".", "order", "(", ")", "==", "BIG_ENDIAN", "?", "getShortB", "(", "buf", ",", "index", ")", ":", "getShortL", "(", "buf", ",", "index", ")", ";", "}" ]
Reads a short value from the buffer starting at the given index relative to the current position() of the buffer, without mutating the buffer in any way (so it's thread safe).
[ "Reads", "a", "short", "value", "from", "the", "buffer", "starting", "at", "the", "given", "index", "relative", "to", "the", "current", "position", "()", "of", "the", "buffer", "without", "mutating", "the", "buffer", "in", "any", "way", "(", "so", "it", "s", "thread", "safe", ")", "." ]
train
https://github.com/kaazing/gateway/blob/06017b19273109b3b992e528e702586446168d57/util/src/main/java/org/kaazing/gateway/util/Utils.java#L450-L452
JadiraOrg/jadira
cloning/src/main/java/org/jadira/reflection/access/unsafe/UnsafeOperations.java
UnsafeOperations.deepCopyObjectField
public final void deepCopyObjectField(Object obj, Object copy, Field field) { """ Copies the object of the specified type from the given field in the source object to the same field in the copy, visiting the object during the copy so that its fields are also copied @param obj The object to copy from @param copy The target object @param field Field to be copied """ deepCopyObjectAtOffset(obj, copy, field.getType(), getObjectFieldOffset(field), new IdentityHashMap<Object, Object>(100)); }
java
public final void deepCopyObjectField(Object obj, Object copy, Field field) { deepCopyObjectAtOffset(obj, copy, field.getType(), getObjectFieldOffset(field), new IdentityHashMap<Object, Object>(100)); }
[ "public", "final", "void", "deepCopyObjectField", "(", "Object", "obj", ",", "Object", "copy", ",", "Field", "field", ")", "{", "deepCopyObjectAtOffset", "(", "obj", ",", "copy", ",", "field", ".", "getType", "(", ")", ",", "getObjectFieldOffset", "(", "field", ")", ",", "new", "IdentityHashMap", "<", "Object", ",", "Object", ">", "(", "100", ")", ")", ";", "}" ]
Copies the object of the specified type from the given field in the source object to the same field in the copy, visiting the object during the copy so that its fields are also copied @param obj The object to copy from @param copy The target object @param field Field to be copied
[ "Copies", "the", "object", "of", "the", "specified", "type", "from", "the", "given", "field", "in", "the", "source", "object", "to", "the", "same", "field", "in", "the", "copy", "visiting", "the", "object", "during", "the", "copy", "so", "that", "its", "fields", "are", "also", "copied" ]
train
https://github.com/JadiraOrg/jadira/blob/d55d0238395f0cb900531f1f08b4b2d87fa9a4f6/cloning/src/main/java/org/jadira/reflection/access/unsafe/UnsafeOperations.java#L441-L444
apache/groovy
subprojects/groovy-swing/src/main/java/org/codehaus/groovy/runtime/SwingGroovyMethods.java
SwingGroovyMethods.leftShift
public static JMenu leftShift(JMenu self, Action action) { """ Overloads the left shift operator to provide an easy way to add components to a menu.<p> @param self a JMenu @param action an action to be added to the menu. @return same menu, after the value was added to it. @since 1.6.4 """ self.add(action); return self; }
java
public static JMenu leftShift(JMenu self, Action action) { self.add(action); return self; }
[ "public", "static", "JMenu", "leftShift", "(", "JMenu", "self", ",", "Action", "action", ")", "{", "self", ".", "add", "(", "action", ")", ";", "return", "self", ";", "}" ]
Overloads the left shift operator to provide an easy way to add components to a menu.<p> @param self a JMenu @param action an action to be added to the menu. @return same menu, after the value was added to it. @since 1.6.4
[ "Overloads", "the", "left", "shift", "operator", "to", "provide", "an", "easy", "way", "to", "add", "components", "to", "a", "menu", ".", "<p", ">" ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-swing/src/main/java/org/codehaus/groovy/runtime/SwingGroovyMethods.java#L767-L770
javagl/ND
nd-distance/src/main/java/de/javagl/nd/distance/tuples/i/IntTupleDistanceFunctions.java
IntTupleDistanceFunctions.computeEuclidean
static double computeEuclidean(IntTuple t0, IntTuple t1) { """ Computes the Euclidean distance between the given arrays @param t0 The first array @param t1 The second array @return The distance @throws IllegalArgumentException If the given array do not have the same length """ return Math.sqrt(computeEuclideanSquared(t0, t1)); }
java
static double computeEuclidean(IntTuple t0, IntTuple t1) { return Math.sqrt(computeEuclideanSquared(t0, t1)); }
[ "static", "double", "computeEuclidean", "(", "IntTuple", "t0", ",", "IntTuple", "t1", ")", "{", "return", "Math", ".", "sqrt", "(", "computeEuclideanSquared", "(", "t0", ",", "t1", ")", ")", ";", "}" ]
Computes the Euclidean distance between the given arrays @param t0 The first array @param t1 The second array @return The distance @throws IllegalArgumentException If the given array do not have the same length
[ "Computes", "the", "Euclidean", "distance", "between", "the", "given", "arrays" ]
train
https://github.com/javagl/ND/blob/bcb655aaf5fc88af6194f73a27cca079186ff559/nd-distance/src/main/java/de/javagl/nd/distance/tuples/i/IntTupleDistanceFunctions.java#L183-L186
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/models/embeddings/loader/WordVectorSerializer.java
WordVectorSerializer.readSequenceVectors
public static <T extends SequenceElement> SequenceVectors<T> readSequenceVectors( @NonNull SequenceElementFactory<T> factory, @NonNull InputStream stream) throws IOException { """ This method loads previously saved SequenceVectors model from InputStream @param factory @param stream @param <T> @return """ BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8")); // at first we load vectors configuration String line = reader.readLine(); VectorsConfiguration configuration = VectorsConfiguration.fromJson(new String(Base64.decodeBase64(line), "UTF-8")); AbstractCache<T> vocabCache = new AbstractCache.Builder<T>().build(); List<INDArray> rows = new ArrayList<>(); while ((line = reader.readLine()) != null) { if (line.isEmpty()) // skip empty line continue; ElementPair pair = ElementPair.fromEncodedJson(line); T element = factory.deserialize(pair.getObject()); rows.add(Nd4j.create(pair.getVector())); vocabCache.addToken(element); vocabCache.addWordToIndex(element.getIndex(), element.getLabel()); } reader.close(); InMemoryLookupTable<T> lookupTable = (InMemoryLookupTable<T>) new InMemoryLookupTable.Builder<T>() .vectorLength(rows.get(0).columns()).cache(vocabCache).build(); // fix: add vocab cache /* * INDArray syn0 = Nd4j.create(rows.size(), rows.get(0).columns()); for (int x = 0; x < rows.size(); x++) { * syn0.putRow(x, rows.get(x)); } */ INDArray syn0 = Nd4j.vstack(rows); lookupTable.setSyn0(syn0); SequenceVectors<T> vectors = new SequenceVectors.Builder<T>(configuration).vocabCache(vocabCache) .lookupTable(lookupTable).resetModel(false).build(); return vectors; }
java
public static <T extends SequenceElement> SequenceVectors<T> readSequenceVectors( @NonNull SequenceElementFactory<T> factory, @NonNull InputStream stream) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8")); // at first we load vectors configuration String line = reader.readLine(); VectorsConfiguration configuration = VectorsConfiguration.fromJson(new String(Base64.decodeBase64(line), "UTF-8")); AbstractCache<T> vocabCache = new AbstractCache.Builder<T>().build(); List<INDArray> rows = new ArrayList<>(); while ((line = reader.readLine()) != null) { if (line.isEmpty()) // skip empty line continue; ElementPair pair = ElementPair.fromEncodedJson(line); T element = factory.deserialize(pair.getObject()); rows.add(Nd4j.create(pair.getVector())); vocabCache.addToken(element); vocabCache.addWordToIndex(element.getIndex(), element.getLabel()); } reader.close(); InMemoryLookupTable<T> lookupTable = (InMemoryLookupTable<T>) new InMemoryLookupTable.Builder<T>() .vectorLength(rows.get(0).columns()).cache(vocabCache).build(); // fix: add vocab cache /* * INDArray syn0 = Nd4j.create(rows.size(), rows.get(0).columns()); for (int x = 0; x < rows.size(); x++) { * syn0.putRow(x, rows.get(x)); } */ INDArray syn0 = Nd4j.vstack(rows); lookupTable.setSyn0(syn0); SequenceVectors<T> vectors = new SequenceVectors.Builder<T>(configuration).vocabCache(vocabCache) .lookupTable(lookupTable).resetModel(false).build(); return vectors; }
[ "public", "static", "<", "T", "extends", "SequenceElement", ">", "SequenceVectors", "<", "T", ">", "readSequenceVectors", "(", "@", "NonNull", "SequenceElementFactory", "<", "T", ">", "factory", ",", "@", "NonNull", "InputStream", "stream", ")", "throws", "IOException", "{", "BufferedReader", "reader", "=", "new", "BufferedReader", "(", "new", "InputStreamReader", "(", "stream", ",", "\"UTF-8\"", ")", ")", ";", "// at first we load vectors configuration", "String", "line", "=", "reader", ".", "readLine", "(", ")", ";", "VectorsConfiguration", "configuration", "=", "VectorsConfiguration", ".", "fromJson", "(", "new", "String", "(", "Base64", ".", "decodeBase64", "(", "line", ")", ",", "\"UTF-8\"", ")", ")", ";", "AbstractCache", "<", "T", ">", "vocabCache", "=", "new", "AbstractCache", ".", "Builder", "<", "T", ">", "(", ")", ".", "build", "(", ")", ";", "List", "<", "INDArray", ">", "rows", "=", "new", "ArrayList", "<>", "(", ")", ";", "while", "(", "(", "line", "=", "reader", ".", "readLine", "(", ")", ")", "!=", "null", ")", "{", "if", "(", "line", ".", "isEmpty", "(", ")", ")", "// skip empty line", "continue", ";", "ElementPair", "pair", "=", "ElementPair", ".", "fromEncodedJson", "(", "line", ")", ";", "T", "element", "=", "factory", ".", "deserialize", "(", "pair", ".", "getObject", "(", ")", ")", ";", "rows", ".", "add", "(", "Nd4j", ".", "create", "(", "pair", ".", "getVector", "(", ")", ")", ")", ";", "vocabCache", ".", "addToken", "(", "element", ")", ";", "vocabCache", ".", "addWordToIndex", "(", "element", ".", "getIndex", "(", ")", ",", "element", ".", "getLabel", "(", ")", ")", ";", "}", "reader", ".", "close", "(", ")", ";", "InMemoryLookupTable", "<", "T", ">", "lookupTable", "=", "(", "InMemoryLookupTable", "<", "T", ">", ")", "new", "InMemoryLookupTable", ".", "Builder", "<", "T", ">", "(", ")", ".", "vectorLength", "(", "rows", ".", "get", "(", "0", ")", ".", "columns", "(", ")", ")", ".", "cache", "(", "vocabCache", ")", ".", "build", "(", ")", ";", "// fix: add vocab cache", "/*\n * INDArray syn0 = Nd4j.create(rows.size(), rows.get(0).columns()); for (int x = 0; x < rows.size(); x++) {\n * syn0.putRow(x, rows.get(x)); }\n */", "INDArray", "syn0", "=", "Nd4j", ".", "vstack", "(", "rows", ")", ";", "lookupTable", ".", "setSyn0", "(", "syn0", ")", ";", "SequenceVectors", "<", "T", ">", "vectors", "=", "new", "SequenceVectors", ".", "Builder", "<", "T", ">", "(", "configuration", ")", ".", "vocabCache", "(", "vocabCache", ")", ".", "lookupTable", "(", "lookupTable", ")", ".", "resetModel", "(", "false", ")", ".", "build", "(", ")", ";", "return", "vectors", ";", "}" ]
This method loads previously saved SequenceVectors model from InputStream @param factory @param stream @param <T> @return
[ "This", "method", "loads", "previously", "saved", "SequenceVectors", "model", "from", "InputStream" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/models/embeddings/loader/WordVectorSerializer.java#L2135-L2176
Coveros/selenified
src/main/java/com/coveros/selenified/Selenified.java
Selenified.setAppURL
protected static void setAppURL(Selenified clazz, ITestContext context, String siteURL) { """ Sets the URL of the application under test. If the site was provided as a system property, this method ignores the passed in value, and uses the system property. @param clazz - the test suite class, used for making threadsafe storage of application, allowing suites to have independent applications under test, run at the same time @param context - the TestNG context associated with the test suite, used for storing app url information @param siteURL - the URL of the application under test """ context.setAttribute(clazz.getClass().getName() + APP_URL, siteURL); }
java
protected static void setAppURL(Selenified clazz, ITestContext context, String siteURL) { context.setAttribute(clazz.getClass().getName() + APP_URL, siteURL); }
[ "protected", "static", "void", "setAppURL", "(", "Selenified", "clazz", ",", "ITestContext", "context", ",", "String", "siteURL", ")", "{", "context", ".", "setAttribute", "(", "clazz", ".", "getClass", "(", ")", ".", "getName", "(", ")", "+", "APP_URL", ",", "siteURL", ")", ";", "}" ]
Sets the URL of the application under test. If the site was provided as a system property, this method ignores the passed in value, and uses the system property. @param clazz - the test suite class, used for making threadsafe storage of application, allowing suites to have independent applications under test, run at the same time @param context - the TestNG context associated with the test suite, used for storing app url information @param siteURL - the URL of the application under test
[ "Sets", "the", "URL", "of", "the", "application", "under", "test", ".", "If", "the", "site", "was", "provided", "as", "a", "system", "property", "this", "method", "ignores", "the", "passed", "in", "value", "and", "uses", "the", "system", "property", "." ]
train
https://github.com/Coveros/selenified/blob/396cc1f010dd69eed33cc5061c41253de246a4cd/src/main/java/com/coveros/selenified/Selenified.java#L106-L108
dropbox/dropbox-sdk-java
src/main/java/com/dropbox/core/v1/DbxClientV1.java
DbxClientV1.disableAccessToken
public void disableAccessToken() throws DbxException { """ Disable the access token that you constructed this {@code DbxClientV1} with. After calling this, API calls made with this {@code DbxClientV1} will fail. """ String host = this.host.getApi(); String apiPath = "1/disable_access_token"; doPost(host, apiPath, null, null, new DbxRequestUtil.ResponseHandler</*@Nullable*/Void>() { @Override public /*@Nullable*/Void handle(HttpRequestor.Response response) throws DbxException { if (response.getStatusCode() != 200) { String requestId = DbxRequestUtil.getRequestId(response); throw new BadResponseException(requestId, "unexpected response code: " + response.getStatusCode()); } return null; } }); }
java
public void disableAccessToken() throws DbxException { String host = this.host.getApi(); String apiPath = "1/disable_access_token"; doPost(host, apiPath, null, null, new DbxRequestUtil.ResponseHandler</*@Nullable*/Void>() { @Override public /*@Nullable*/Void handle(HttpRequestor.Response response) throws DbxException { if (response.getStatusCode() != 200) { String requestId = DbxRequestUtil.getRequestId(response); throw new BadResponseException(requestId, "unexpected response code: " + response.getStatusCode()); } return null; } }); }
[ "public", "void", "disableAccessToken", "(", ")", "throws", "DbxException", "{", "String", "host", "=", "this", ".", "host", ".", "getApi", "(", ")", ";", "String", "apiPath", "=", "\"1/disable_access_token\"", ";", "doPost", "(", "host", ",", "apiPath", ",", "null", ",", "null", ",", "new", "DbxRequestUtil", ".", "ResponseHandler", "<", "/*@Nullable*/", "Void", ">", "(", ")", "{", "@", "Override", "public", "/*@Nullable*/", "Void", "handle", "(", "HttpRequestor", ".", "Response", "response", ")", "throws", "DbxException", "{", "if", "(", "response", ".", "getStatusCode", "(", ")", "!=", "200", ")", "{", "String", "requestId", "=", "DbxRequestUtil", ".", "getRequestId", "(", "response", ")", ";", "throw", "new", "BadResponseException", "(", "requestId", ",", "\"unexpected response code: \"", "+", "response", ".", "getStatusCode", "(", ")", ")", ";", "}", "return", "null", ";", "}", "}", ")", ";", "}" ]
Disable the access token that you constructed this {@code DbxClientV1} with. After calling this, API calls made with this {@code DbxClientV1} will fail.
[ "Disable", "the", "access", "token", "that", "you", "constructed", "this", "{" ]
train
https://github.com/dropbox/dropbox-sdk-java/blob/d86157005fad6233c18b4b0f10f00b8d9d56ae92/src/main/java/com/dropbox/core/v1/DbxClientV1.java#L374-L391
liferay/com-liferay-commerce
commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CPDefinitionInventoryPersistenceImpl.java
CPDefinitionInventoryPersistenceImpl.removeByUUID_G
@Override public CPDefinitionInventory removeByUUID_G(String uuid, long groupId) throws NoSuchCPDefinitionInventoryException { """ Removes the cp definition inventory where uuid = &#63; and groupId = &#63; from the database. @param uuid the uuid @param groupId the group ID @return the cp definition inventory that was removed """ CPDefinitionInventory cpDefinitionInventory = findByUUID_G(uuid, groupId); return remove(cpDefinitionInventory); }
java
@Override public CPDefinitionInventory removeByUUID_G(String uuid, long groupId) throws NoSuchCPDefinitionInventoryException { CPDefinitionInventory cpDefinitionInventory = findByUUID_G(uuid, groupId); return remove(cpDefinitionInventory); }
[ "@", "Override", "public", "CPDefinitionInventory", "removeByUUID_G", "(", "String", "uuid", ",", "long", "groupId", ")", "throws", "NoSuchCPDefinitionInventoryException", "{", "CPDefinitionInventory", "cpDefinitionInventory", "=", "findByUUID_G", "(", "uuid", ",", "groupId", ")", ";", "return", "remove", "(", "cpDefinitionInventory", ")", ";", "}" ]
Removes the cp definition inventory where uuid = &#63; and groupId = &#63; from the database. @param uuid the uuid @param groupId the group ID @return the cp definition inventory that was removed
[ "Removes", "the", "cp", "definition", "inventory", "where", "uuid", "=", "&#63", ";", "and", "groupId", "=", "&#63", ";", "from", "the", "database", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CPDefinitionInventoryPersistenceImpl.java#L816-L822
alkacon/opencms-core
src/org/opencms/ade/sitemap/CmsModelPageHelper.java
CmsModelPageHelper.createModelPageEntry
CmsModelPageEntry createModelPageEntry(CmsResource resource, boolean disabled, boolean isDefault, Locale locale) { """ Creates a model page entry bean from a model page resource.<p> @param resource the model page resource @param disabled if the model page is disabled @param isDefault if this is the default model page @param locale the current user locale @return the model page entry bean """ try { CmsModelPageEntry result = new CmsModelPageEntry(); result.setDefault(isDefault); result.setDisabled(disabled); List<CmsProperty> properties = m_cms.readPropertyObjects(resource, false); Map<String, CmsClientProperty> clientProperties = Maps.newHashMap(); for (CmsProperty prop : properties) { CmsClientProperty clientProp = CmsVfsSitemapService.createClientProperty(prop, false); clientProperties.put(prop.getName(), clientProp); } result.setOwnProperties(clientProperties); result.setRootPath(resource.getRootPath()); if (resource.getRootPath().startsWith(m_siteRoot)) { CmsObject siteCms = OpenCms.initCmsObject(m_cms); siteCms.getRequestContext().setSiteRoot(m_siteRoot); result.setSitePath(siteCms.getSitePath(resource)); } result.setResourceType(OpenCms.getResourceManager().getResourceType(resource).getTypeName()); result.setStructureId(resource.getStructureId()); CmsListInfoBean infoBean = CmsVfsService.getPageInfo(m_cms, resource); CmsProperty descProperty = m_cms.readPropertyObject( resource, CmsPropertyDefinition.PROPERTY_DESCRIPTION, false, locale); if (!CmsStringUtil.isEmptyOrWhitespaceOnly(descProperty.getValue())) { infoBean.setSubTitle(descProperty.getValue()); } infoBean.addAdditionalInfo( Messages.get().getBundle(OpenCms.getWorkplaceManager().getWorkplaceLocale(m_cms)).key( Messages.GUI_VFS_PATH_0), result.getSitePath() != null ? result.getSitePath() : result.getRootPath()); result.setListInfoBean(infoBean); return result; } catch (Exception e) { LOG.error(e.getLocalizedMessage(), e); return null; } }
java
CmsModelPageEntry createModelPageEntry(CmsResource resource, boolean disabled, boolean isDefault, Locale locale) { try { CmsModelPageEntry result = new CmsModelPageEntry(); result.setDefault(isDefault); result.setDisabled(disabled); List<CmsProperty> properties = m_cms.readPropertyObjects(resource, false); Map<String, CmsClientProperty> clientProperties = Maps.newHashMap(); for (CmsProperty prop : properties) { CmsClientProperty clientProp = CmsVfsSitemapService.createClientProperty(prop, false); clientProperties.put(prop.getName(), clientProp); } result.setOwnProperties(clientProperties); result.setRootPath(resource.getRootPath()); if (resource.getRootPath().startsWith(m_siteRoot)) { CmsObject siteCms = OpenCms.initCmsObject(m_cms); siteCms.getRequestContext().setSiteRoot(m_siteRoot); result.setSitePath(siteCms.getSitePath(resource)); } result.setResourceType(OpenCms.getResourceManager().getResourceType(resource).getTypeName()); result.setStructureId(resource.getStructureId()); CmsListInfoBean infoBean = CmsVfsService.getPageInfo(m_cms, resource); CmsProperty descProperty = m_cms.readPropertyObject( resource, CmsPropertyDefinition.PROPERTY_DESCRIPTION, false, locale); if (!CmsStringUtil.isEmptyOrWhitespaceOnly(descProperty.getValue())) { infoBean.setSubTitle(descProperty.getValue()); } infoBean.addAdditionalInfo( Messages.get().getBundle(OpenCms.getWorkplaceManager().getWorkplaceLocale(m_cms)).key( Messages.GUI_VFS_PATH_0), result.getSitePath() != null ? result.getSitePath() : result.getRootPath()); result.setListInfoBean(infoBean); return result; } catch (Exception e) { LOG.error(e.getLocalizedMessage(), e); return null; } }
[ "CmsModelPageEntry", "createModelPageEntry", "(", "CmsResource", "resource", ",", "boolean", "disabled", ",", "boolean", "isDefault", ",", "Locale", "locale", ")", "{", "try", "{", "CmsModelPageEntry", "result", "=", "new", "CmsModelPageEntry", "(", ")", ";", "result", ".", "setDefault", "(", "isDefault", ")", ";", "result", ".", "setDisabled", "(", "disabled", ")", ";", "List", "<", "CmsProperty", ">", "properties", "=", "m_cms", ".", "readPropertyObjects", "(", "resource", ",", "false", ")", ";", "Map", "<", "String", ",", "CmsClientProperty", ">", "clientProperties", "=", "Maps", ".", "newHashMap", "(", ")", ";", "for", "(", "CmsProperty", "prop", ":", "properties", ")", "{", "CmsClientProperty", "clientProp", "=", "CmsVfsSitemapService", ".", "createClientProperty", "(", "prop", ",", "false", ")", ";", "clientProperties", ".", "put", "(", "prop", ".", "getName", "(", ")", ",", "clientProp", ")", ";", "}", "result", ".", "setOwnProperties", "(", "clientProperties", ")", ";", "result", ".", "setRootPath", "(", "resource", ".", "getRootPath", "(", ")", ")", ";", "if", "(", "resource", ".", "getRootPath", "(", ")", ".", "startsWith", "(", "m_siteRoot", ")", ")", "{", "CmsObject", "siteCms", "=", "OpenCms", ".", "initCmsObject", "(", "m_cms", ")", ";", "siteCms", ".", "getRequestContext", "(", ")", ".", "setSiteRoot", "(", "m_siteRoot", ")", ";", "result", ".", "setSitePath", "(", "siteCms", ".", "getSitePath", "(", "resource", ")", ")", ";", "}", "result", ".", "setResourceType", "(", "OpenCms", ".", "getResourceManager", "(", ")", ".", "getResourceType", "(", "resource", ")", ".", "getTypeName", "(", ")", ")", ";", "result", ".", "setStructureId", "(", "resource", ".", "getStructureId", "(", ")", ")", ";", "CmsListInfoBean", "infoBean", "=", "CmsVfsService", ".", "getPageInfo", "(", "m_cms", ",", "resource", ")", ";", "CmsProperty", "descProperty", "=", "m_cms", ".", "readPropertyObject", "(", "resource", ",", "CmsPropertyDefinition", ".", "PROPERTY_DESCRIPTION", ",", "false", ",", "locale", ")", ";", "if", "(", "!", "CmsStringUtil", ".", "isEmptyOrWhitespaceOnly", "(", "descProperty", ".", "getValue", "(", ")", ")", ")", "{", "infoBean", ".", "setSubTitle", "(", "descProperty", ".", "getValue", "(", ")", ")", ";", "}", "infoBean", ".", "addAdditionalInfo", "(", "Messages", ".", "get", "(", ")", ".", "getBundle", "(", "OpenCms", ".", "getWorkplaceManager", "(", ")", ".", "getWorkplaceLocale", "(", "m_cms", ")", ")", ".", "key", "(", "Messages", ".", "GUI_VFS_PATH_0", ")", ",", "result", ".", "getSitePath", "(", ")", "!=", "null", "?", "result", ".", "getSitePath", "(", ")", ":", "result", ".", "getRootPath", "(", ")", ")", ";", "result", ".", "setListInfoBean", "(", "infoBean", ")", ";", "return", "result", ";", "}", "catch", "(", "Exception", "e", ")", "{", "LOG", ".", "error", "(", "e", ".", "getLocalizedMessage", "(", ")", ",", "e", ")", ";", "return", "null", ";", "}", "}" ]
Creates a model page entry bean from a model page resource.<p> @param resource the model page resource @param disabled if the model page is disabled @param isDefault if this is the default model page @param locale the current user locale @return the model page entry bean
[ "Creates", "a", "model", "page", "entry", "bean", "from", "a", "model", "page", "resource", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/sitemap/CmsModelPageHelper.java#L419-L459
grails/gorm-hibernate5
grails-datastore-gorm-hibernate5/src/main/groovy/org/grails/orm/hibernate/query/AbstractHibernateCriteriaBuilder.java
AbstractHibernateCriteriaBuilder.fetchMode
public void fetchMode(String associationPath, FetchMode fetchMode) { """ Sets the fetch mode of an associated path @param associationPath The name of the associated path @param fetchMode The fetch mode to set """ if (criteria != null) { criteria.setFetchMode(associationPath, fetchMode); } }
java
public void fetchMode(String associationPath, FetchMode fetchMode) { if (criteria != null) { criteria.setFetchMode(associationPath, fetchMode); } }
[ "public", "void", "fetchMode", "(", "String", "associationPath", ",", "FetchMode", "fetchMode", ")", "{", "if", "(", "criteria", "!=", "null", ")", "{", "criteria", ".", "setFetchMode", "(", "associationPath", ",", "fetchMode", ")", ";", "}", "}" ]
Sets the fetch mode of an associated path @param associationPath The name of the associated path @param fetchMode The fetch mode to set
[ "Sets", "the", "fetch", "mode", "of", "an", "associated", "path" ]
train
https://github.com/grails/gorm-hibernate5/blob/0ebb80cd769ef2bea955723d4543828a3e9542ef/grails-datastore-gorm-hibernate5/src/main/groovy/org/grails/orm/hibernate/query/AbstractHibernateCriteriaBuilder.java#L544-L548
l0s/fernet-java8
fernet-aws-secrets-manager-rotator/src/main/java/com/macasaet/fernet/aws/secretsmanager/rotation/SecretsManager.java
SecretsManager.getSecretVersion
public ByteBuffer getSecretVersion(final String secretId, final String clientRequestToken) { """ Retrieve a specific version of the secret. This requires the permission <code>secretsmanager:GetSecretValue</code> @param secretId the ARN of the secret @param clientRequestToken the version identifier of the secret @return the Fernet key or keys in binary form """ final GetSecretValueRequest getSecretValueRequest = new GetSecretValueRequest(); getSecretValueRequest.setSecretId(secretId); getSecretValueRequest.setVersionId(clientRequestToken); final GetSecretValueResult result = getDelegate().getSecretValue(getSecretValueRequest); return result.getSecretBinary(); }
java
public ByteBuffer getSecretVersion(final String secretId, final String clientRequestToken) { final GetSecretValueRequest getSecretValueRequest = new GetSecretValueRequest(); getSecretValueRequest.setSecretId(secretId); getSecretValueRequest.setVersionId(clientRequestToken); final GetSecretValueResult result = getDelegate().getSecretValue(getSecretValueRequest); return result.getSecretBinary(); }
[ "public", "ByteBuffer", "getSecretVersion", "(", "final", "String", "secretId", ",", "final", "String", "clientRequestToken", ")", "{", "final", "GetSecretValueRequest", "getSecretValueRequest", "=", "new", "GetSecretValueRequest", "(", ")", ";", "getSecretValueRequest", ".", "setSecretId", "(", "secretId", ")", ";", "getSecretValueRequest", ".", "setVersionId", "(", "clientRequestToken", ")", ";", "final", "GetSecretValueResult", "result", "=", "getDelegate", "(", ")", ".", "getSecretValue", "(", "getSecretValueRequest", ")", ";", "return", "result", ".", "getSecretBinary", "(", ")", ";", "}" ]
Retrieve a specific version of the secret. This requires the permission <code>secretsmanager:GetSecretValue</code> @param secretId the ARN of the secret @param clientRequestToken the version identifier of the secret @return the Fernet key or keys in binary form
[ "Retrieve", "a", "specific", "version", "of", "the", "secret", ".", "This", "requires", "the", "permission", "<code", ">", "secretsmanager", ":", "GetSecretValue<", "/", "code", ">" ]
train
https://github.com/l0s/fernet-java8/blob/427244bc1af605ffca0ac2469d66b297ea9f77b3/fernet-aws-secrets-manager-rotator/src/main/java/com/macasaet/fernet/aws/secretsmanager/rotation/SecretsManager.java#L92-L98