repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
18
201
func_name
stringlengths
4
126
whole_func_string
stringlengths
75
3.57k
language
stringclasses
1 value
func_code_string
stringlengths
75
3.57k
func_code_tokens
listlengths
21
599
func_documentation_string
stringlengths
61
1.95k
func_documentation_tokens
listlengths
1
478
split_name
stringclasses
1 value
func_code_url
stringlengths
111
308
NordicSemiconductor/Android-DFU-Library
dfu/src/main/java/no/nordicsemi/android/dfu/SecureDfuImpl.java
SecureDfuImpl.readChecksum
private ObjectChecksum readChecksum() throws DeviceDisconnectedException, DfuException, UploadAbortedException, RemoteDfuException, UnknownResponseException { if (!mConnected) throw new DeviceDisconnectedException("Unable to read Checksum: device disconnected"); writeOpCode(mControlPointCharacteristic, OP_CODE_CALCULATE_CHECKSUM); final byte[] response = readNotificationResponse(); final int status = getStatusCode(response, OP_CODE_CALCULATE_CHECKSUM_KEY); if (status == SecureDfuError.EXTENDED_ERROR) throw new RemoteDfuExtendedErrorException("Receiving Checksum failed", response[3]); if (status != DFU_STATUS_SUCCESS) throw new RemoteDfuException("Receiving Checksum failed", status); final ObjectChecksum checksum = new ObjectChecksum(); checksum.offset = mControlPointCharacteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT32, 3); checksum.CRC32 = mControlPointCharacteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT32, 3 + 4); return checksum; }
java
private ObjectChecksum readChecksum() throws DeviceDisconnectedException, DfuException, UploadAbortedException, RemoteDfuException, UnknownResponseException { if (!mConnected) throw new DeviceDisconnectedException("Unable to read Checksum: device disconnected"); writeOpCode(mControlPointCharacteristic, OP_CODE_CALCULATE_CHECKSUM); final byte[] response = readNotificationResponse(); final int status = getStatusCode(response, OP_CODE_CALCULATE_CHECKSUM_KEY); if (status == SecureDfuError.EXTENDED_ERROR) throw new RemoteDfuExtendedErrorException("Receiving Checksum failed", response[3]); if (status != DFU_STATUS_SUCCESS) throw new RemoteDfuException("Receiving Checksum failed", status); final ObjectChecksum checksum = new ObjectChecksum(); checksum.offset = mControlPointCharacteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT32, 3); checksum.CRC32 = mControlPointCharacteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT32, 3 + 4); return checksum; }
[ "private", "ObjectChecksum", "readChecksum", "(", ")", "throws", "DeviceDisconnectedException", ",", "DfuException", ",", "UploadAbortedException", ",", "RemoteDfuException", ",", "UnknownResponseException", "{", "if", "(", "!", "mConnected", ")", "throw", "new", "Devic...
Sends the Calculate Checksum request. As a response a notification will be sent with current offset and CRC32 of the current object. @return requested object info. @throws DeviceDisconnectedException @throws DfuException @throws UploadAbortedException @throws RemoteDfuException thrown when the returned status code is not equal to {@link #DFU_STATUS_SUCCESS}.
[ "Sends", "the", "Calculate", "Checksum", "request", ".", "As", "a", "response", "a", "notification", "will", "be", "sent", "with", "current", "offset", "and", "CRC32", "of", "the", "current", "object", "." ]
train
https://github.com/NordicSemiconductor/Android-DFU-Library/blob/ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f/dfu/src/main/java/no/nordicsemi/android/dfu/SecureDfuImpl.java#L870-L888
Azure/azure-sdk-for-java
batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/FilesImpl.java
FilesImpl.listFromComputeNodeNextAsync
public Observable<Page<NodeFile>> listFromComputeNodeNextAsync(final String nextPageLink, final FileListFromComputeNodeNextOptions fileListFromComputeNodeNextOptions) { return listFromComputeNodeNextWithServiceResponseAsync(nextPageLink, fileListFromComputeNodeNextOptions) .map(new Func1<ServiceResponseWithHeaders<Page<NodeFile>, FileListFromComputeNodeHeaders>, Page<NodeFile>>() { @Override public Page<NodeFile> call(ServiceResponseWithHeaders<Page<NodeFile>, FileListFromComputeNodeHeaders> response) { return response.body(); } }); }
java
public Observable<Page<NodeFile>> listFromComputeNodeNextAsync(final String nextPageLink, final FileListFromComputeNodeNextOptions fileListFromComputeNodeNextOptions) { return listFromComputeNodeNextWithServiceResponseAsync(nextPageLink, fileListFromComputeNodeNextOptions) .map(new Func1<ServiceResponseWithHeaders<Page<NodeFile>, FileListFromComputeNodeHeaders>, Page<NodeFile>>() { @Override public Page<NodeFile> call(ServiceResponseWithHeaders<Page<NodeFile>, FileListFromComputeNodeHeaders> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Page", "<", "NodeFile", ">", ">", "listFromComputeNodeNextAsync", "(", "final", "String", "nextPageLink", ",", "final", "FileListFromComputeNodeNextOptions", "fileListFromComputeNodeNextOptions", ")", "{", "return", "listFromComputeNodeNextWithSe...
Lists all of the files in task directories on the specified compute node. @param nextPageLink The NextLink from the previous successful call to List operation. @param fileListFromComputeNodeNextOptions Additional parameters for the operation @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;NodeFile&gt; object
[ "Lists", "all", "of", "the", "files", "in", "task", "directories", "on", "the", "specified", "compute", "node", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/FilesImpl.java#L2628-L2636
threerings/narya
core/src/main/java/com/threerings/presents/server/PresentsDObjectMgr.java
PresentsDObjectMgr.setDefaultAccessController
public void setDefaultAccessController (AccessController controller) { AccessController oldDefault = _defaultController; _defaultController = controller; // switch all objects from the old default (null, usually) to the new default. for (DObject obj : _objects.values()) { if (oldDefault == obj.getAccessController()) { obj.setAccessController(controller); } } }
java
public void setDefaultAccessController (AccessController controller) { AccessController oldDefault = _defaultController; _defaultController = controller; // switch all objects from the old default (null, usually) to the new default. for (DObject obj : _objects.values()) { if (oldDefault == obj.getAccessController()) { obj.setAccessController(controller); } } }
[ "public", "void", "setDefaultAccessController", "(", "AccessController", "controller", ")", "{", "AccessController", "oldDefault", "=", "_defaultController", ";", "_defaultController", "=", "controller", ";", "// switch all objects from the old default (null, usually) to the new de...
Sets up an access controller that will be provided to any distributed objects created on the server. The controllers can subsequently be overridden if desired, but a default controller is useful for implementing basic access control policies.
[ "Sets", "up", "an", "access", "controller", "that", "will", "be", "provided", "to", "any", "distributed", "objects", "created", "on", "the", "server", ".", "The", "controllers", "can", "subsequently", "be", "overridden", "if", "desired", "but", "a", "default",...
train
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/server/PresentsDObjectMgr.java#L152-L163
aws/aws-sdk-java
aws-java-sdk-robomaker/src/main/java/com/amazonaws/services/robomaker/model/DescribeSimulationApplicationResult.java
DescribeSimulationApplicationResult.withTags
public DescribeSimulationApplicationResult withTags(java.util.Map<String, String> tags) { setTags(tags); return this; }
java
public DescribeSimulationApplicationResult withTags(java.util.Map<String, String> tags) { setTags(tags); return this; }
[ "public", "DescribeSimulationApplicationResult", "withTags", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "tags", ")", "{", "setTags", "(", "tags", ")", ";", "return", "this", ";", "}" ]
<p> The list of all tags added to the specified simulation application. </p> @param tags The list of all tags added to the specified simulation application. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "The", "list", "of", "all", "tags", "added", "to", "the", "specified", "simulation", "application", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-robomaker/src/main/java/com/amazonaws/services/robomaker/model/DescribeSimulationApplicationResult.java#L513-L516
josueeduardo/snappy
plugin-parent/snappy-loader/src/main/java/io/joshworks/snappy/loader/jar/JarEntryData.java
JarEntryData.decodeMsDosFormatDateTime
private Calendar decodeMsDosFormatDateTime(long date, long time) { int year = (int) ((date >> 9) & 0x7F) + 1980; int month = (int) ((date >> 5) & 0xF) - 1; int day = (int) (date & 0x1F); int hours = (int) ((time >> 11) & 0x1F); int minutes = (int) ((time >> 5) & 0x3F); int seconds = (int) ((time << 1) & 0x3E); return new GregorianCalendar(year, month, day, hours, minutes, seconds); }
java
private Calendar decodeMsDosFormatDateTime(long date, long time) { int year = (int) ((date >> 9) & 0x7F) + 1980; int month = (int) ((date >> 5) & 0xF) - 1; int day = (int) (date & 0x1F); int hours = (int) ((time >> 11) & 0x1F); int minutes = (int) ((time >> 5) & 0x3F); int seconds = (int) ((time << 1) & 0x3E); return new GregorianCalendar(year, month, day, hours, minutes, seconds); }
[ "private", "Calendar", "decodeMsDosFormatDateTime", "(", "long", "date", ",", "long", "time", ")", "{", "int", "year", "=", "(", "int", ")", "(", "(", "date", ">>", "9", ")", "&", "0x7F", ")", "+", "1980", ";", "int", "month", "=", "(", "int", ")",...
Decode MS-DOS Date Time details. See <a href="http://mindprod.com/jgloss/zip.html">mindprod.com/jgloss/zip.html</a> for more details of the format. @param date the date part @param time the time part @return a {@link Calendar} containing the decoded date.
[ "Decode", "MS", "-", "DOS", "Date", "Time", "details", ".", "See", "<a", "href", "=", "http", ":", "//", "mindprod", ".", "com", "/", "jgloss", "/", "zip", ".", "html", ">", "mindprod", ".", "com", "/", "jgloss", "/", "zip", ".", "html<", "/", "a...
train
https://github.com/josueeduardo/snappy/blob/d95a9e811eda3c24a5e53086369208819884fa49/plugin-parent/snappy-loader/src/main/java/io/joshworks/snappy/loader/jar/JarEntryData.java#L176-L184
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/time/DateUtils.java
DateUtils.getFragmentInHours
@GwtIncompatible("incompatible method") public static long getFragmentInHours(final Date date, final int fragment) { return getFragment(date, fragment, TimeUnit.HOURS); }
java
@GwtIncompatible("incompatible method") public static long getFragmentInHours(final Date date, final int fragment) { return getFragment(date, fragment, TimeUnit.HOURS); }
[ "@", "GwtIncompatible", "(", "\"incompatible method\"", ")", "public", "static", "long", "getFragmentInHours", "(", "final", "Date", "date", ",", "final", "int", "fragment", ")", "{", "return", "getFragment", "(", "date", ",", "fragment", ",", "TimeUnit", ".", ...
<p>Returns the number of hours within the fragment. All datefields greater than the fragment will be ignored.</p> <p>Asking the hours of any date will only return the number of hours of the current day (resulting in a number between 0 and 23). This method will retrieve the number of hours for any fragment. For example, if you want to calculate the number of hours past this month, your fragment is Calendar.MONTH. The result will be all hours of the past day(s).</p> <p>Valid fragments are: Calendar.YEAR, Calendar.MONTH, both Calendar.DAY_OF_YEAR and Calendar.DATE, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND and Calendar.MILLISECOND A fragment less than or equal to a HOUR field will return 0.</p> <ul> <li>January 1, 2008 7:15:10.538 with Calendar.DAY_OF_YEAR as fragment will return 7 (equivalent to deprecated date.getHours())</li> <li>January 6, 2008 7:15:10.538 with Calendar.DAY_OF_YEAR as fragment will return 7 (equivalent to deprecated date.getHours())</li> <li>January 1, 2008 7:15:10.538 with Calendar.MONTH as fragment will return 7</li> <li>January 6, 2008 7:15:10.538 with Calendar.MONTH as fragment will return 127 (5*24 + 7)</li> <li>January 16, 2008 7:15:10.538 with Calendar.MILLISECOND as fragment will return 0 (a millisecond cannot be split in hours)</li> </ul> @param date the date to work with, not null @param fragment the {@code Calendar} field part of date to calculate @return number of hours within the fragment of date @throws IllegalArgumentException if the date is <code>null</code> or fragment is not supported @since 2.4
[ "<p", ">", "Returns", "the", "number", "of", "hours", "within", "the", "fragment", ".", "All", "datefields", "greater", "than", "the", "fragment", "will", "be", "ignored", ".", "<", "/", "p", ">" ]
train
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/time/DateUtils.java#L1413-L1416
grpc/grpc-java
netty/src/main/java/io/grpc/netty/ProtocolNegotiators.java
ProtocolNegotiators.httpProxy
public static ProtocolNegotiator httpProxy(final SocketAddress proxyAddress, final @Nullable String proxyUsername, final @Nullable String proxyPassword, final ProtocolNegotiator negotiator) { final AsciiString scheme = negotiator.scheme(); Preconditions.checkNotNull(proxyAddress, "proxyAddress"); Preconditions.checkNotNull(negotiator, "negotiator"); class ProxyNegotiator implements ProtocolNegotiator { @Override public ChannelHandler newHandler(GrpcHttp2ConnectionHandler http2Handler) { HttpProxyHandler proxyHandler; if (proxyUsername == null || proxyPassword == null) { proxyHandler = new HttpProxyHandler(proxyAddress); } else { proxyHandler = new HttpProxyHandler(proxyAddress, proxyUsername, proxyPassword); } return new BufferUntilProxyTunnelledHandler( proxyHandler, negotiator.newHandler(http2Handler)); } @Override public AsciiString scheme() { return scheme; } // This method is not normally called, because we use httpProxy on a per-connection basis in // NettyChannelBuilder. Instead, we expect `negotiator' to be closed by NettyTransportFactory. @Override public void close() { negotiator.close(); } } return new ProxyNegotiator(); }
java
public static ProtocolNegotiator httpProxy(final SocketAddress proxyAddress, final @Nullable String proxyUsername, final @Nullable String proxyPassword, final ProtocolNegotiator negotiator) { final AsciiString scheme = negotiator.scheme(); Preconditions.checkNotNull(proxyAddress, "proxyAddress"); Preconditions.checkNotNull(negotiator, "negotiator"); class ProxyNegotiator implements ProtocolNegotiator { @Override public ChannelHandler newHandler(GrpcHttp2ConnectionHandler http2Handler) { HttpProxyHandler proxyHandler; if (proxyUsername == null || proxyPassword == null) { proxyHandler = new HttpProxyHandler(proxyAddress); } else { proxyHandler = new HttpProxyHandler(proxyAddress, proxyUsername, proxyPassword); } return new BufferUntilProxyTunnelledHandler( proxyHandler, negotiator.newHandler(http2Handler)); } @Override public AsciiString scheme() { return scheme; } // This method is not normally called, because we use httpProxy on a per-connection basis in // NettyChannelBuilder. Instead, we expect `negotiator' to be closed by NettyTransportFactory. @Override public void close() { negotiator.close(); } } return new ProxyNegotiator(); }
[ "public", "static", "ProtocolNegotiator", "httpProxy", "(", "final", "SocketAddress", "proxyAddress", ",", "final", "@", "Nullable", "String", "proxyUsername", ",", "final", "@", "Nullable", "String", "proxyPassword", ",", "final", "ProtocolNegotiator", "negotiator", ...
Returns a {@link ProtocolNegotiator} that does HTTP CONNECT proxy negotiation.
[ "Returns", "a", "{" ]
train
https://github.com/grpc/grpc-java/blob/973885457f9609de232d2553b82c67f6c3ff57bf/netty/src/main/java/io/grpc/netty/ProtocolNegotiators.java#L204-L237
cdk/cdk
base/valencycheck/src/main/java/org/openscience/cdk/tools/AtomTypeAwareSaturationChecker.java
AtomTypeAwareSaturationChecker.decideBondOrder
private void decideBondOrder(IAtomContainer atomContainer, int start) throws CDKException { for (int i = 0; i < atomContainer.getBondCount(); i++) if (atomContainer.getBond(i).getFlag(CDKConstants.SINGLE_OR_DOUBLE)) atomContainer.getBond(i).setOrder(IBond.Order.SINGLE); for (int i = start; i < atomContainer.getBondCount(); i++) { checkBond(atomContainer, i); } /* * If we don't start with first bond, then we have to check the bonds * before the bond we started with. */ if (start > 0) { for (int i = start - 1; i >= 0; i--) { checkBond(atomContainer, i); } } }
java
private void decideBondOrder(IAtomContainer atomContainer, int start) throws CDKException { for (int i = 0; i < atomContainer.getBondCount(); i++) if (atomContainer.getBond(i).getFlag(CDKConstants.SINGLE_OR_DOUBLE)) atomContainer.getBond(i).setOrder(IBond.Order.SINGLE); for (int i = start; i < atomContainer.getBondCount(); i++) { checkBond(atomContainer, i); } /* * If we don't start with first bond, then we have to check the bonds * before the bond we started with. */ if (start > 0) { for (int i = start - 1; i >= 0; i--) { checkBond(atomContainer, i); } } }
[ "private", "void", "decideBondOrder", "(", "IAtomContainer", "atomContainer", ",", "int", "start", ")", "throws", "CDKException", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "atomContainer", ".", "getBondCount", "(", ")", ";", "i", "++", ")", "...
This method decides the bond order on bonds that has the <code>SINGLE_OR_DOUBLE</code>-flag raised. @param atomContainer The molecule to investigate @param start The bond to start with @throws CDKException
[ "This", "method", "decides", "the", "bond", "order", "on", "bonds", "that", "has", "the", "<code", ">", "SINGLE_OR_DOUBLE<", "/", "code", ">", "-", "flag", "raised", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/base/valencycheck/src/main/java/org/openscience/cdk/tools/AtomTypeAwareSaturationChecker.java#L138-L155
google/error-prone-javac
src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/SourceToHTMLConverter.java
SourceToHTMLConverter.convertRoot
public static void convertRoot(ConfigurationImpl configuration, DocletEnvironment docEnv, DocPath outputdir) throws DocFileIOException, SimpleDocletException { new SourceToHTMLConverter(configuration, docEnv, outputdir).generate(); }
java
public static void convertRoot(ConfigurationImpl configuration, DocletEnvironment docEnv, DocPath outputdir) throws DocFileIOException, SimpleDocletException { new SourceToHTMLConverter(configuration, docEnv, outputdir).generate(); }
[ "public", "static", "void", "convertRoot", "(", "ConfigurationImpl", "configuration", ",", "DocletEnvironment", "docEnv", ",", "DocPath", "outputdir", ")", "throws", "DocFileIOException", ",", "SimpleDocletException", "{", "new", "SourceToHTMLConverter", "(", "configurati...
Translate the TypeElements in the given DocletEnvironment to HTML representation. @param configuration the configuration. @param docEnv the DocletEnvironment to convert. @param outputdir the name of the directory to output to. @throws DocFileIOException if there is a problem generating an output file @throws SimpleDocletException if there is a problem reading a source file
[ "Translate", "the", "TypeElements", "in", "the", "given", "DocletEnvironment", "to", "HTML", "representation", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/SourceToHTMLConverter.java#L109-L112
Azure/azure-sdk-for-java
compute/resource-manager/v2017_12_01/src/main/java/com/microsoft/azure/management/compute/v2017_12_01/implementation/VirtualMachineScaleSetVMsInner.java
VirtualMachineScaleSetVMsInner.getInstanceView
public VirtualMachineScaleSetVMInstanceViewInner getInstanceView(String resourceGroupName, String vmScaleSetName, String instanceId) { return getInstanceViewWithServiceResponseAsync(resourceGroupName, vmScaleSetName, instanceId).toBlocking().single().body(); }
java
public VirtualMachineScaleSetVMInstanceViewInner getInstanceView(String resourceGroupName, String vmScaleSetName, String instanceId) { return getInstanceViewWithServiceResponseAsync(resourceGroupName, vmScaleSetName, instanceId).toBlocking().single().body(); }
[ "public", "VirtualMachineScaleSetVMInstanceViewInner", "getInstanceView", "(", "String", "resourceGroupName", ",", "String", "vmScaleSetName", ",", "String", "instanceId", ")", "{", "return", "getInstanceViewWithServiceResponseAsync", "(", "resourceGroupName", ",", "vmScaleSetN...
Gets the status of a virtual machine from a VM scale set. @param resourceGroupName The name of the resource group. @param vmScaleSetName The name of the VM scale set. @param instanceId The instance ID of the virtual machine. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the VirtualMachineScaleSetVMInstanceViewInner object if successful.
[ "Gets", "the", "status", "of", "a", "virtual", "machine", "from", "a", "VM", "scale", "set", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/compute/resource-manager/v2017_12_01/src/main/java/com/microsoft/azure/management/compute/v2017_12_01/implementation/VirtualMachineScaleSetVMsInner.java#L1134-L1136
jenkinsci/artifactory-plugin
src/main/java/org/jfrog/hudson/pipeline/declarative/utils/DeclarativePipelineUtils.java
DeclarativePipelineUtils.deleteOldBuildDataDirs
static void deleteOldBuildDataDirs(File tmpDir, Log logger) { if (!tmpDir.exists()) { // Before creation of the @tmp directory return; } File[] buildDataDirs = tmpDir.listFiles(buildDataDir -> { long ageInMilliseconds = new Date().getTime() - buildDataDir.lastModified(); return ageInMilliseconds > TimeUnit.DAYS.toMillis(1); }); if (buildDataDirs == null) { logger.error("Failed while attempting to delete old build data dirs. Could not list files in " + tmpDir); return; } for (File buildDataDir : buildDataDirs) { try { FileUtils.deleteDirectory(buildDataDir); logger.debug(buildDataDir.getAbsolutePath() + " deleted"); } catch (IOException e) { logger.error("Failed while attempting to delete old build data dir: " + buildDataDir.toString(), e); } } }
java
static void deleteOldBuildDataDirs(File tmpDir, Log logger) { if (!tmpDir.exists()) { // Before creation of the @tmp directory return; } File[] buildDataDirs = tmpDir.listFiles(buildDataDir -> { long ageInMilliseconds = new Date().getTime() - buildDataDir.lastModified(); return ageInMilliseconds > TimeUnit.DAYS.toMillis(1); }); if (buildDataDirs == null) { logger.error("Failed while attempting to delete old build data dirs. Could not list files in " + tmpDir); return; } for (File buildDataDir : buildDataDirs) { try { FileUtils.deleteDirectory(buildDataDir); logger.debug(buildDataDir.getAbsolutePath() + " deleted"); } catch (IOException e) { logger.error("Failed while attempting to delete old build data dir: " + buildDataDir.toString(), e); } } }
[ "static", "void", "deleteOldBuildDataDirs", "(", "File", "tmpDir", ",", "Log", "logger", ")", "{", "if", "(", "!", "tmpDir", ".", "exists", "(", ")", ")", "{", "// Before creation of the @tmp directory", "return", ";", "}", "File", "[", "]", "buildDataDirs", ...
Delete @tmp/artifactory-pipeline-cache/build-number directories older than 1 day.
[ "Delete" ]
train
https://github.com/jenkinsci/artifactory-plugin/blob/f5fcfff6a5a50be5374813e49d1fe3aaf6422333/src/main/java/org/jfrog/hudson/pipeline/declarative/utils/DeclarativePipelineUtils.java#L152-L174
OpenLiberty/open-liberty
dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/InvalidationAuditDaemon.java
InvalidationAuditDaemon.wakeUp
public void wakeUp(long startDaemonTime, long startWakeUpTime) { lastTimeCleared = startWakeUpTime; for (Map.Entry<String, InvalidationTableList> entry : cacheinvalidationTables.entrySet()) { InvalidationTableList invalidationTableList = entry.getValue(); try { invalidationTableList.readWriteLock.writeLock().lock(); invalidationTableList.pastIdSet.clear(); Map<Object, InvalidationEvent> temp = invalidationTableList.pastIdSet; invalidationTableList.pastIdSet = invalidationTableList.presentIdSet; invalidationTableList.presentIdSet = invalidationTableList.futureIdSet; invalidationTableList.futureIdSet = temp; invalidationTableList.pastTemplateSet.clear(); temp = invalidationTableList.pastTemplateSet; invalidationTableList.pastTemplateSet = invalidationTableList.presentTemplateSet; invalidationTableList.presentTemplateSet = invalidationTableList.futureTemplateSet; invalidationTableList.futureTemplateSet = temp; } finally { invalidationTableList.readWriteLock.writeLock().unlock(); } } }
java
public void wakeUp(long startDaemonTime, long startWakeUpTime) { lastTimeCleared = startWakeUpTime; for (Map.Entry<String, InvalidationTableList> entry : cacheinvalidationTables.entrySet()) { InvalidationTableList invalidationTableList = entry.getValue(); try { invalidationTableList.readWriteLock.writeLock().lock(); invalidationTableList.pastIdSet.clear(); Map<Object, InvalidationEvent> temp = invalidationTableList.pastIdSet; invalidationTableList.pastIdSet = invalidationTableList.presentIdSet; invalidationTableList.presentIdSet = invalidationTableList.futureIdSet; invalidationTableList.futureIdSet = temp; invalidationTableList.pastTemplateSet.clear(); temp = invalidationTableList.pastTemplateSet; invalidationTableList.pastTemplateSet = invalidationTableList.presentTemplateSet; invalidationTableList.presentTemplateSet = invalidationTableList.futureTemplateSet; invalidationTableList.futureTemplateSet = temp; } finally { invalidationTableList.readWriteLock.writeLock().unlock(); } } }
[ "public", "void", "wakeUp", "(", "long", "startDaemonTime", ",", "long", "startWakeUpTime", ")", "{", "lastTimeCleared", "=", "startWakeUpTime", ";", "for", "(", "Map", ".", "Entry", "<", "String", ",", "InvalidationTableList", ">", "entry", ":", "cacheinvalidat...
This is the method in the RealTimeDaemon base class. It is called periodically (period is timeHoldingInvalidations). @param startDaemonTime The absolute time when this daemon was first started. @param startWakeUpTime The absolute time when this wakeUp call was made.
[ "This", "is", "the", "method", "in", "the", "RealTimeDaemon", "base", "class", ".", "It", "is", "called", "periodically", "(", "period", "is", "timeHoldingInvalidations", ")", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/InvalidationAuditDaemon.java#L67-L92
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/preprocessing/text/KerasTokenizer.java
KerasTokenizer.reverseSortByValues
private static HashMap reverseSortByValues(HashMap map) { List list = new LinkedList(map.entrySet()); Collections.sort(list, new Comparator() { public int compare(Object o1, Object o2) { return ((Comparable) ((Map.Entry) (o1)).getValue()) .compareTo(((Map.Entry) (o2)).getValue()); } }); HashMap sortedHashMap = new LinkedHashMap(); for (Iterator it = list.iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); sortedHashMap.put(entry.getKey(), entry.getValue()); } return sortedHashMap; }
java
private static HashMap reverseSortByValues(HashMap map) { List list = new LinkedList(map.entrySet()); Collections.sort(list, new Comparator() { public int compare(Object o1, Object o2) { return ((Comparable) ((Map.Entry) (o1)).getValue()) .compareTo(((Map.Entry) (o2)).getValue()); } }); HashMap sortedHashMap = new LinkedHashMap(); for (Iterator it = list.iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); sortedHashMap.put(entry.getKey(), entry.getValue()); } return sortedHashMap; }
[ "private", "static", "HashMap", "reverseSortByValues", "(", "HashMap", "map", ")", "{", "List", "list", "=", "new", "LinkedList", "(", "map", ".", "entrySet", "(", ")", ")", ";", "Collections", ".", "sort", "(", "list", ",", "new", "Comparator", "(", ")"...
Sort HashMap by values in reverse order @param map input HashMap @return sorted HashMap
[ "Sort", "HashMap", "by", "values", "in", "reverse", "order" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/preprocessing/text/KerasTokenizer.java#L229-L243
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/models/paragraphvectors/ParagraphVectors.java
ParagraphVectors.inferVectorBatched
public Future<Pair<String, INDArray>> inferVectorBatched(@NonNull LabelledDocument document) { if (countSubmitted == null) initInference(); if (this.vocab == null || this.vocab.numWords() == 0) reassignExistingModel(); // we block execution until queued amount of documents gets below acceptable level, to avoid memory exhaust while (countSubmitted.get() - countFinished.get() > 1024) { ThreadUtils.uncheckedSleep(50); } InferenceCallable callable = new InferenceCallable(vocab, tokenizerFactory, document); Future<Pair<String, INDArray>> future = inferenceExecutor.submit(callable); countSubmitted.incrementAndGet(); return future; }
java
public Future<Pair<String, INDArray>> inferVectorBatched(@NonNull LabelledDocument document) { if (countSubmitted == null) initInference(); if (this.vocab == null || this.vocab.numWords() == 0) reassignExistingModel(); // we block execution until queued amount of documents gets below acceptable level, to avoid memory exhaust while (countSubmitted.get() - countFinished.get() > 1024) { ThreadUtils.uncheckedSleep(50); } InferenceCallable callable = new InferenceCallable(vocab, tokenizerFactory, document); Future<Pair<String, INDArray>> future = inferenceExecutor.submit(callable); countSubmitted.incrementAndGet(); return future; }
[ "public", "Future", "<", "Pair", "<", "String", ",", "INDArray", ">", ">", "inferVectorBatched", "(", "@", "NonNull", "LabelledDocument", "document", ")", "{", "if", "(", "countSubmitted", "==", "null", ")", "initInference", "(", ")", ";", "if", "(", "this...
This method implements batched inference, based on Java Future parallelism model. PLEASE NOTE: In order to use this method, LabelledDocument being passed in should have Id field defined. @param document @return
[ "This", "method", "implements", "batched", "inference", "based", "on", "Java", "Future", "parallelism", "model", "." ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/models/paragraphvectors/ParagraphVectors.java#L326-L343
fuinorg/srcgen4javassist
src/main/java/org/fuin/srcgen4javassist/ByteCodeGenerator.java
ByteCodeGenerator.createWithCurrentThreadContextClassLoader
public static ByteCodeGenerator createWithCurrentThreadContextClassLoader() { final ClassPool pool = ClassPool.getDefault(); final ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); pool.appendClassPath(new LoaderClassPath(classLoader)); return new ByteCodeGenerator(pool, classLoader); }
java
public static ByteCodeGenerator createWithCurrentThreadContextClassLoader() { final ClassPool pool = ClassPool.getDefault(); final ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); pool.appendClassPath(new LoaderClassPath(classLoader)); return new ByteCodeGenerator(pool, classLoader); }
[ "public", "static", "ByteCodeGenerator", "createWithCurrentThreadContextClassLoader", "(", ")", "{", "final", "ClassPool", "pool", "=", "ClassPool", ".", "getDefault", "(", ")", ";", "final", "ClassLoader", "classLoader", "=", "Thread", ".", "currentThread", "(", ")...
Creates a generator initialized with default class pool and the context class loader of the current thread. @return New byte code generator instance.
[ "Creates", "a", "generator", "initialized", "with", "default", "class", "pool", "and", "the", "context", "class", "loader", "of", "the", "current", "thread", "." ]
train
https://github.com/fuinorg/srcgen4javassist/blob/355828113cfce3cdd3d69ba242c5bdfc7d899f2f/src/main/java/org/fuin/srcgen4javassist/ByteCodeGenerator.java#L351-L356
signalapp/libsignal-service-java
java/src/main/java/org/whispersystems/signalservice/api/SignalServiceAccountManager.java
SignalServiceAccountManager.setPreKeys
public void setPreKeys(IdentityKey identityKey, SignedPreKeyRecord signedPreKey, List<PreKeyRecord> oneTimePreKeys) throws IOException { this.pushServiceSocket.registerPreKeys(identityKey, signedPreKey, oneTimePreKeys); }
java
public void setPreKeys(IdentityKey identityKey, SignedPreKeyRecord signedPreKey, List<PreKeyRecord> oneTimePreKeys) throws IOException { this.pushServiceSocket.registerPreKeys(identityKey, signedPreKey, oneTimePreKeys); }
[ "public", "void", "setPreKeys", "(", "IdentityKey", "identityKey", ",", "SignedPreKeyRecord", "signedPreKey", ",", "List", "<", "PreKeyRecord", ">", "oneTimePreKeys", ")", "throws", "IOException", "{", "this", ".", "pushServiceSocket", ".", "registerPreKeys", "(", "...
Register an identity key, signed prekey, and list of one time prekeys with the server. @param identityKey The client's long-term identity keypair. @param signedPreKey The client's signed prekey. @param oneTimePreKeys The client's list of one-time prekeys. @throws IOException
[ "Register", "an", "identity", "key", "signed", "prekey", "and", "list", "of", "one", "time", "prekeys", "with", "the", "server", "." ]
train
https://github.com/signalapp/libsignal-service-java/blob/64f1150c5e4062d67d31c9a2a9c3a0237d022902/java/src/main/java/org/whispersystems/signalservice/api/SignalServiceAccountManager.java#L206-L210
netscaler/nitro
src/main/java/com/citrix/netscaler/nitro/service/nitro_service.java
nitro_service.clear_config
public base_response clear_config(Boolean force, String level) throws Exception { base_response result = null; nsconfig resource = new nsconfig(); if (force) resource.set_force(force); resource.set_level(level); options option = new options(); option.set_action("clear"); result = resource.perform_operation(this, option); return result; }
java
public base_response clear_config(Boolean force, String level) throws Exception { base_response result = null; nsconfig resource = new nsconfig(); if (force) resource.set_force(force); resource.set_level(level); options option = new options(); option.set_action("clear"); result = resource.perform_operation(this, option); return result; }
[ "public", "base_response", "clear_config", "(", "Boolean", "force", ",", "String", "level", ")", "throws", "Exception", "{", "base_response", "result", "=", "null", ";", "nsconfig", "resource", "=", "new", "nsconfig", "(", ")", ";", "if", "(", "force", ")", ...
Use this API to clear configuration on netscaler. @param force clear confirmation without prompting. @param level clear config according to the level. eg: basic, extended, full @return status of the operation performed. @throws Exception Nitro exception is thrown.
[ "Use", "this", "API", "to", "clear", "configuration", "on", "netscaler", "." ]
train
https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/service/nitro_service.java#L369-L381
lessthanoptimal/BoofCV
main/boofcv-feature/src/main/java/boofcv/alg/feature/describe/DescribePointSift.java
DescribePointSift.computeRawDescriptor
void computeRawDescriptor(double c_x, double c_y, double sigma, double orientation, TupleDesc_F64 descriptor) { double c = Math.cos(orientation); double s = Math.sin(orientation); float fwidthSubregion = widthSubregion; int sampleWidth = widthGrid*widthSubregion; double sampleRadius = sampleWidth/2; double sampleToPixels = sigma*sigmaToPixels; Deriv image = (Deriv)imageDerivX.getImage(); for (int sampleY = 0; sampleY < sampleWidth; sampleY++) { float subY = sampleY/fwidthSubregion; double y = sampleToPixels*(sampleY-sampleRadius); for (int sampleX = 0; sampleX < sampleWidth; sampleX++) { // coordinate of samples in terms of sub-region. Center of sample point, hence + 0.5f float subX = sampleX/fwidthSubregion; // recentered local pixel sample coordinate double x = sampleToPixels*(sampleX-sampleRadius); // pixel coordinate in the image that is to be sampled. Note the rounding // If the pixel coordinate is -1 < x < 0 then it will round to 0 instead of -1, but the rounding // method below is WAY faster than Math.round() so this is a small loss. int pixelX = (int)(x*c - y*s + c_x + 0.5); int pixelY = (int)(x*s + y*c + c_y + 0.5); // skip pixels outside of the image if( image.isInBounds(pixelX,pixelY) ) { // spacial image derivative at this point float spacialDX = imageDerivX.unsafe_getF(pixelX, pixelY); float spacialDY = imageDerivY.unsafe_getF(pixelX, pixelY); double adjDX = c*spacialDX + s*spacialDY; double adjDY = -s*spacialDX + c*spacialDY; double angle = UtilAngle.domain2PI(Math.atan2(adjDY,adjDX)); float weightGaussian = gaussianWeight[sampleY*sampleWidth+sampleX]; float weightGradient = (float)Math.sqrt(spacialDX*spacialDX + spacialDY*spacialDY); // trilinear interpolation intro descriptor trilinearInterpolation(weightGaussian*weightGradient,subX,subY,angle, descriptor); } } } }
java
void computeRawDescriptor(double c_x, double c_y, double sigma, double orientation, TupleDesc_F64 descriptor) { double c = Math.cos(orientation); double s = Math.sin(orientation); float fwidthSubregion = widthSubregion; int sampleWidth = widthGrid*widthSubregion; double sampleRadius = sampleWidth/2; double sampleToPixels = sigma*sigmaToPixels; Deriv image = (Deriv)imageDerivX.getImage(); for (int sampleY = 0; sampleY < sampleWidth; sampleY++) { float subY = sampleY/fwidthSubregion; double y = sampleToPixels*(sampleY-sampleRadius); for (int sampleX = 0; sampleX < sampleWidth; sampleX++) { // coordinate of samples in terms of sub-region. Center of sample point, hence + 0.5f float subX = sampleX/fwidthSubregion; // recentered local pixel sample coordinate double x = sampleToPixels*(sampleX-sampleRadius); // pixel coordinate in the image that is to be sampled. Note the rounding // If the pixel coordinate is -1 < x < 0 then it will round to 0 instead of -1, but the rounding // method below is WAY faster than Math.round() so this is a small loss. int pixelX = (int)(x*c - y*s + c_x + 0.5); int pixelY = (int)(x*s + y*c + c_y + 0.5); // skip pixels outside of the image if( image.isInBounds(pixelX,pixelY) ) { // spacial image derivative at this point float spacialDX = imageDerivX.unsafe_getF(pixelX, pixelY); float spacialDY = imageDerivY.unsafe_getF(pixelX, pixelY); double adjDX = c*spacialDX + s*spacialDY; double adjDY = -s*spacialDX + c*spacialDY; double angle = UtilAngle.domain2PI(Math.atan2(adjDY,adjDX)); float weightGaussian = gaussianWeight[sampleY*sampleWidth+sampleX]; float weightGradient = (float)Math.sqrt(spacialDX*spacialDX + spacialDY*spacialDY); // trilinear interpolation intro descriptor trilinearInterpolation(weightGaussian*weightGradient,subX,subY,angle, descriptor); } } } }
[ "void", "computeRawDescriptor", "(", "double", "c_x", ",", "double", "c_y", ",", "double", "sigma", ",", "double", "orientation", ",", "TupleDesc_F64", "descriptor", ")", "{", "double", "c", "=", "Math", ".", "cos", "(", "orientation", ")", ";", "double", ...
Computes the descriptor by sampling the input image. This is raw because the descriptor hasn't been massaged yet.
[ "Computes", "the", "descriptor", "by", "sampling", "the", "input", "image", ".", "This", "is", "raw", "because", "the", "descriptor", "hasn", "t", "been", "massaged", "yet", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/feature/describe/DescribePointSift.java#L118-L165
kaazing/gateway
mina.core/core/src/main/java/org/apache/mina/proxy/handlers/http/ntlm/NTLMResponses.java
NTLMResponses.getNTLMResponse
public static byte[] getNTLMResponse(String password, byte[] challenge) throws Exception { byte[] ntlmHash = ntlmHash(password); return lmResponse(ntlmHash, challenge); }
java
public static byte[] getNTLMResponse(String password, byte[] challenge) throws Exception { byte[] ntlmHash = ntlmHash(password); return lmResponse(ntlmHash, challenge); }
[ "public", "static", "byte", "[", "]", "getNTLMResponse", "(", "String", "password", ",", "byte", "[", "]", "challenge", ")", "throws", "Exception", "{", "byte", "[", "]", "ntlmHash", "=", "ntlmHash", "(", "password", ")", ";", "return", "lmResponse", "(", ...
Calculates the NTLM Response for the given challenge, using the specified password. @param password The user's password. @param challenge The Type 2 challenge from the server. @return The NTLM Response.
[ "Calculates", "the", "NTLM", "Response", "for", "the", "given", "challenge", "using", "the", "specified", "password", "." ]
train
https://github.com/kaazing/gateway/blob/06017b19273109b3b992e528e702586446168d57/mina.core/core/src/main/java/org/apache/mina/proxy/handlers/http/ntlm/NTLMResponses.java#L76-L80
alkacon/opencms-core
src/org/opencms/ui/apps/lists/CmsListManager.java
CmsListManager.executeSearch
private void executeSearch(CmsSearchController controller, CmsSolrQuery query) { CmsObject cms = A_CmsUI.getCmsObject(); CmsSolrIndex index = OpenCms.getSearchManager().getIndexSolr( cms.getRequestContext().getCurrentProject().isOnlineProject() ? CmsSolrIndex.DEFAULT_INDEX_NAME_ONLINE : CmsSolrIndex.DEFAULT_INDEX_NAME_OFFLINE); try { CmsSolrResultList solrResultList = index.search(cms, query, true, CmsResourceFilter.IGNORE_EXPIRATION); displayResult(solrResultList); m_resultFacets.displayFacetResult( solrResultList, new CmsSearchResultWrapper(controller, solrResultList, query, cms, null)); } catch (CmsSearchException e) { CmsErrorDialog.showErrorDialog(e); LOG.error("Error executing search.", e); } }
java
private void executeSearch(CmsSearchController controller, CmsSolrQuery query) { CmsObject cms = A_CmsUI.getCmsObject(); CmsSolrIndex index = OpenCms.getSearchManager().getIndexSolr( cms.getRequestContext().getCurrentProject().isOnlineProject() ? CmsSolrIndex.DEFAULT_INDEX_NAME_ONLINE : CmsSolrIndex.DEFAULT_INDEX_NAME_OFFLINE); try { CmsSolrResultList solrResultList = index.search(cms, query, true, CmsResourceFilter.IGNORE_EXPIRATION); displayResult(solrResultList); m_resultFacets.displayFacetResult( solrResultList, new CmsSearchResultWrapper(controller, solrResultList, query, cms, null)); } catch (CmsSearchException e) { CmsErrorDialog.showErrorDialog(e); LOG.error("Error executing search.", e); } }
[ "private", "void", "executeSearch", "(", "CmsSearchController", "controller", ",", "CmsSolrQuery", "query", ")", "{", "CmsObject", "cms", "=", "A_CmsUI", ".", "getCmsObject", "(", ")", ";", "CmsSolrIndex", "index", "=", "OpenCms", ".", "getSearchManager", "(", "...
Executes a search.<p> @param controller the search controller @param query the SOLR query
[ "Executes", "a", "search", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/apps/lists/CmsListManager.java#L2106-L2124
attribyte/wpdb
src/main/java/org/attribyte/wp/db/DB.java
DB.setTermMeta
public void setTermMeta(final long termId, final List<Meta> termMeta) throws SQLException { clearTermMeta(termId); if(termMeta == null || termMeta.size() == 0) { return; } Connection conn = null; PreparedStatement stmt = null; Timer.Context ctx = metrics.setTermMetaTimer.time(); try { conn = connectionSupplier.getConnection(); stmt = conn.prepareStatement(insertTermMetaSQL); for(Meta meta : termMeta) { stmt.setLong(1, termId); stmt.setString(2, meta.key); stmt.setString(3, meta.value); stmt.executeUpdate(); } } finally { ctx.stop(); SQLUtil.closeQuietly(conn, stmt); } }
java
public void setTermMeta(final long termId, final List<Meta> termMeta) throws SQLException { clearTermMeta(termId); if(termMeta == null || termMeta.size() == 0) { return; } Connection conn = null; PreparedStatement stmt = null; Timer.Context ctx = metrics.setTermMetaTimer.time(); try { conn = connectionSupplier.getConnection(); stmt = conn.prepareStatement(insertTermMetaSQL); for(Meta meta : termMeta) { stmt.setLong(1, termId); stmt.setString(2, meta.key); stmt.setString(3, meta.value); stmt.executeUpdate(); } } finally { ctx.stop(); SQLUtil.closeQuietly(conn, stmt); } }
[ "public", "void", "setTermMeta", "(", "final", "long", "termId", ",", "final", "List", "<", "Meta", ">", "termMeta", ")", "throws", "SQLException", "{", "clearTermMeta", "(", "termId", ")", ";", "if", "(", "termMeta", "==", "null", "||", "termMeta", ".", ...
Sets metadata for a term. <p> Clears existing metadata. </p> @param termId The term id. @param termMeta The metadata. @throws SQLException on database error.
[ "Sets", "metadata", "for", "a", "term", ".", "<p", ">", "Clears", "existing", "metadata", ".", "<", "/", "p", ">" ]
train
https://github.com/attribyte/wpdb/blob/b9adf6131dfb67899ebff770c9bfeb001cc42f30/src/main/java/org/attribyte/wp/db/DB.java#L2085-L2108
UrielCh/ovh-java-sdk
ovh-java-sdk-hostingweb/src/main/java/net/minidev/ovh/api/ApiOvhHostingweb.java
ApiOvhHostingweb.serviceName_cron_id_PUT
public void serviceName_cron_id_PUT(String serviceName, Long id, OvhCron body) throws IOException { String qPath = "/hosting/web/{serviceName}/cron/{id}"; StringBuilder sb = path(qPath, serviceName, id); exec(qPath, "PUT", sb.toString(), body); }
java
public void serviceName_cron_id_PUT(String serviceName, Long id, OvhCron body) throws IOException { String qPath = "/hosting/web/{serviceName}/cron/{id}"; StringBuilder sb = path(qPath, serviceName, id); exec(qPath, "PUT", sb.toString(), body); }
[ "public", "void", "serviceName_cron_id_PUT", "(", "String", "serviceName", ",", "Long", "id", ",", "OvhCron", "body", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/hosting/web/{serviceName}/cron/{id}\"", ";", "StringBuilder", "sb", "=", "path", "(",...
Alter this object properties REST: PUT /hosting/web/{serviceName}/cron/{id} @param body [required] New object properties @param serviceName [required] The internal name of your hosting @param id [required] Cron's id
[ "Alter", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-hostingweb/src/main/java/net/minidev/ovh/api/ApiOvhHostingweb.java#L2095-L2099
pryzach/midao
midao-jdbc-dbcp-1-4/src/main/java/org/midao/jdbc/core/pool/MjdbcPoolBinder.java
MjdbcPoolBinder.createDataSource
public static DataSource createDataSource(String driverClassName, String url, String userName, String password) throws SQLException { return createDataSource(driverClassName, url, userName, password, 10, 100); }
java
public static DataSource createDataSource(String driverClassName, String url, String userName, String password) throws SQLException { return createDataSource(driverClassName, url, userName, password, 10, 100); }
[ "public", "static", "DataSource", "createDataSource", "(", "String", "driverClassName", ",", "String", "url", ",", "String", "userName", ",", "String", "password", ")", "throws", "SQLException", "{", "return", "createDataSource", "(", "driverClassName", ",", "url", ...
Returns new Pooled {@link DataSource} implementation <p/> In case this function won't work - use {@link #createDataSource(java.util.Properties)} @param driverClassName Driver Class name @param url Database connection url @param userName Database user name @param password Database user password @return new Pooled {@link DataSource} implementation @throws SQLException
[ "Returns", "new", "Pooled", "{", "@link", "DataSource", "}", "implementation", "<p", "/", ">", "In", "case", "this", "function", "won", "t", "work", "-", "use", "{", "@link", "#createDataSource", "(", "java", ".", "util", ".", "Properties", ")", "}" ]
train
https://github.com/pryzach/midao/blob/ed9048ed2c792a4794a2116a25779dfb84cd9447/midao-jdbc-dbcp-1-4/src/main/java/org/midao/jdbc/core/pool/MjdbcPoolBinder.java#L103-L105
codescape/bitvunit
bitvunit-core/src/main/java/de/codescape/bitvunit/report/TextReportWriter.java
TextReportWriter.printTitle
private void printTitle(HtmlPage htmlPage, PrintWriter out) { out.println(String.format("BitvUnit %s Report - %s - %s", getBitvUnitVersion(), htmlPage.getUrl(), getFormattedDate())); }
java
private void printTitle(HtmlPage htmlPage, PrintWriter out) { out.println(String.format("BitvUnit %s Report - %s - %s", getBitvUnitVersion(), htmlPage.getUrl(), getFormattedDate())); }
[ "private", "void", "printTitle", "(", "HtmlPage", "htmlPage", ",", "PrintWriter", "out", ")", "{", "out", ".", "println", "(", "String", ".", "format", "(", "\"BitvUnit %s Report - %s - %s\"", ",", "getBitvUnitVersion", "(", ")", ",", "htmlPage", ".", "getUrl", ...
Writes the header. @param htmlPage {@link HtmlPage} that was inspected @param out target where the report is written to
[ "Writes", "the", "header", "." ]
train
https://github.com/codescape/bitvunit/blob/cef6d9af60d684e41294981c10b6d92c8f063a4e/bitvunit-core/src/main/java/de/codescape/bitvunit/report/TextReportWriter.java#L49-L51
wcm-io/wcm-io-wcm
commons/src/main/java/io/wcm/wcm/commons/caching/CacheHeader.java
CacheHeader.setExpiresDays
public static void setExpiresDays(@NotNull HttpServletResponse response, int days) { Date expiresDate = DateUtils.addDays(new Date(), days); setExpires(response, expiresDate); }
java
public static void setExpiresDays(@NotNull HttpServletResponse response, int days) { Date expiresDate = DateUtils.addDays(new Date(), days); setExpires(response, expiresDate); }
[ "public", "static", "void", "setExpiresDays", "(", "@", "NotNull", "HttpServletResponse", "response", ",", "int", "days", ")", "{", "Date", "expiresDate", "=", "DateUtils", ".", "addDays", "(", "new", "Date", "(", ")", ",", "days", ")", ";", "setExpires", ...
Set expires header to given amount of days in the future. @param response Response @param days Days to expire
[ "Set", "expires", "header", "to", "given", "amount", "of", "days", "in", "the", "future", "." ]
train
https://github.com/wcm-io/wcm-io-wcm/blob/8eff9434f2f4b6462fdb718f8769ad793c55b8d7/commons/src/main/java/io/wcm/wcm/commons/caching/CacheHeader.java#L252-L255
baasbox/Android-SDK
library/src/main/java/com/baasbox/android/BaasDocument.java
BaasDocument.countSync
public static BaasResult<Long> countSync(String collection, BaasQuery.Criteria filter) { BaasBox box = BaasBox.getDefaultChecked(); if (collection == null) throw new IllegalArgumentException("collection cannot be null"); filter = filter==null?BaasQuery.builder().count(true).criteria() :filter.buildUpon().count(true).criteria(); Count request = new Count(box, collection, filter, RequestOptions.DEFAULT, null); return box.submitSync(request); }
java
public static BaasResult<Long> countSync(String collection, BaasQuery.Criteria filter) { BaasBox box = BaasBox.getDefaultChecked(); if (collection == null) throw new IllegalArgumentException("collection cannot be null"); filter = filter==null?BaasQuery.builder().count(true).criteria() :filter.buildUpon().count(true).criteria(); Count request = new Count(box, collection, filter, RequestOptions.DEFAULT, null); return box.submitSync(request); }
[ "public", "static", "BaasResult", "<", "Long", ">", "countSync", "(", "String", "collection", ",", "BaasQuery", ".", "Criteria", "filter", ")", "{", "BaasBox", "box", "=", "BaasBox", ".", "getDefaultChecked", "(", ")", ";", "if", "(", "collection", "==", "...
Synchronously retrieves the number of document readable to the user that match <code>filter</code> in <code>collection</code> @param collection the collection to doCount not <code>null</code> @param filter a filter to apply to the request @return the result of the request
[ "Synchronously", "retrieves", "the", "number", "of", "document", "readable", "to", "the", "user", "that", "match", "<code", ">", "filter<", "/", "code", ">", "in", "<code", ">", "collection<", "/", "code", ">" ]
train
https://github.com/baasbox/Android-SDK/blob/6bb2203246b885b2ad63a7bfaf37c83caf15e0d8/library/src/main/java/com/baasbox/android/BaasDocument.java#L357-L364
Mozu/mozu-java
mozu-java-core/src/main/java/com/mozu/api/urls/commerce/catalog/admin/attributedefinition/producttypes/ProductTypeOptionUrl.java
ProductTypeOptionUrl.addOptionUrl
public static MozuUrl addOptionUrl(Integer productTypeId, String responseFields) { UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/admin/attributedefinition/producttypes/{productTypeId}/Options?responseFields={responseFields}"); formatter.formatUrl("productTypeId", productTypeId); formatter.formatUrl("responseFields", responseFields); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
java
public static MozuUrl addOptionUrl(Integer productTypeId, String responseFields) { UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/admin/attributedefinition/producttypes/{productTypeId}/Options?responseFields={responseFields}"); formatter.formatUrl("productTypeId", productTypeId); formatter.formatUrl("responseFields", responseFields); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
[ "public", "static", "MozuUrl", "addOptionUrl", "(", "Integer", "productTypeId", ",", "String", "responseFields", ")", "{", "UrlFormatter", "formatter", "=", "new", "UrlFormatter", "(", "\"/api/commerce/catalog/admin/attributedefinition/producttypes/{productTypeId}/Options?respons...
Get Resource Url for AddOption @param productTypeId Identifier of the product type. @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss. @return String Resource Url
[ "Get", "Resource", "Url", "for", "AddOption" ]
train
https://github.com/Mozu/mozu-java/blob/5beadde73601a859f845e3e2fc1077b39c8bea83/mozu-java-core/src/main/java/com/mozu/api/urls/commerce/catalog/admin/attributedefinition/producttypes/ProductTypeOptionUrl.java#L50-L56
highsource/jaxb2-basics
runtime/src/main/java/org/jvnet/jaxb2_commons/lang/ClassUtils.java
ClassUtils.getShortClassName
public static String getShortClassName(String className) { if (className == null) { return ""; } if (className.length() == 0) { return ""; } char[] chars = className.toCharArray(); int lastDot = 0; for (int i = 0; i < chars.length; i++) { if (chars[i] == PACKAGE_SEPARATOR_CHAR) { lastDot = i + 1; } else if (chars[i] == INNER_CLASS_SEPARATOR_CHAR) { // handle inner // classes chars[i] = PACKAGE_SEPARATOR_CHAR; } } return new String(chars, lastDot, chars.length - lastDot); }
java
public static String getShortClassName(String className) { if (className == null) { return ""; } if (className.length() == 0) { return ""; } char[] chars = className.toCharArray(); int lastDot = 0; for (int i = 0; i < chars.length; i++) { if (chars[i] == PACKAGE_SEPARATOR_CHAR) { lastDot = i + 1; } else if (chars[i] == INNER_CLASS_SEPARATOR_CHAR) { // handle inner // classes chars[i] = PACKAGE_SEPARATOR_CHAR; } } return new String(chars, lastDot, chars.length - lastDot); }
[ "public", "static", "String", "getShortClassName", "(", "String", "className", ")", "{", "if", "(", "className", "==", "null", ")", "{", "return", "\"\"", ";", "}", "if", "(", "className", ".", "length", "(", ")", "==", "0", ")", "{", "return", "\"\"",...
<p> Gets the class name minus the package name from a String. </p> <p> The string passed in is assumed to be a class name - it is not checked. </p> @param className the className to get the short name for @return the class name of the class without the package name or an empty string
[ "<p", ">", "Gets", "the", "class", "name", "minus", "the", "package", "name", "from", "a", "String", ".", "<", "/", "p", ">" ]
train
https://github.com/highsource/jaxb2-basics/blob/571cca0ce58a75d984324d33d8af453bf5862e75/runtime/src/main/java/org/jvnet/jaxb2_commons/lang/ClassUtils.java#L42-L60
micronaut-projects/micronaut-core
core/src/main/java/io/micronaut/core/reflect/ReflectionUtils.java
ReflectionUtils.invokeMethod
public static <R, T> R invokeMethod(T instance, Method method, Object... arguments) { try { return (R) method.invoke(instance, arguments); } catch (IllegalAccessException e) { throw new InvocationException("Illegal access invoking method [" + method + "]: " + e.getMessage(), e); } catch (InvocationTargetException e) { throw new InvocationException("Exception occurred invoking method [" + method + "]: " + e.getMessage(), e); } }
java
public static <R, T> R invokeMethod(T instance, Method method, Object... arguments) { try { return (R) method.invoke(instance, arguments); } catch (IllegalAccessException e) { throw new InvocationException("Illegal access invoking method [" + method + "]: " + e.getMessage(), e); } catch (InvocationTargetException e) { throw new InvocationException("Exception occurred invoking method [" + method + "]: " + e.getMessage(), e); } }
[ "public", "static", "<", "R", ",", "T", ">", "R", "invokeMethod", "(", "T", "instance", ",", "Method", "method", ",", "Object", "...", "arguments", ")", "{", "try", "{", "return", "(", "R", ")", "method", ".", "invoke", "(", "instance", ",", "argumen...
Invokes a method. @param instance The instance @param method The method @param arguments The arguments @param <R> The return type @param <T> The instance type @return The result
[ "Invokes", "a", "method", "." ]
train
https://github.com/micronaut-projects/micronaut-core/blob/c31f5b03ce0eb88c2f6470710987db03b8967d5c/core/src/main/java/io/micronaut/core/reflect/ReflectionUtils.java#L196-L204
guicamest/bsoneer
compiler/compiler/src/main/java/com/sleepcamel/bsoneer/processor/util/Util.java
Util.getAnnotation
public static Map<String, Object> getAnnotation(Class<?> annotationType, Element element) { for (AnnotationMirror annotation : element.getAnnotationMirrors()) { if (!rawTypeToString(annotation.getAnnotationType(), '$').equals( annotationType.getName())) { continue; } return parseAnnotationMirror(annotationType, annotation); } return null; // Annotation not found. }
java
public static Map<String, Object> getAnnotation(Class<?> annotationType, Element element) { for (AnnotationMirror annotation : element.getAnnotationMirrors()) { if (!rawTypeToString(annotation.getAnnotationType(), '$').equals( annotationType.getName())) { continue; } return parseAnnotationMirror(annotationType, annotation); } return null; // Annotation not found. }
[ "public", "static", "Map", "<", "String", ",", "Object", ">", "getAnnotation", "(", "Class", "<", "?", ">", "annotationType", ",", "Element", "element", ")", "{", "for", "(", "AnnotationMirror", "annotation", ":", "element", ".", "getAnnotationMirrors", "(", ...
Returns the annotation on {@code element} formatted as a Map. This returns a Map rather than an instance of the annotation interface to work-around the fact that Class and Class[] fields won't work at code generation time. See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5089128
[ "Returns", "the", "annotation", "on", "{" ]
train
https://github.com/guicamest/bsoneer/blob/170a4a5d99519c49ee01a38bb1562a42375f686d/compiler/compiler/src/main/java/com/sleepcamel/bsoneer/processor/util/Util.java#L137-L148
OpenLiberty/open-liberty
dev/com.ibm.ws.config/src/com/ibm/ws/config/admin/internal/ConfigurationStore.java
ConfigurationStore.deserializeConfigurationData
ExtendedConfigurationImpl deserializeConfigurationData(String pid) throws IOException { ExtendedConfigurationImpl config = null; File configFile = persistedConfig.getConfigFile(pid); if (configFile != null) { if (configFile.length() > 0) { FileInputStream fis = null; ObjectInputStream ois = null; try { fis = new FileInputStream(configFile); ois = new ObjectInputStream(new BufferedInputStream(fis)); @SuppressWarnings("unchecked") Dictionary<String, Object> d = (Dictionary<String, Object>) ois.readObject(); String location; location = (String) ois.readObject(); ois.readBoolean(); @SuppressWarnings("unchecked") Set<ConfigID> references = (Set<ConfigID>) ois.readObject(); @SuppressWarnings("unchecked") Set<String> uniqueVariables = (Set<String>) ois.readObject(); String factoryPid = (String) d.get(ConfigurationAdmin.SERVICE_FACTORYPID); VariableRegistry variableRegistry = caFactory.getVariableRegistry(); for (String variable : uniqueVariables) { variableRegistry.addVariable(variable, ConfigAdminConstants.VAR_IN_USE); } config = new ExtendedConfigurationImpl(caFactory, location, factoryPid, pid, d, references, uniqueVariables); } catch (ClassNotFoundException e) { throw new IOException(e); } finally { ConfigUtil.closeIO(ois); ConfigUtil.closeIO(fis); } } } return config; }
java
ExtendedConfigurationImpl deserializeConfigurationData(String pid) throws IOException { ExtendedConfigurationImpl config = null; File configFile = persistedConfig.getConfigFile(pid); if (configFile != null) { if (configFile.length() > 0) { FileInputStream fis = null; ObjectInputStream ois = null; try { fis = new FileInputStream(configFile); ois = new ObjectInputStream(new BufferedInputStream(fis)); @SuppressWarnings("unchecked") Dictionary<String, Object> d = (Dictionary<String, Object>) ois.readObject(); String location; location = (String) ois.readObject(); ois.readBoolean(); @SuppressWarnings("unchecked") Set<ConfigID> references = (Set<ConfigID>) ois.readObject(); @SuppressWarnings("unchecked") Set<String> uniqueVariables = (Set<String>) ois.readObject(); String factoryPid = (String) d.get(ConfigurationAdmin.SERVICE_FACTORYPID); VariableRegistry variableRegistry = caFactory.getVariableRegistry(); for (String variable : uniqueVariables) { variableRegistry.addVariable(variable, ConfigAdminConstants.VAR_IN_USE); } config = new ExtendedConfigurationImpl(caFactory, location, factoryPid, pid, d, references, uniqueVariables); } catch (ClassNotFoundException e) { throw new IOException(e); } finally { ConfigUtil.closeIO(ois); ConfigUtil.closeIO(fis); } } } return config; }
[ "ExtendedConfigurationImpl", "deserializeConfigurationData", "(", "String", "pid", ")", "throws", "IOException", "{", "ExtendedConfigurationImpl", "config", "=", "null", ";", "File", "configFile", "=", "persistedConfig", ".", "getConfigFile", "(", "pid", ")", ";", "if...
If a serialized file does not exist, a null is returned. If a serialized file exists for the given pid, it deserializes configuration dictionary and bound location and returns in an array of size 2. Index 0 of returning array contains configuration dictionary. Index 1 of returning array contains bound bundle location in String Index 2 of returning array contains whether Meta-Type processsing was done or not (if CMConstants.METATYPE_PROCESSED, then yes. if null, then no.) @param pid
[ "If", "a", "serialized", "file", "does", "not", "exist", "a", "null", "is", "returned", ".", "If", "a", "serialized", "file", "exists", "for", "the", "given", "pid", "it", "deserializes", "configuration", "dictionary", "and", "bound", "location", "and", "ret...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.config/src/com/ibm/ws/config/admin/internal/ConfigurationStore.java#L230-L270
haraldk/TwelveMonkeys
common/common-image/src/main/java/com/twelvemonkeys/image/MagickUtil.java
MagickUtil.createIndexColorModel
public static IndexColorModel createIndexColorModel(PixelPacket[] pColormap, boolean pAlpha) { int[] colors = new int[pColormap.length]; // TODO: Verify if this is correct for alpha...? int trans = pAlpha ? colors.length - 1 : -1; //for (int i = 0; i < pColormap.length; i++) { for (int i = pColormap.length - 1; i != 0; i--) { PixelPacket color = pColormap[i]; if (pAlpha) { colors[i] = (0xff - (color.getOpacity() & 0xff)) << 24 | (color.getRed() & 0xff) << 16 | (color.getGreen() & 0xff) << 8 | (color.getBlue() & 0xff); } else { colors[i] = (color.getRed() & 0xff) << 16 | (color.getGreen() & 0xff) << 8 | (color.getBlue() & 0xff); } } return new InverseColorMapIndexColorModel(8, colors.length, colors, 0, pAlpha, trans, DataBuffer.TYPE_BYTE); }
java
public static IndexColorModel createIndexColorModel(PixelPacket[] pColormap, boolean pAlpha) { int[] colors = new int[pColormap.length]; // TODO: Verify if this is correct for alpha...? int trans = pAlpha ? colors.length - 1 : -1; //for (int i = 0; i < pColormap.length; i++) { for (int i = pColormap.length - 1; i != 0; i--) { PixelPacket color = pColormap[i]; if (pAlpha) { colors[i] = (0xff - (color.getOpacity() & 0xff)) << 24 | (color.getRed() & 0xff) << 16 | (color.getGreen() & 0xff) << 8 | (color.getBlue() & 0xff); } else { colors[i] = (color.getRed() & 0xff) << 16 | (color.getGreen() & 0xff) << 8 | (color.getBlue() & 0xff); } } return new InverseColorMapIndexColorModel(8, colors.length, colors, 0, pAlpha, trans, DataBuffer.TYPE_BYTE); }
[ "public", "static", "IndexColorModel", "createIndexColorModel", "(", "PixelPacket", "[", "]", "pColormap", ",", "boolean", "pAlpha", ")", "{", "int", "[", "]", "colors", "=", "new", "int", "[", "pColormap", ".", "length", "]", ";", "// TODO: Verify if this is co...
Creates an {@code IndexColorModel} from an array of {@code PixelPacket}s. @param pColormap the original colormap as a {@code PixelPacket} array @param pAlpha keep alpha channel @return a new {@code IndexColorModel}
[ "Creates", "an", "{", "@code", "IndexColorModel", "}", "from", "an", "array", "of", "{", "@code", "PixelPacket", "}", "s", "." ]
train
https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/common/common-image/src/main/java/com/twelvemonkeys/image/MagickUtil.java#L499-L522
alkacon/opencms-core
src-gwt/org/opencms/ade/containerpage/client/CmsContainerpageHandler.java
CmsContainerpageHandler.createViewOnlineEntry
protected I_CmsContextMenuEntry createViewOnlineEntry() { final String onlineLink = m_controller.getData().getOnlineLink(); CmsContextMenuEntry entry = null; if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(onlineLink)) { I_CmsContextMenuCommand command = new I_CmsContextMenuCommand() { public void execute( CmsUUID structureId, I_CmsContextMenuHandler handler, CmsContextMenuEntryBean bean) { Window.open(onlineLink, "opencms-online", null); } public A_CmsContextMenuItem getItemWidget( CmsUUID structureId, I_CmsContextMenuHandler handler, CmsContextMenuEntryBean bean) { return null; } public boolean hasItemWidget() { return false; } }; entry = new CmsContextMenuEntry(this, null, command); CmsContextMenuEntryBean entryBean = new CmsContextMenuEntryBean(); entryBean.setLabel(Messages.get().key(Messages.GUI_VIEW_ONLINE_0)); entryBean.setActive(true); entryBean.setVisible(true); entry.setBean(entryBean); } return entry; }
java
protected I_CmsContextMenuEntry createViewOnlineEntry() { final String onlineLink = m_controller.getData().getOnlineLink(); CmsContextMenuEntry entry = null; if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(onlineLink)) { I_CmsContextMenuCommand command = new I_CmsContextMenuCommand() { public void execute( CmsUUID structureId, I_CmsContextMenuHandler handler, CmsContextMenuEntryBean bean) { Window.open(onlineLink, "opencms-online", null); } public A_CmsContextMenuItem getItemWidget( CmsUUID structureId, I_CmsContextMenuHandler handler, CmsContextMenuEntryBean bean) { return null; } public boolean hasItemWidget() { return false; } }; entry = new CmsContextMenuEntry(this, null, command); CmsContextMenuEntryBean entryBean = new CmsContextMenuEntryBean(); entryBean.setLabel(Messages.get().key(Messages.GUI_VIEW_ONLINE_0)); entryBean.setActive(true); entryBean.setVisible(true); entry.setBean(entryBean); } return entry; }
[ "protected", "I_CmsContextMenuEntry", "createViewOnlineEntry", "(", ")", "{", "final", "String", "onlineLink", "=", "m_controller", ".", "getData", "(", ")", ".", "getOnlineLink", "(", ")", ";", "CmsContextMenuEntry", "entry", "=", "null", ";", "if", "(", "CmsSt...
Creates the view online entry, if an online link is available.<p> @return the menu entry or null, if not available
[ "Creates", "the", "view", "online", "entry", "if", "an", "online", "link", "is", "available", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/containerpage/client/CmsContainerpageHandler.java#L1451-L1487
netscaler/nitro
src/main/java/com/citrix/netscaler/nitro/resource/config/authorization/authorizationpolicy_binding.java
authorizationpolicy_binding.get
public static authorizationpolicy_binding get(nitro_service service, String name) throws Exception{ authorizationpolicy_binding obj = new authorizationpolicy_binding(); obj.set_name(name); authorizationpolicy_binding response = (authorizationpolicy_binding) obj.get_resource(service); return response; }
java
public static authorizationpolicy_binding get(nitro_service service, String name) throws Exception{ authorizationpolicy_binding obj = new authorizationpolicy_binding(); obj.set_name(name); authorizationpolicy_binding response = (authorizationpolicy_binding) obj.get_resource(service); return response; }
[ "public", "static", "authorizationpolicy_binding", "get", "(", "nitro_service", "service", ",", "String", "name", ")", "throws", "Exception", "{", "authorizationpolicy_binding", "obj", "=", "new", "authorizationpolicy_binding", "(", ")", ";", "obj", ".", "set_name", ...
Use this API to fetch authorizationpolicy_binding resource of given name .
[ "Use", "this", "API", "to", "fetch", "authorizationpolicy_binding", "resource", "of", "given", "name", "." ]
train
https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/authorization/authorizationpolicy_binding.java#L147-L152
find-sec-bugs/find-sec-bugs
findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/common/ByteCode.java
ByteCode.getConstantLDC
public static <T> T getConstantLDC(InstructionHandle h, ConstantPoolGen cpg, Class<T> clazz) { Instruction prevIns = h.getInstruction(); if (prevIns instanceof LDC) { LDC ldcInst = (LDC) prevIns; Object val = ldcInst.getValue(cpg); if (val.getClass().equals(clazz)) { return clazz.cast(val); } } else if(clazz.equals(String.class) && prevIns instanceof INVOKESPECIAL) { //This additionnal call allow the support of hardcoded value passed to String constructor //new String("HARDCODE") INVOKESPECIAL invoke = (INVOKESPECIAL) prevIns; if(invoke.getMethodName(cpg).equals("<init>") && invoke.getClassName(cpg).equals("java.lang.String") && invoke.getSignature(cpg).equals("(Ljava/lang/String;)V")) { return getConstantLDC(h.getPrev(), cpg, clazz); } } return null; }
java
public static <T> T getConstantLDC(InstructionHandle h, ConstantPoolGen cpg, Class<T> clazz) { Instruction prevIns = h.getInstruction(); if (prevIns instanceof LDC) { LDC ldcInst = (LDC) prevIns; Object val = ldcInst.getValue(cpg); if (val.getClass().equals(clazz)) { return clazz.cast(val); } } else if(clazz.equals(String.class) && prevIns instanceof INVOKESPECIAL) { //This additionnal call allow the support of hardcoded value passed to String constructor //new String("HARDCODE") INVOKESPECIAL invoke = (INVOKESPECIAL) prevIns; if(invoke.getMethodName(cpg).equals("<init>") && invoke.getClassName(cpg).equals("java.lang.String") && invoke.getSignature(cpg).equals("(Ljava/lang/String;)V")) { return getConstantLDC(h.getPrev(), cpg, clazz); } } return null; }
[ "public", "static", "<", "T", ">", "T", "getConstantLDC", "(", "InstructionHandle", "h", ",", "ConstantPoolGen", "cpg", ",", "Class", "<", "T", ">", "clazz", ")", "{", "Instruction", "prevIns", "=", "h", ".", "getInstruction", "(", ")", ";", "if", "(", ...
Get the constant value of the given instruction. (The instruction must refer to the Constant Pool otherwise null is return) &lt;T&gt; is the Type of the constant value return This utility method should be used only when the taint analysis is not needed. For example, to detect api where the value will typically be hardcoded. (Call such as setConfig("valueHardcoded"), setActivateStuff(true) ) @param h Instruction Handle @param cpg Constant Pool @param clazz Type of the constant being read @return The constant value if any is found
[ "Get", "the", "constant", "value", "of", "the", "given", "instruction", ".", "(", "The", "instruction", "must", "refer", "to", "the", "Constant", "Pool", "otherwise", "null", "is", "return", ")" ]
train
https://github.com/find-sec-bugs/find-sec-bugs/blob/362da013cef4925e6a1506dd3511fe5bdcc5fba3/findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/common/ByteCode.java#L97-L117
facebookarchive/hadoop-20
src/core/org/apache/hadoop/util/MRAsyncDiskService.java
MRAsyncDiskService.moveAndDeleteRelativePath
public boolean moveAndDeleteRelativePath(String volume, String pathName) throws IOException { volume = normalizePath(volume); // Move the file right now, so that it can be deleted later String newPathName = format.format(new Date()) + "_" + uniqueId.getAndIncrement(); newPathName = TOBEDELETED + Path.SEPARATOR_CHAR + newPathName; Path source = new Path(volume, pathName); Path target = new Path(volume, newPathName); try { if (!localFileSystem.rename(source, target)) { // If the source does not exists, return false. // This is necessary because rename can return false if the source // does not exists. if (!localFileSystem.exists(source)) { return false; } // Try to recreate the parent directory just in case it gets deleted. if (!localFileSystem.mkdirs(new Path(volume, TOBEDELETED))) { throw new IOException("Cannot create " + TOBEDELETED + " under " + volume); } // Try rename again. If it fails, return false. if (!localFileSystem.rename(source, target)) { throw new IOException("Cannot rename " + source + " to " + target); } } } catch (FileNotFoundException e) { // Return false in case that the file is not found. return false; } DeleteTask task = new DeleteTask(volume, pathName, newPathName); execute(volume, task); return true; }
java
public boolean moveAndDeleteRelativePath(String volume, String pathName) throws IOException { volume = normalizePath(volume); // Move the file right now, so that it can be deleted later String newPathName = format.format(new Date()) + "_" + uniqueId.getAndIncrement(); newPathName = TOBEDELETED + Path.SEPARATOR_CHAR + newPathName; Path source = new Path(volume, pathName); Path target = new Path(volume, newPathName); try { if (!localFileSystem.rename(source, target)) { // If the source does not exists, return false. // This is necessary because rename can return false if the source // does not exists. if (!localFileSystem.exists(source)) { return false; } // Try to recreate the parent directory just in case it gets deleted. if (!localFileSystem.mkdirs(new Path(volume, TOBEDELETED))) { throw new IOException("Cannot create " + TOBEDELETED + " under " + volume); } // Try rename again. If it fails, return false. if (!localFileSystem.rename(source, target)) { throw new IOException("Cannot rename " + source + " to " + target); } } } catch (FileNotFoundException e) { // Return false in case that the file is not found. return false; } DeleteTask task = new DeleteTask(volume, pathName, newPathName); execute(volume, task); return true; }
[ "public", "boolean", "moveAndDeleteRelativePath", "(", "String", "volume", ",", "String", "pathName", ")", "throws", "IOException", "{", "volume", "=", "normalizePath", "(", "volume", ")", ";", "// Move the file right now, so that it can be deleted later", "String", "newP...
Move the path name on one volume to a temporary location and then delete them. This functions returns when the moves are done, but not necessarily all deletions are done. This is usually good enough because applications won't see the path name under the old name anyway after the move. @param volume The disk volume @param pathName The path name relative to volume root. @throws IOException If the move failed @return false if the file is not found
[ "Move", "the", "path", "name", "on", "one", "volume", "to", "a", "temporary", "location", "and", "then", "delete", "them", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/util/MRAsyncDiskService.java#L251-L290
Impetus/Kundera
src/kundera-kudu/src/main/java/com/impetus/client/kudu/KuduDBClient.java
KuduDBClient.populateEntity
public void populateEntity(Object entity, RowResult result, EntityType entityType, MetamodelImpl metaModel) { Set<Attribute> attributes = entityType.getAttributes(); Iterator<Attribute> iterator = attributes.iterator(); iterateAndPopulateEntity(entity, result, metaModel, iterator); }
java
public void populateEntity(Object entity, RowResult result, EntityType entityType, MetamodelImpl metaModel) { Set<Attribute> attributes = entityType.getAttributes(); Iterator<Attribute> iterator = attributes.iterator(); iterateAndPopulateEntity(entity, result, metaModel, iterator); }
[ "public", "void", "populateEntity", "(", "Object", "entity", ",", "RowResult", "result", ",", "EntityType", "entityType", ",", "MetamodelImpl", "metaModel", ")", "{", "Set", "<", "Attribute", ">", "attributes", "=", "entityType", ".", "getAttributes", "(", ")", ...
Populate entity. @param entity the entity @param result the result @param entityType the entity type @param metaModel the meta model
[ "Populate", "entity", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-kudu/src/main/java/com/impetus/client/kudu/KuduDBClient.java#L286-L291
Azure/azure-sdk-for-java
cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/TrainingsImpl.java
TrainingsImpl.getIterationPerformanceWithServiceResponseAsync
public Observable<ServiceResponse<IterationPerformance>> getIterationPerformanceWithServiceResponseAsync(UUID projectId, UUID iterationId, GetIterationPerformanceOptionalParameter getIterationPerformanceOptionalParameter) { if (projectId == null) { throw new IllegalArgumentException("Parameter projectId is required and cannot be null."); } if (iterationId == null) { throw new IllegalArgumentException("Parameter iterationId is required and cannot be null."); } if (this.client.apiKey() == null) { throw new IllegalArgumentException("Parameter this.client.apiKey() is required and cannot be null."); } final Double threshold = getIterationPerformanceOptionalParameter != null ? getIterationPerformanceOptionalParameter.threshold() : null; final Double overlapThreshold = getIterationPerformanceOptionalParameter != null ? getIterationPerformanceOptionalParameter.overlapThreshold() : null; return getIterationPerformanceWithServiceResponseAsync(projectId, iterationId, threshold, overlapThreshold); }
java
public Observable<ServiceResponse<IterationPerformance>> getIterationPerformanceWithServiceResponseAsync(UUID projectId, UUID iterationId, GetIterationPerformanceOptionalParameter getIterationPerformanceOptionalParameter) { if (projectId == null) { throw new IllegalArgumentException("Parameter projectId is required and cannot be null."); } if (iterationId == null) { throw new IllegalArgumentException("Parameter iterationId is required and cannot be null."); } if (this.client.apiKey() == null) { throw new IllegalArgumentException("Parameter this.client.apiKey() is required and cannot be null."); } final Double threshold = getIterationPerformanceOptionalParameter != null ? getIterationPerformanceOptionalParameter.threshold() : null; final Double overlapThreshold = getIterationPerformanceOptionalParameter != null ? getIterationPerformanceOptionalParameter.overlapThreshold() : null; return getIterationPerformanceWithServiceResponseAsync(projectId, iterationId, threshold, overlapThreshold); }
[ "public", "Observable", "<", "ServiceResponse", "<", "IterationPerformance", ">", ">", "getIterationPerformanceWithServiceResponseAsync", "(", "UUID", "projectId", ",", "UUID", "iterationId", ",", "GetIterationPerformanceOptionalParameter", "getIterationPerformanceOptionalParameter...
Get detailed performance information about an iteration. @param projectId The id of the project the iteration belongs to @param iterationId The id of the iteration to get @param getIterationPerformanceOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the IterationPerformance object
[ "Get", "detailed", "performance", "information", "about", "an", "iteration", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/TrainingsImpl.java#L1661-L1675
google/gson
codegen/src/main/java/com/google/gson/codegen/JavaWriter.java
JavaWriter.beginType
public void beginType(String type, String kind, int modifiers) throws IOException { beginType(type, kind, modifiers, null); }
java
public void beginType(String type, String kind, int modifiers) throws IOException { beginType(type, kind, modifiers, null); }
[ "public", "void", "beginType", "(", "String", "type", ",", "String", "kind", ",", "int", "modifiers", ")", "throws", "IOException", "{", "beginType", "(", "type", ",", "kind", ",", "modifiers", ",", "null", ")", ";", "}" ]
Emits a type declaration. @param kind such as "class", "interface" or "enum".
[ "Emits", "a", "type", "declaration", "." ]
train
https://github.com/google/gson/blob/63ee47cb642c8018e5cddd639aa2be143220ad4b/codegen/src/main/java/com/google/gson/codegen/JavaWriter.java#L134-L136
kuali/ojb-1.0.4
src/jdori/org/apache/ojb/jdori/sql/OjbExtent.java
OjbExtent.provideStateManagers
protected Collection provideStateManagers(Collection pojos) { PersistenceCapable pc; int [] fieldNums; Iterator iter = pojos.iterator(); Collection result = new ArrayList(); while (iter.hasNext()) { // obtain a StateManager pc = (PersistenceCapable) iter.next(); Identity oid = new Identity(pc, broker); StateManagerInternal smi = pmi.getStateManager(oid, pc.getClass()); // fetch attributes into StateManager JDOClass jdoClass = Helper.getJDOClass(pc.getClass()); fieldNums = jdoClass.getManagedFieldNumbers(); FieldManager fm = new OjbFieldManager(pc, broker); smi.replaceFields(fieldNums, fm); smi.retrieve(); // get JDO PersistencecCapable instance from SM and add it to result collection Object instance = smi.getObject(); result.add(instance); } return result; }
java
protected Collection provideStateManagers(Collection pojos) { PersistenceCapable pc; int [] fieldNums; Iterator iter = pojos.iterator(); Collection result = new ArrayList(); while (iter.hasNext()) { // obtain a StateManager pc = (PersistenceCapable) iter.next(); Identity oid = new Identity(pc, broker); StateManagerInternal smi = pmi.getStateManager(oid, pc.getClass()); // fetch attributes into StateManager JDOClass jdoClass = Helper.getJDOClass(pc.getClass()); fieldNums = jdoClass.getManagedFieldNumbers(); FieldManager fm = new OjbFieldManager(pc, broker); smi.replaceFields(fieldNums, fm); smi.retrieve(); // get JDO PersistencecCapable instance from SM and add it to result collection Object instance = smi.getObject(); result.add(instance); } return result; }
[ "protected", "Collection", "provideStateManagers", "(", "Collection", "pojos", ")", "{", "PersistenceCapable", "pc", ";", "int", "[", "]", "fieldNums", ";", "Iterator", "iter", "=", "pojos", ".", "iterator", "(", ")", ";", "Collection", "result", "=", "new", ...
This methods enhances the objects loaded by a broker query with a JDO StateManager an brings them under JDO control. @param pojos the OJB pojos as obtained by the broker @return the collection of JDO PersistenceCapable instances
[ "This", "methods", "enhances", "the", "objects", "loaded", "by", "a", "broker", "query", "with", "a", "JDO", "StateManager", "an", "brings", "them", "under", "JDO", "control", "." ]
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/jdori/org/apache/ojb/jdori/sql/OjbExtent.java#L120-L147
ZenHarbinger/l2fprod-properties-editor
src/main/java/com/l2fprod/common/swing/StatusBar.java
StatusBar.addZone
public void addZone(String id, Component zone, String constraints) { // is there already a zone with this id? Component previousZone = getZone(id); if (previousZone != null) { remove(previousZone); idToZones.remove(id); } if (zone instanceof JComponent) { JComponent jc = (JComponent) zone; if (jc.getBorder() == null || jc.getBorder() instanceof UIResource) { if (jc instanceof JLabel) { jc.setBorder( new CompoundBorder(zoneBorder, new EmptyBorder(0, 2, 0, 2))); ((JLabel) jc).setText(" "); } else { jc.setBorder(zoneBorder); } } } add(zone, constraints); idToZones.put(id, zone); }
java
public void addZone(String id, Component zone, String constraints) { // is there already a zone with this id? Component previousZone = getZone(id); if (previousZone != null) { remove(previousZone); idToZones.remove(id); } if (zone instanceof JComponent) { JComponent jc = (JComponent) zone; if (jc.getBorder() == null || jc.getBorder() instanceof UIResource) { if (jc instanceof JLabel) { jc.setBorder( new CompoundBorder(zoneBorder, new EmptyBorder(0, 2, 0, 2))); ((JLabel) jc).setText(" "); } else { jc.setBorder(zoneBorder); } } } add(zone, constraints); idToZones.put(id, zone); }
[ "public", "void", "addZone", "(", "String", "id", ",", "Component", "zone", ",", "String", "constraints", ")", "{", "// is there already a zone with this id?", "Component", "previousZone", "=", "getZone", "(", "id", ")", ";", "if", "(", "previousZone", "!=", "nu...
Adds a new zone in the StatusBar. @param id @param zone @param constraints one of the constraint support by the {@link com.l2fprod.common.swing.PercentLayout}
[ "Adds", "a", "new", "zone", "in", "the", "StatusBar", "." ]
train
https://github.com/ZenHarbinger/l2fprod-properties-editor/blob/d9b15c3f0b6ac1d9a2a9d315be073d2a4a419c32/src/main/java/com/l2fprod/common/swing/StatusBar.java#L67-L90
alkacon/opencms-core
src/org/opencms/ui/apps/CmsDefaultAppButtonProvider.java
CmsDefaultAppButtonProvider.createIconButton
public static Button createIconButton(String name, String description, Resource icon, String buttonStyle) { Button button = new Button(name); button.setIcon(icon, name); button.setDescription(description); button.addStyleName(OpenCmsTheme.APP_BUTTON); button.addStyleName(ValoTheme.BUTTON_BORDERLESS); button.addStyleName(ValoTheme.BUTTON_ICON_ALIGN_TOP); if (buttonStyle != null) { button.addStyleName(buttonStyle); } if ((icon instanceof CmsCssIcon) && ((CmsCssIcon)icon).hasAdditionalButtonStyle()) { button.addStyleName(((CmsCssIcon)icon).getAdditionalButtonStyle()); } return button; }
java
public static Button createIconButton(String name, String description, Resource icon, String buttonStyle) { Button button = new Button(name); button.setIcon(icon, name); button.setDescription(description); button.addStyleName(OpenCmsTheme.APP_BUTTON); button.addStyleName(ValoTheme.BUTTON_BORDERLESS); button.addStyleName(ValoTheme.BUTTON_ICON_ALIGN_TOP); if (buttonStyle != null) { button.addStyleName(buttonStyle); } if ((icon instanceof CmsCssIcon) && ((CmsCssIcon)icon).hasAdditionalButtonStyle()) { button.addStyleName(((CmsCssIcon)icon).getAdditionalButtonStyle()); } return button; }
[ "public", "static", "Button", "createIconButton", "(", "String", "name", ",", "String", "description", ",", "Resource", "icon", ",", "String", "buttonStyle", ")", "{", "Button", "button", "=", "new", "Button", "(", "name", ")", ";", "button", ".", "setIcon",...
Creates an icon button.<p> @param name the name @param description the description @param icon the icon @param buttonStyle the button style @return the created button
[ "Creates", "an", "icon", "button", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/apps/CmsDefaultAppButtonProvider.java#L210-L225
elki-project/elki
elki-timeseries/src/main/java/de/lmu/ifi/dbs/elki/algorithm/timeseries/OfflineChangePointDetectionAlgorithm.java
OfflineChangePointDetectionAlgorithm.run
public ChangePoints run(Relation<DoubleVector> relation) { if(!(relation.getDBIDs() instanceof ArrayDBIDs)) { throw new AbortException("This implementation may only be used on static databases, with ArrayDBIDs to provide a clear order."); } return new Instance(rnd.getSingleThreadedRandom()).run(relation); }
java
public ChangePoints run(Relation<DoubleVector> relation) { if(!(relation.getDBIDs() instanceof ArrayDBIDs)) { throw new AbortException("This implementation may only be used on static databases, with ArrayDBIDs to provide a clear order."); } return new Instance(rnd.getSingleThreadedRandom()).run(relation); }
[ "public", "ChangePoints", "run", "(", "Relation", "<", "DoubleVector", ">", "relation", ")", "{", "if", "(", "!", "(", "relation", ".", "getDBIDs", "(", ")", "instanceof", "ArrayDBIDs", ")", ")", "{", "throw", "new", "AbortException", "(", "\"This implementa...
Executes multiple change point detection for given relation @param relation the relation to process @return list with all the detected change point for every time series
[ "Executes", "multiple", "change", "point", "detection", "for", "given", "relation" ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-timeseries/src/main/java/de/lmu/ifi/dbs/elki/algorithm/timeseries/OfflineChangePointDetectionAlgorithm.java#L133-L138
liyiorg/weixin-popular
src/main/java/weixin/popular/api/ShakeAroundAPI.java
ShakeAroundAPI.pageUpdate
public static PageUpdateResult pageUpdate(String accessToken, PageUpdate pageUpdate) { return pageUpdate(accessToken, JsonUtil.toJSONString(pageUpdate)); }
java
public static PageUpdateResult pageUpdate(String accessToken, PageUpdate pageUpdate) { return pageUpdate(accessToken, JsonUtil.toJSONString(pageUpdate)); }
[ "public", "static", "PageUpdateResult", "pageUpdate", "(", "String", "accessToken", ",", "PageUpdate", "pageUpdate", ")", "{", "return", "pageUpdate", "(", "accessToken", ",", "JsonUtil", ".", "toJSONString", "(", "pageUpdate", ")", ")", ";", "}" ]
页面管理-编辑页面信息 @param accessToken accessToken @param pageUpdate pageUpdate @return result
[ "页面管理-编辑页面信息" ]
train
https://github.com/liyiorg/weixin-popular/blob/c64255292d41463bdb671938feaabf42a335d82c/src/main/java/weixin/popular/api/ShakeAroundAPI.java#L820-L823
haraldk/TwelveMonkeys
sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/ObjectReader.java
ObjectReader.buildWhereClause
private String buildWhereClause(String[] pKeys, Hashtable pMapping) { StringBuilder sqlBuf = new StringBuilder(); for (int i = 0; i < pKeys.length; i++) { String column = (String) pMapping.get(pKeys[i]); sqlBuf.append(" AND "); sqlBuf.append(column); sqlBuf.append(" = ?"); } return sqlBuf.toString(); }
java
private String buildWhereClause(String[] pKeys, Hashtable pMapping) { StringBuilder sqlBuf = new StringBuilder(); for (int i = 0; i < pKeys.length; i++) { String column = (String) pMapping.get(pKeys[i]); sqlBuf.append(" AND "); sqlBuf.append(column); sqlBuf.append(" = ?"); } return sqlBuf.toString(); }
[ "private", "String", "buildWhereClause", "(", "String", "[", "]", "pKeys", ",", "Hashtable", "pMapping", ")", "{", "StringBuilder", "sqlBuf", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "pKeys", ".", "le...
Builds extra SQL WHERE clause @param keys An array of ID names @param mapping The hashtable containing the object mapping @return A string containing valid SQL
[ "Builds", "extra", "SQL", "WHERE", "clause" ]
train
https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/ObjectReader.java#L524-L536
elki-project/elki
elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/linearalgebra/LinearEquationSystem.java
LinearEquationSystem.equationsToString
public String equationsToString(String prefix, int fractionDigits) { DecimalFormat nf = new DecimalFormat(); nf.setMinimumFractionDigits(fractionDigits); nf.setMaximumFractionDigits(fractionDigits); nf.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US)); nf.setNegativePrefix(""); nf.setPositivePrefix(""); return equationsToString(prefix, nf); }
java
public String equationsToString(String prefix, int fractionDigits) { DecimalFormat nf = new DecimalFormat(); nf.setMinimumFractionDigits(fractionDigits); nf.setMaximumFractionDigits(fractionDigits); nf.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US)); nf.setNegativePrefix(""); nf.setPositivePrefix(""); return equationsToString(prefix, nf); }
[ "public", "String", "equationsToString", "(", "String", "prefix", ",", "int", "fractionDigits", ")", "{", "DecimalFormat", "nf", "=", "new", "DecimalFormat", "(", ")", ";", "nf", ".", "setMinimumFractionDigits", "(", "fractionDigits", ")", ";", "nf", ".", "set...
Returns a string representation of this equation system. @param prefix the prefix of each line @param fractionDigits the number of fraction digits for output accuracy @return a string representation of this equation system
[ "Returns", "a", "string", "representation", "of", "this", "equation", "system", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/linearalgebra/LinearEquationSystem.java#L275-L283
ahome-it/lienzo-core
src/main/java/com/ait/lienzo/client/core/shape/Shape.java
Shape.setScale
@Override public T setScale(final double x, final double y) { getAttributes().setScale(x, y); return cast(); }
java
@Override public T setScale(final double x, final double y) { getAttributes().setScale(x, y); return cast(); }
[ "@", "Override", "public", "T", "setScale", "(", "final", "double", "x", ",", "final", "double", "y", ")", "{", "getAttributes", "(", ")", ".", "setScale", "(", "x", ",", "y", ")", ";", "return", "cast", "(", ")", ";", "}" ]
Sets this shape's scale, starting at the given x and y @param x @param y @return T
[ "Sets", "this", "shape", "s", "scale", "starting", "at", "the", "given", "x", "and", "y" ]
train
https://github.com/ahome-it/lienzo-core/blob/8e03723700dec366f77064d12fb8676d8cd6be99/src/main/java/com/ait/lienzo/client/core/shape/Shape.java#L1154-L1160
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/MessageFormat.java
MessageFormat.setFormatsByArgumentName
public void setFormatsByArgumentName(Map<String, Format> newFormats) { for (int partIndex = 0; (partIndex = nextTopLevelArgStart(partIndex)) >= 0;) { String key = getArgName(partIndex + 1); if (newFormats.containsKey(key)) { setCustomArgStartFormat(partIndex, newFormats.get(key)); } } }
java
public void setFormatsByArgumentName(Map<String, Format> newFormats) { for (int partIndex = 0; (partIndex = nextTopLevelArgStart(partIndex)) >= 0;) { String key = getArgName(partIndex + 1); if (newFormats.containsKey(key)) { setCustomArgStartFormat(partIndex, newFormats.get(key)); } } }
[ "public", "void", "setFormatsByArgumentName", "(", "Map", "<", "String", ",", "Format", ">", "newFormats", ")", "{", "for", "(", "int", "partIndex", "=", "0", ";", "(", "partIndex", "=", "nextTopLevelArgStart", "(", "partIndex", ")", ")", ">=", "0", ";", ...
<strong>[icu]</strong> Sets the Format objects to use for the values passed into <code>format</code> methods or returned from <code>parse</code> methods. The keys in <code>newFormats</code> are the argument names in the previously set pattern string, and the values are the formats. <p> Only argument names from the pattern string are considered. Extra keys in <code>newFormats</code> that do not correspond to an argument name are ignored. Similarly, if there is no format in newFormats for an argument name, the formatter for that argument remains unchanged. <p> This may be called on formats that do not use named arguments. In this case the map will be queried for key Strings that represent argument indices, e.g. "0", "1", "2" etc. @param newFormats a map from String to Format providing new formats for named arguments.
[ "<strong", ">", "[", "icu", "]", "<", "/", "strong", ">", "Sets", "the", "Format", "objects", "to", "use", "for", "the", "values", "passed", "into", "<code", ">", "format<", "/", "code", ">", "methods", "or", "returned", "from", "<code", ">", "parse<",...
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/MessageFormat.java#L614-L621
pravega/pravega
controller/src/main/java/io/pravega/controller/task/Stream/StreamMetadataTasks.java
StreamMetadataTasks.truncateStream
public CompletableFuture<UpdateStreamStatus.Status> truncateStream(final String scope, final String stream, final Map<Long, Long> streamCut, final OperationContext contextOpt) { final OperationContext context = contextOpt == null ? streamMetadataStore.createContext(scope, stream) : contextOpt; final long requestId = requestTracker.getRequestIdFor("truncateStream", scope, stream); // 1. get stream cut return startTruncation(scope, stream, streamCut, context, requestId) // 4. check for truncation to complete .thenCompose(truncationStarted -> { if (truncationStarted) { return checkDone(() -> isTruncated(scope, stream, streamCut, context), 1000L) .thenApply(y -> UpdateStreamStatus.Status.SUCCESS); } else { log.warn(requestId, "Unable to start truncation for {}/{}", scope, stream); return CompletableFuture.completedFuture(UpdateStreamStatus.Status.FAILURE); } }) .exceptionally(ex -> { log.warn(requestId, "Exception thrown in trying to update stream configuration {}", ex); return handleUpdateStreamError(ex, requestId); }); }
java
public CompletableFuture<UpdateStreamStatus.Status> truncateStream(final String scope, final String stream, final Map<Long, Long> streamCut, final OperationContext contextOpt) { final OperationContext context = contextOpt == null ? streamMetadataStore.createContext(scope, stream) : contextOpt; final long requestId = requestTracker.getRequestIdFor("truncateStream", scope, stream); // 1. get stream cut return startTruncation(scope, stream, streamCut, context, requestId) // 4. check for truncation to complete .thenCompose(truncationStarted -> { if (truncationStarted) { return checkDone(() -> isTruncated(scope, stream, streamCut, context), 1000L) .thenApply(y -> UpdateStreamStatus.Status.SUCCESS); } else { log.warn(requestId, "Unable to start truncation for {}/{}", scope, stream); return CompletableFuture.completedFuture(UpdateStreamStatus.Status.FAILURE); } }) .exceptionally(ex -> { log.warn(requestId, "Exception thrown in trying to update stream configuration {}", ex); return handleUpdateStreamError(ex, requestId); }); }
[ "public", "CompletableFuture", "<", "UpdateStreamStatus", ".", "Status", ">", "truncateStream", "(", "final", "String", "scope", ",", "final", "String", "stream", ",", "final", "Map", "<", "Long", ",", "Long", ">", "streamCut", ",", "final", "OperationContext", ...
Truncate a stream. @param scope scope. @param stream stream name. @param streamCut stream cut. @param contextOpt optional context @return update status.
[ "Truncate", "a", "stream", "." ]
train
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/controller/src/main/java/io/pravega/controller/task/Stream/StreamMetadataTasks.java#L364-L386
google/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/transformer/SerializerSwitcher.java
SerializerSwitcher.getOutputPropertyNoDefault
private static String getOutputPropertyNoDefault(String qnameString, Properties props) throws IllegalArgumentException { String value = (String)props.get(qnameString); return value; }
java
private static String getOutputPropertyNoDefault(String qnameString, Properties props) throws IllegalArgumentException { String value = (String)props.get(qnameString); return value; }
[ "private", "static", "String", "getOutputPropertyNoDefault", "(", "String", "qnameString", ",", "Properties", "props", ")", "throws", "IllegalArgumentException", "{", "String", "value", "=", "(", "String", ")", "props", ".", "get", "(", "qnameString", ")", ";", ...
Get the value of a property, without using the default properties. This can be used to test if a property has been explicitly set by the stylesheet or user. @param name The property name, which is a fully-qualified URI. @return The value of the property, or null if not found. @throws IllegalArgumentException If the property is not supported, and is not namespaced.
[ "Get", "the", "value", "of", "a", "property", "without", "using", "the", "default", "properties", ".", "This", "can", "be", "used", "to", "test", "if", "a", "property", "has", "been", "explicitly", "set", "by", "the", "stylesheet", "or", "user", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/transformer/SerializerSwitcher.java#L131-L137
xcesco/kripton
kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/SqlBuilderHelper.java
SqlBuilderHelper.generateLogForSQL
static void generateLogForSQL(SQLiteModelMethod method, MethodSpec.Builder methodBuilder) { // manage log if (method.getParent().getParent().generateLog) { methodBuilder.addCode("\n// manage log\n"); methodBuilder.addStatement("$T.info(_sql)", Logger.class); } }
java
static void generateLogForSQL(SQLiteModelMethod method, MethodSpec.Builder methodBuilder) { // manage log if (method.getParent().getParent().generateLog) { methodBuilder.addCode("\n// manage log\n"); methodBuilder.addStatement("$T.info(_sql)", Logger.class); } }
[ "static", "void", "generateLogForSQL", "(", "SQLiteModelMethod", "method", ",", "MethodSpec", ".", "Builder", "methodBuilder", ")", "{", "// manage log", "if", "(", "method", ".", "getParent", "(", ")", ".", "getParent", "(", ")", ".", "generateLog", ")", "{",...
<p> Generate log for where conditions. </p> <h2>pre conditions</h2> <p> required variable are: </p> <ul> <li>_sqlBuilder</li> <li>_projectionBuffer</li> * </ul> <h2>post conditions</h2> <p> created variables are:</li> <ul> <li>_sql</li> </ul> @param method the method @param methodBuilder the method builder
[ "<p", ">", "Generate", "log", "for", "where", "conditions", ".", "<", "/", "p", ">" ]
train
https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/SqlBuilderHelper.java#L313-L319
google/closure-templates
java/src/com/google/template/soy/data/SanitizedContents.java
SanitizedContents.constantJs
public static SanitizedContent constantJs(@CompileTimeConstant final String constant) { return fromConstant(constant, ContentKind.JS, Dir.LTR); }
java
public static SanitizedContent constantJs(@CompileTimeConstant final String constant) { return fromConstant(constant, ContentKind.JS, Dir.LTR); }
[ "public", "static", "SanitizedContent", "constantJs", "(", "@", "CompileTimeConstant", "final", "String", "constant", ")", "{", "return", "fromConstant", "(", "constant", ",", "ContentKind", ".", "JS", ",", "Dir", ".", "LTR", ")", ";", "}" ]
Wraps an assumed-safe JS constant. <p>This only accepts compile-time constants, based on the assumption that scripts that are controlled by the application (and not user input) are considered safe.
[ "Wraps", "an", "assumed", "-", "safe", "JS", "constant", "." ]
train
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/data/SanitizedContents.java#L228-L230
gmessner/gitlab4j-api
src/main/java/org/gitlab4j/api/LabelsApi.java
LabelsApi.createLabel
public Label createLabel(Object projectIdOrPath, String name, String color, String description, Integer priority) throws GitLabApiException { GitLabApiForm formData = new GitLabApiForm() .withParam("name", name, true) .withParam("color", color, true) .withParam("description", description) .withParam("priority", priority); Response response = post(Response.Status.CREATED, formData, "projects", getProjectIdOrPath(projectIdOrPath), "labels"); return (response.readEntity(Label.class)); }
java
public Label createLabel(Object projectIdOrPath, String name, String color, String description, Integer priority) throws GitLabApiException { GitLabApiForm formData = new GitLabApiForm() .withParam("name", name, true) .withParam("color", color, true) .withParam("description", description) .withParam("priority", priority); Response response = post(Response.Status.CREATED, formData, "projects", getProjectIdOrPath(projectIdOrPath), "labels"); return (response.readEntity(Label.class)); }
[ "public", "Label", "createLabel", "(", "Object", "projectIdOrPath", ",", "String", "name", ",", "String", "color", ",", "String", "description", ",", "Integer", "priority", ")", "throws", "GitLabApiException", "{", "GitLabApiForm", "formData", "=", "new", "GitLabA...
Create a label @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance @param name the name for the label @param color the color for the label @param description the description for the label @param priority the priority for the label @return the created Label instance @throws GitLabApiException if any exception occurs
[ "Create", "a", "label" ]
train
https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/LabelsApi.java#L119-L128
MenoData/Time4J
base/src/main/java/net/time4j/history/ChronoHistory.java
ChronoHistory.with
public ChronoHistory with(AncientJulianLeapYears ancientJulianLeapYears) { if (ancientJulianLeapYears == null) { throw new NullPointerException("Missing ancient julian leap years."); } else if (!this.hasGregorianCutOverDate()) { return this; } return new ChronoHistory(this.variant, this.events, ancientJulianLeapYears, this.nys, this.eraPreference); }
java
public ChronoHistory with(AncientJulianLeapYears ancientJulianLeapYears) { if (ancientJulianLeapYears == null) { throw new NullPointerException("Missing ancient julian leap years."); } else if (!this.hasGregorianCutOverDate()) { return this; } return new ChronoHistory(this.variant, this.events, ancientJulianLeapYears, this.nys, this.eraPreference); }
[ "public", "ChronoHistory", "with", "(", "AncientJulianLeapYears", "ancientJulianLeapYears", ")", "{", "if", "(", "ancientJulianLeapYears", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"Missing ancient julian leap years.\"", ")", ";", "}", "else...
/*[deutsch] <p>Erzeugt eine Kopie dieser Instanz mit den angegebenen historischen julianischen Schaltjahren. </p> <p>Diese Methode hat keine Auswirkung, wenn angewandt auf {@code ChronoHistory.PROLEPTIC_GREGORIAN} oder {@code ChronoHistory.PROLEPTIC_JULIAN} oder {@code ChronoHistory.PROLEPTIC_BYZANTINE}. </p> @param ancientJulianLeapYears sequence of historic julian leap years @return new history which starts at first of January in year BC 45 @since 3.11/4.8
[ "/", "*", "[", "deutsch", "]", "<p", ">", "Erzeugt", "eine", "Kopie", "dieser", "Instanz", "mit", "den", "angegebenen", "historischen", "julianischen", "Schaltjahren", ".", "<", "/", "p", ">" ]
train
https://github.com/MenoData/Time4J/blob/08b2eda6b2dbb140b92011cf7071bb087edd46a5/base/src/main/java/net/time4j/history/ChronoHistory.java#L1299-L1309
zaproxy/zaproxy
src/org/zaproxy/zap/extension/spider/SpiderThread.java
SpiderThread.addMessageToSitesTree
private void addMessageToSitesTree(final HistoryReference historyReference, final HttpMessage message) { if (View.isInitialised() && !EventQueue.isDispatchThread()) { EventQueue.invokeLater(new Runnable() { @Override public void run() { addMessageToSitesTree(historyReference, message); } }); return; } StructuralNode node = SessionStructure.addPath( Model.getSingleton().getSession(), historyReference, message, true); if (node != null) { try { addUriToAddedNodesModel(SessionStructure.getNodeName(message), message.getRequestHeader().getMethod(), ""); } catch (URIException e) { log.error("Error while adding node to added nodes model: " + e.getMessage(), e); } } }
java
private void addMessageToSitesTree(final HistoryReference historyReference, final HttpMessage message) { if (View.isInitialised() && !EventQueue.isDispatchThread()) { EventQueue.invokeLater(new Runnable() { @Override public void run() { addMessageToSitesTree(historyReference, message); } }); return; } StructuralNode node = SessionStructure.addPath( Model.getSingleton().getSession(), historyReference, message, true); if (node != null) { try { addUriToAddedNodesModel(SessionStructure.getNodeName(message), message.getRequestHeader().getMethod(), ""); } catch (URIException e) { log.error("Error while adding node to added nodes model: " + e.getMessage(), e); } } }
[ "private", "void", "addMessageToSitesTree", "(", "final", "HistoryReference", "historyReference", ",", "final", "HttpMessage", "message", ")", "{", "if", "(", "View", ".", "isInitialised", "(", ")", "&&", "!", "EventQueue", ".", "isDispatchThread", "(", ")", ")"...
Adds the given message to the sites tree. @param historyReference the history reference of the message, must not be {@code null} @param message the actual message, must not be {@code null}
[ "Adds", "the", "given", "message", "to", "the", "sites", "tree", "." ]
train
https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/extension/spider/SpiderThread.java#L504-L526
matomo-org/piwik-java-tracker
src/main/java/org/piwik/java/tracking/PiwikRequest.java
PiwikRequest.setNonEmptyStringParameter
private void setNonEmptyStringParameter(String key, String value){ if (value == null){ parameters.remove(key); } else if (value.length() == 0){ throw new IllegalArgumentException("Value cannot be empty."); } else{ parameters.put(key, value); } }
java
private void setNonEmptyStringParameter(String key, String value){ if (value == null){ parameters.remove(key); } else if (value.length() == 0){ throw new IllegalArgumentException("Value cannot be empty."); } else{ parameters.put(key, value); } }
[ "private", "void", "setNonEmptyStringParameter", "(", "String", "key", ",", "String", "value", ")", "{", "if", "(", "value", "==", "null", ")", "{", "parameters", ".", "remove", "(", "key", ")", ";", "}", "else", "if", "(", "value", ".", "length", "(",...
Set a stored parameter and verify it is a non-empty string. @param key the parameter's key @param value the parameter's value. Cannot be the empty. Removes the parameter if null string
[ "Set", "a", "stored", "parameter", "and", "verify", "it", "is", "a", "non", "-", "empty", "string", "." ]
train
https://github.com/matomo-org/piwik-java-tracker/blob/23df71d27a89e89dc7a539b2eda88c90a206458b/src/main/java/org/piwik/java/tracking/PiwikRequest.java#L1781-L1791
jmeetsma/Iglu-Http
src/main/java/org/ijsberg/iglu/util/http/ServletSupport.java
ServletSupport.forward
public static void forward(String url, ServletRequest req, ServletResponse res) throws ServletException, IOException { RequestDispatcher dispatch = req.getRequestDispatcher(url); System.out.println(new LogEntry("about to forward to " + url)); dispatch.forward(req, res); }
java
public static void forward(String url, ServletRequest req, ServletResponse res) throws ServletException, IOException { RequestDispatcher dispatch = req.getRequestDispatcher(url); System.out.println(new LogEntry("about to forward to " + url)); dispatch.forward(req, res); }
[ "public", "static", "void", "forward", "(", "String", "url", ",", "ServletRequest", "req", ",", "ServletResponse", "res", ")", "throws", "ServletException", ",", "IOException", "{", "RequestDispatcher", "dispatch", "=", "req", ".", "getRequestDispatcher", "(", "ur...
Dispatches http-request to url @param url @throws ServletException to abort request handling
[ "Dispatches", "http", "-", "request", "to", "url" ]
train
https://github.com/jmeetsma/Iglu-Http/blob/5b5ed3b417285dc79b7aa013bf2340bb5ba1ffbe/src/main/java/org/ijsberg/iglu/util/http/ServletSupport.java#L472-L477
rundeck/rundeck
core/src/main/java/com/dtolabs/rundeck/core/execution/impl/jsch/NodeSSHConnectionInfo.java
NodeSSHConnectionInfo.resolveLongFwk
private long resolveLongFwk(final String key, final String frameworkProp, final long defval) { long timeout = defval; String opt = resolve(key); if (opt == null && frameworkProp != null && framework.getPropertyLookup().hasProperty(frameworkProp)) { opt = framework.getProperty(frameworkProp); } if (opt != null) { try { timeout = Long.parseLong(opt); } catch (NumberFormatException ignored) { } } return timeout; }
java
private long resolveLongFwk(final String key, final String frameworkProp, final long defval) { long timeout = defval; String opt = resolve(key); if (opt == null && frameworkProp != null && framework.getPropertyLookup().hasProperty(frameworkProp)) { opt = framework.getProperty(frameworkProp); } if (opt != null) { try { timeout = Long.parseLong(opt); } catch (NumberFormatException ignored) { } } return timeout; }
[ "private", "long", "resolveLongFwk", "(", "final", "String", "key", ",", "final", "String", "frameworkProp", ",", "final", "long", "defval", ")", "{", "long", "timeout", "=", "defval", ";", "String", "opt", "=", "resolve", "(", "key", ")", ";", "if", "("...
Look for a node/project/framework config property of the given key, and if not found fallback to a framework property, return parsed long or the default @param key key for node attribute/project/framework property @param frameworkProp fallback framework property @param defval default value @return parsed value or default
[ "Look", "for", "a", "node", "/", "project", "/", "framework", "config", "property", "of", "the", "given", "key", "and", "if", "not", "found", "fallback", "to", "a", "framework", "property", "return", "parsed", "long", "or", "the", "default" ]
train
https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/execution/impl/jsch/NodeSSHConnectionInfo.java#L252-L265
abel533/Mapper
core/src/main/java/tk/mybatis/mapper/mapperhelper/SqlHelper.java
SqlHelper.updateTable
public static String updateTable(Class<?> entityClass, String defaultTableName, String entityName) { StringBuilder sql = new StringBuilder(); sql.append("UPDATE "); sql.append(getDynamicTableName(entityClass, defaultTableName, entityName)); sql.append(" "); return sql.toString(); }
java
public static String updateTable(Class<?> entityClass, String defaultTableName, String entityName) { StringBuilder sql = new StringBuilder(); sql.append("UPDATE "); sql.append(getDynamicTableName(entityClass, defaultTableName, entityName)); sql.append(" "); return sql.toString(); }
[ "public", "static", "String", "updateTable", "(", "Class", "<", "?", ">", "entityClass", ",", "String", "defaultTableName", ",", "String", "entityName", ")", "{", "StringBuilder", "sql", "=", "new", "StringBuilder", "(", ")", ";", "sql", ".", "append", "(", ...
update tableName - 动态表名 @param entityClass @param defaultTableName 默认表名 @param entityName 别名 @return
[ "update", "tableName", "-", "动态表名" ]
train
https://github.com/abel533/Mapper/blob/45c3d716583cba3680e03f1f6790fab5e1f4f668/core/src/main/java/tk/mybatis/mapper/mapperhelper/SqlHelper.java#L339-L345
alexa/alexa-skills-kit-sdk-for-java
ask-sdk-servlet-support/src/com/amazon/ask/servlet/SkillServlet.java
SkillServlet.doPost
@Override protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws IOException { byte[] serializedRequestEnvelope = IOUtils.toByteArray(request.getInputStream()); try { final RequestEnvelope deserializedRequestEnvelope = serializer.deserialize(IOUtils.toString( serializedRequestEnvelope, ServletConstants.CHARACTER_ENCODING), RequestEnvelope.class); // Verify the authenticity of the request by executing configured verifiers. for (SkillServletVerifier verifier : verifiers) { verifier.verify(request, serializedRequestEnvelope, deserializedRequestEnvelope); } ResponseEnvelope skillResponse = skill.invoke(deserializedRequestEnvelope); // Generate JSON and send back the response response.setContentType("application/json"); response.setStatus(HttpServletResponse.SC_OK); if (skillResponse != null) { byte[] serializedResponse = serializer.serialize(skillResponse).getBytes(StandardCharsets.UTF_8); try (final OutputStream out = response.getOutputStream()) { response.setContentLength(serializedResponse.length); out.write(serializedResponse); } } } catch (SecurityException ex) { int statusCode = HttpServletResponse.SC_BAD_REQUEST; log.error("Incoming request failed verification {}", statusCode, ex); response.sendError(statusCode, ex.getMessage()); } catch (AskSdkException ex) { int statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; log.error("Exception occurred in doPost, returning status code {}", statusCode, ex); response.sendError(statusCode, ex.getMessage()); } }
java
@Override protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws IOException { byte[] serializedRequestEnvelope = IOUtils.toByteArray(request.getInputStream()); try { final RequestEnvelope deserializedRequestEnvelope = serializer.deserialize(IOUtils.toString( serializedRequestEnvelope, ServletConstants.CHARACTER_ENCODING), RequestEnvelope.class); // Verify the authenticity of the request by executing configured verifiers. for (SkillServletVerifier verifier : verifiers) { verifier.verify(request, serializedRequestEnvelope, deserializedRequestEnvelope); } ResponseEnvelope skillResponse = skill.invoke(deserializedRequestEnvelope); // Generate JSON and send back the response response.setContentType("application/json"); response.setStatus(HttpServletResponse.SC_OK); if (skillResponse != null) { byte[] serializedResponse = serializer.serialize(skillResponse).getBytes(StandardCharsets.UTF_8); try (final OutputStream out = response.getOutputStream()) { response.setContentLength(serializedResponse.length); out.write(serializedResponse); } } } catch (SecurityException ex) { int statusCode = HttpServletResponse.SC_BAD_REQUEST; log.error("Incoming request failed verification {}", statusCode, ex); response.sendError(statusCode, ex.getMessage()); } catch (AskSdkException ex) { int statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; log.error("Exception occurred in doPost, returning status code {}", statusCode, ex); response.sendError(statusCode, ex.getMessage()); } }
[ "@", "Override", "protected", "void", "doPost", "(", "final", "HttpServletRequest", "request", ",", "final", "HttpServletResponse", "response", ")", "throws", "IOException", "{", "byte", "[", "]", "serializedRequestEnvelope", "=", "IOUtils", ".", "toByteArray", "(",...
Handles a POST request. Based on the request parameters, invokes the right method on the {@code Skill}. @param request the object that contains the request the client has made of the servlet @param response object that contains the response the servlet sends to the client @throws IOException if an input or output error is detected when the servlet handles the request
[ "Handles", "a", "POST", "request", ".", "Based", "on", "the", "request", "parameters", "invokes", "the", "right", "method", "on", "the", "{", "@code", "Skill", "}", "." ]
train
https://github.com/alexa/alexa-skills-kit-sdk-for-java/blob/c49194da0693898c70f3f2c4a372f5a12da04e3e/ask-sdk-servlet-support/src/com/amazon/ask/servlet/SkillServlet.java#L92-L125
astefanutti/camel-cdi
maven/src/main/java/org/apache/camel/maven/RunMojo.java
RunMojo.addRelevantPluginDependenciesToClasspath
private void addRelevantPluginDependenciesToClasspath(Set<URL> path) throws MojoExecutionException { if (hasCommandlineArgs()) { arguments = parseCommandlineArgs(); } try { Iterator<Artifact> iter = this.determineRelevantPluginDependencies().iterator(); while (iter.hasNext()) { Artifact classPathElement = iter.next(); // we must skip org.osgi.core, otherwise we get a // java.lang.NoClassDefFoundError: org.osgi.vendor.framework property not set if (classPathElement.getArtifactId().equals("org.osgi.core")) { getLog().debug("Skipping org.osgi.core -> " + classPathElement.getGroupId() + "/" + classPathElement.getArtifactId() + "/" + classPathElement.getVersion()); continue; } getLog().debug("Adding plugin dependency artifact: " + classPathElement.getArtifactId() + " to classpath"); path.add(classPathElement.getFile().toURI().toURL()); } } catch (MalformedURLException e) { throw new MojoExecutionException("Error during setting up classpath", e); } }
java
private void addRelevantPluginDependenciesToClasspath(Set<URL> path) throws MojoExecutionException { if (hasCommandlineArgs()) { arguments = parseCommandlineArgs(); } try { Iterator<Artifact> iter = this.determineRelevantPluginDependencies().iterator(); while (iter.hasNext()) { Artifact classPathElement = iter.next(); // we must skip org.osgi.core, otherwise we get a // java.lang.NoClassDefFoundError: org.osgi.vendor.framework property not set if (classPathElement.getArtifactId().equals("org.osgi.core")) { getLog().debug("Skipping org.osgi.core -> " + classPathElement.getGroupId() + "/" + classPathElement.getArtifactId() + "/" + classPathElement.getVersion()); continue; } getLog().debug("Adding plugin dependency artifact: " + classPathElement.getArtifactId() + " to classpath"); path.add(classPathElement.getFile().toURI().toURL()); } } catch (MalformedURLException e) { throw new MojoExecutionException("Error during setting up classpath", e); } }
[ "private", "void", "addRelevantPluginDependenciesToClasspath", "(", "Set", "<", "URL", ">", "path", ")", "throws", "MojoExecutionException", "{", "if", "(", "hasCommandlineArgs", "(", ")", ")", "{", "arguments", "=", "parseCommandlineArgs", "(", ")", ";", "}", "...
Add any relevant project dependencies to the classpath. Indirectly takes includePluginDependencies and ExecutableDependency into consideration. @param path classpath of {@link java.net.URL} objects @throws MojoExecutionException
[ "Add", "any", "relevant", "project", "dependencies", "to", "the", "classpath", ".", "Indirectly", "takes", "includePluginDependencies", "and", "ExecutableDependency", "into", "consideration", "." ]
train
https://github.com/astefanutti/camel-cdi/blob/686c7f5fe3a706f47378e0c49c323040795ddff8/maven/src/main/java/org/apache/camel/maven/RunMojo.java#L735-L760
OpenLiberty/open-liberty
dev/com.ibm.ws.channel.ssl/src/com/ibm/ws/channel/ssl/internal/SSLAlpnNegotiator.java
SSLAlpnNegotiator.tryToRemoveAlpnNegotiator
protected void tryToRemoveAlpnNegotiator(ThirdPartyAlpnNegotiator negotiator, SSLEngine engine, SSLConnectionLink link) { // the Java 9 and IBM JSSE ALPN implementations don't use a negotiator object if (negotiator == null && isNativeAlpnActive()) { getNativeAlpnChoice(engine, link); } else if (negotiator == null && isIbmAlpnActive()) { getAndRemoveIbmAlpnChoice(engine, link); } else if (negotiator != null && isJettyAlpnActive() && negotiator instanceof JettyServerNegotiator) { ((JettyServerNegotiator) negotiator).removeEngine(); } else if (negotiator != null && isGrizzlyAlpnActive() && negotiator instanceof GrizzlyAlpnNegotiator) { ((GrizzlyAlpnNegotiator) negotiator).removeServerNegotiatorEngine(); } }
java
protected void tryToRemoveAlpnNegotiator(ThirdPartyAlpnNegotiator negotiator, SSLEngine engine, SSLConnectionLink link) { // the Java 9 and IBM JSSE ALPN implementations don't use a negotiator object if (negotiator == null && isNativeAlpnActive()) { getNativeAlpnChoice(engine, link); } else if (negotiator == null && isIbmAlpnActive()) { getAndRemoveIbmAlpnChoice(engine, link); } else if (negotiator != null && isJettyAlpnActive() && negotiator instanceof JettyServerNegotiator) { ((JettyServerNegotiator) negotiator).removeEngine(); } else if (negotiator != null && isGrizzlyAlpnActive() && negotiator instanceof GrizzlyAlpnNegotiator) { ((GrizzlyAlpnNegotiator) negotiator).removeServerNegotiatorEngine(); } }
[ "protected", "void", "tryToRemoveAlpnNegotiator", "(", "ThirdPartyAlpnNegotiator", "negotiator", ",", "SSLEngine", "engine", ",", "SSLConnectionLink", "link", ")", "{", "// the Java 9 and IBM JSSE ALPN implementations don't use a negotiator object", "if", "(", "negotiator", "==",...
If ALPN is active, try to remove the ThirdPartyAlpnNegotiator from the map of active negotiators @param ThirdPartyAlpnNegotiator @param SSLEngine @param SSLConnectionLink
[ "If", "ALPN", "is", "active", "try", "to", "remove", "the", "ThirdPartyAlpnNegotiator", "from", "the", "map", "of", "active", "negotiators" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.channel.ssl/src/com/ibm/ws/channel/ssl/internal/SSLAlpnNegotiator.java#L224-L235
apereo/cas
core/cas-server-core-authentication-mfa-api/src/main/java/org/apereo/cas/authentication/MultifactorAuthenticationUtils.java
MultifactorAuthenticationUtils.resolveProvider
public static Optional<MultifactorAuthenticationProvider> resolveProvider(final Map<String, MultifactorAuthenticationProvider> providers, final String requestMfaMethod) { return resolveProvider(providers, Stream.of(requestMfaMethod).collect(Collectors.toList())); }
java
public static Optional<MultifactorAuthenticationProvider> resolveProvider(final Map<String, MultifactorAuthenticationProvider> providers, final String requestMfaMethod) { return resolveProvider(providers, Stream.of(requestMfaMethod).collect(Collectors.toList())); }
[ "public", "static", "Optional", "<", "MultifactorAuthenticationProvider", ">", "resolveProvider", "(", "final", "Map", "<", "String", ",", "MultifactorAuthenticationProvider", ">", "providers", ",", "final", "String", "requestMfaMethod", ")", "{", "return", "resolveProv...
Resolve provider optional. @param providers the providers @param requestMfaMethod the request mfa method @return the optional
[ "Resolve", "provider", "optional", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/core/cas-server-core-authentication-mfa-api/src/main/java/org/apereo/cas/authentication/MultifactorAuthenticationUtils.java#L139-L142
Erudika/para
para-server/src/main/java/com/erudika/para/utils/GZipResponseUtil.java
GZipResponseUtil.shouldBodyBeZero
public static boolean shouldBodyBeZero(HttpServletRequest request, int responseStatus) { //Check for NO_CONTENT if (responseStatus == HttpServletResponse.SC_NO_CONTENT) { if (log.isDebugEnabled()) { log.debug("{} resulted in a {} response. Removing message body in accordance with RFC2616.", request.getRequestURL(), HttpServletResponse.SC_NO_CONTENT); } return true; } //Check for NOT_MODIFIED if (responseStatus == HttpServletResponse.SC_NOT_MODIFIED) { if (log.isDebugEnabled()) { log.debug("{} resulted in a {} response. Removing message body in accordance with RFC2616.", request.getRequestURL(), HttpServletResponse.SC_NOT_MODIFIED); } return true; } return false; }
java
public static boolean shouldBodyBeZero(HttpServletRequest request, int responseStatus) { //Check for NO_CONTENT if (responseStatus == HttpServletResponse.SC_NO_CONTENT) { if (log.isDebugEnabled()) { log.debug("{} resulted in a {} response. Removing message body in accordance with RFC2616.", request.getRequestURL(), HttpServletResponse.SC_NO_CONTENT); } return true; } //Check for NOT_MODIFIED if (responseStatus == HttpServletResponse.SC_NOT_MODIFIED) { if (log.isDebugEnabled()) { log.debug("{} resulted in a {} response. Removing message body in accordance with RFC2616.", request.getRequestURL(), HttpServletResponse.SC_NOT_MODIFIED); } return true; } return false; }
[ "public", "static", "boolean", "shouldBodyBeZero", "(", "HttpServletRequest", "request", ",", "int", "responseStatus", ")", "{", "//Check for NO_CONTENT", "if", "(", "responseStatus", "==", "HttpServletResponse", ".", "SC_NO_CONTENT", ")", "{", "if", "(", "log", "."...
Performs a number of checks to ensure response saneness according to the rules of RFC2616: <ol> <li>If the response code is {@link javax.servlet.http.HttpServletResponse#SC_NO_CONTENT} then it is illegal for the body to contain anything. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.5 <li>If the response code is {@link javax.servlet.http.HttpServletResponse#SC_NOT_MODIFIED} then it is illegal for the body to contain anything. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5 </ol> @param request the client HTTP request @param responseStatus the responseStatus @return true if the response should be 0, even if it is isn't.
[ "Performs", "a", "number", "of", "checks", "to", "ensure", "response", "saneness", "according", "to", "the", "rules", "of", "RFC2616", ":", "<ol", ">", "<li", ">", "If", "the", "response", "code", "is", "{" ]
train
https://github.com/Erudika/para/blob/5ba096c477042ea7b18e9a0e8b5b1ee0f5bd6ce9/para-server/src/main/java/com/erudika/para/utils/GZipResponseUtil.java#L81-L101
apereo/cas
core/cas-server-core-util-api/src/main/java/org/apereo/cas/util/EncodingUtils.java
EncodingUtils.encryptValueAsJwtDirectAes128Sha256
public static String encryptValueAsJwtDirectAes128Sha256(final Key key, final Serializable value) { return encryptValueAsJwt(key, value, KeyManagementAlgorithmIdentifiers.DIRECT, CipherExecutor.DEFAULT_CONTENT_ENCRYPTION_ALGORITHM); }
java
public static String encryptValueAsJwtDirectAes128Sha256(final Key key, final Serializable value) { return encryptValueAsJwt(key, value, KeyManagementAlgorithmIdentifiers.DIRECT, CipherExecutor.DEFAULT_CONTENT_ENCRYPTION_ALGORITHM); }
[ "public", "static", "String", "encryptValueAsJwtDirectAes128Sha256", "(", "final", "Key", "key", ",", "final", "Serializable", "value", ")", "{", "return", "encryptValueAsJwt", "(", "key", ",", "value", ",", "KeyManagementAlgorithmIdentifiers", ".", "DIRECT", ",", "...
Encrypt value as jwt with direct algorithm and encryption content alg aes-128-sha-256. @param key the key @param value the value @return the string
[ "Encrypt", "value", "as", "jwt", "with", "direct", "algorithm", "and", "encryption", "content", "alg", "aes", "-", "128", "-", "sha", "-", "256", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/core/cas-server-core-util-api/src/main/java/org/apereo/cas/util/EncodingUtils.java#L378-L381
alipay/sofa-rpc
core/api/src/main/java/com/alipay/sofa/rpc/transport/ClientTransportFactory.java
ClientTransportFactory.getReverseClientTransport
public static ClientTransport getReverseClientTransport(String container, AbstractChannel channel) { if (REVERSE_CLIENT_TRANSPORT_MAP == null) { // 初始化 synchronized (ClientTransportFactory.class) { if (REVERSE_CLIENT_TRANSPORT_MAP == null) { REVERSE_CLIENT_TRANSPORT_MAP = new ConcurrentHashMap<String, ClientTransport>(); } } } String key = NetUtils.channelToString(channel.remoteAddress(), channel.localAddress()); ClientTransport transport = REVERSE_CLIENT_TRANSPORT_MAP.get(key); if (transport == null) { synchronized (ClientTransportFactory.class) { transport = REVERSE_CLIENT_TRANSPORT_MAP.get(key); if (transport == null) { ClientTransportConfig config = new ClientTransportConfig() .setProviderInfo(new ProviderInfo().setHost(channel.remoteAddress().getHostName()) .setPort(channel.remoteAddress().getPort())) .setContainer(container); transport = ExtensionLoaderFactory.getExtensionLoader(ClientTransport.class) .getExtension(config.getContainer(), new Class[] { ClientTransportConfig.class }, new Object[] { config }); transport.setChannel(channel); REVERSE_CLIENT_TRANSPORT_MAP.put(key, transport); // 保存唯一长连接 } } } return transport; }
java
public static ClientTransport getReverseClientTransport(String container, AbstractChannel channel) { if (REVERSE_CLIENT_TRANSPORT_MAP == null) { // 初始化 synchronized (ClientTransportFactory.class) { if (REVERSE_CLIENT_TRANSPORT_MAP == null) { REVERSE_CLIENT_TRANSPORT_MAP = new ConcurrentHashMap<String, ClientTransport>(); } } } String key = NetUtils.channelToString(channel.remoteAddress(), channel.localAddress()); ClientTransport transport = REVERSE_CLIENT_TRANSPORT_MAP.get(key); if (transport == null) { synchronized (ClientTransportFactory.class) { transport = REVERSE_CLIENT_TRANSPORT_MAP.get(key); if (transport == null) { ClientTransportConfig config = new ClientTransportConfig() .setProviderInfo(new ProviderInfo().setHost(channel.remoteAddress().getHostName()) .setPort(channel.remoteAddress().getPort())) .setContainer(container); transport = ExtensionLoaderFactory.getExtensionLoader(ClientTransport.class) .getExtension(config.getContainer(), new Class[] { ClientTransportConfig.class }, new Object[] { config }); transport.setChannel(channel); REVERSE_CLIENT_TRANSPORT_MAP.put(key, transport); // 保存唯一长连接 } } } return transport; }
[ "public", "static", "ClientTransport", "getReverseClientTransport", "(", "String", "container", ",", "AbstractChannel", "channel", ")", "{", "if", "(", "REVERSE_CLIENT_TRANSPORT_MAP", "==", "null", ")", "{", "// 初始化", "synchronized", "(", "ClientTransportFactory", ".", ...
构建反向的(服务端到客户端)虚拟长连接 @param container Container of client transport @param channel Exists channel from client @return reverse client transport of exists channel
[ "构建反向的(服务端到客户端)虚拟长连接" ]
train
https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/core/api/src/main/java/com/alipay/sofa/rpc/transport/ClientTransportFactory.java#L135-L163
OpenLiberty/open-liberty
dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/DCacheBase.java
DCacheBase.setValue
public void setValue(EntryInfo entryInfo, Object value) { setValue(entryInfo, value, !shouldPull(entryInfo.getSharingPolicy(), entryInfo.id), DynaCacheConstants.VBC_CACHE_NEW_CONTENT); }
java
public void setValue(EntryInfo entryInfo, Object value) { setValue(entryInfo, value, !shouldPull(entryInfo.getSharingPolicy(), entryInfo.id), DynaCacheConstants.VBC_CACHE_NEW_CONTENT); }
[ "public", "void", "setValue", "(", "EntryInfo", "entryInfo", ",", "Object", "value", ")", "{", "setValue", "(", "entryInfo", ",", "value", ",", "!", "shouldPull", "(", "entryInfo", ".", "getSharingPolicy", "(", ")", ",", "entryInfo", ".", "id", ")", ",", ...
This sets the actual value (JSP or command) of an entry in the cache. @param entryInfo The cache entry @param value The value to cache in the entry
[ "This", "sets", "the", "actual", "value", "(", "JSP", "or", "command", ")", "of", "an", "entry", "in", "the", "cache", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/DCacheBase.java#L521-L523
lucee/Lucee
core/src/main/java/lucee/runtime/config/XMLConfigAdmin.java
XMLConfigAdmin.updateJDBCDriver
public void updateJDBCDriver(String label, String id, ClassDefinition cd) throws PageException { checkWriteAccess(); _updateJDBCDriver(label, id, cd); }
java
public void updateJDBCDriver(String label, String id, ClassDefinition cd) throws PageException { checkWriteAccess(); _updateJDBCDriver(label, id, cd); }
[ "public", "void", "updateJDBCDriver", "(", "String", "label", ",", "String", "id", ",", "ClassDefinition", "cd", ")", "throws", "PageException", "{", "checkWriteAccess", "(", ")", ";", "_updateJDBCDriver", "(", "label", ",", "id", ",", "cd", ")", ";", "}" ]
/* public static void updateJDBCDriver(ConfigImpl config, String label, ClassDefinition cd, boolean reload) throws IOException, SAXException, PageException, BundleException { ConfigWebAdmin admin = new ConfigWebAdmin(config, null); admin._updateJDBCDriver(label,cd); admin._store(); // store is necessary, otherwise it get lost if(reload)admin._reload(); }
[ "/", "*", "public", "static", "void", "updateJDBCDriver", "(", "ConfigImpl", "config", "String", "label", "ClassDefinition", "cd", "boolean", "reload", ")", "throws", "IOException", "SAXException", "PageException", "BundleException", "{", "ConfigWebAdmin", "admin", "=...
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/config/XMLConfigAdmin.java#L1677-L1680
gmessner/gitlab4j-api
src/main/java/org/gitlab4j/api/GitLabApiClient.java
GitLabApiClient.getWithAccepts
protected Response getWithAccepts(MultivaluedMap<String, String> queryParams, String accepts, Object... pathArgs) throws IOException { URL url = getApiUrl(pathArgs); return (getWithAccepts(queryParams, url, accepts)); }
java
protected Response getWithAccepts(MultivaluedMap<String, String> queryParams, String accepts, Object... pathArgs) throws IOException { URL url = getApiUrl(pathArgs); return (getWithAccepts(queryParams, url, accepts)); }
[ "protected", "Response", "getWithAccepts", "(", "MultivaluedMap", "<", "String", ",", "String", ">", "queryParams", ",", "String", "accepts", ",", "Object", "...", "pathArgs", ")", "throws", "IOException", "{", "URL", "url", "=", "getApiUrl", "(", "pathArgs", ...
Perform an HTTP GET call with the specified query parameters and path objects, returning a ClientResponse instance with the data returned from the endpoint. @param queryParams multivalue map of request parameters @param accepts if non-empty will set the Accepts header to this value @param pathArgs variable list of arguments used to build the URI @return a ClientResponse instance with the data returned from the endpoint @throws IOException if an error occurs while constructing the URL
[ "Perform", "an", "HTTP", "GET", "call", "with", "the", "specified", "query", "parameters", "and", "path", "objects", "returning", "a", "ClientResponse", "instance", "with", "the", "data", "returned", "from", "the", "endpoint", "." ]
train
https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/GitLabApiClient.java#L399-L402
JOML-CI/JOML
src/org/joml/Matrix4f.java
Matrix4f.scaleAround
public Matrix4f scaleAround(float sx, float sy, float sz, float ox, float oy, float oz, Matrix4f dest) { float nm30 = m00 * ox + m10 * oy + m20 * oz + m30; float nm31 = m01 * ox + m11 * oy + m21 * oz + m31; float nm32 = m02 * ox + m12 * oy + m22 * oz + m32; float nm33 = m03 * ox + m13 * oy + m23 * oz + m33; dest._m00(m00 * sx); dest._m01(m01 * sx); dest._m02(m02 * sx); dest._m03(m03 * sx); dest._m10(m10 * sy); dest._m11(m11 * sy); dest._m12(m12 * sy); dest._m13(m13 * sy); dest._m20(m20 * sz); dest._m21(m21 * sz); dest._m22(m22 * sz); dest._m23(m23 * sz); dest._m30(-m00 * ox - m10 * oy - m20 * oz + nm30); dest._m31(-m01 * ox - m11 * oy - m21 * oz + nm31); dest._m32(-m02 * ox - m12 * oy - m22 * oz + nm32); dest._m33(-m03 * ox - m13 * oy - m23 * oz + nm33); boolean one = Math.abs(sx) == 1.0f && Math.abs(sy) == 1.0f && Math.abs(sz) == 1.0f; dest._properties(properties & ~(PROPERTY_PERSPECTIVE | PROPERTY_IDENTITY | PROPERTY_TRANSLATION | (one ? 0 : PROPERTY_ORTHONORMAL))); return dest; }
java
public Matrix4f scaleAround(float sx, float sy, float sz, float ox, float oy, float oz, Matrix4f dest) { float nm30 = m00 * ox + m10 * oy + m20 * oz + m30; float nm31 = m01 * ox + m11 * oy + m21 * oz + m31; float nm32 = m02 * ox + m12 * oy + m22 * oz + m32; float nm33 = m03 * ox + m13 * oy + m23 * oz + m33; dest._m00(m00 * sx); dest._m01(m01 * sx); dest._m02(m02 * sx); dest._m03(m03 * sx); dest._m10(m10 * sy); dest._m11(m11 * sy); dest._m12(m12 * sy); dest._m13(m13 * sy); dest._m20(m20 * sz); dest._m21(m21 * sz); dest._m22(m22 * sz); dest._m23(m23 * sz); dest._m30(-m00 * ox - m10 * oy - m20 * oz + nm30); dest._m31(-m01 * ox - m11 * oy - m21 * oz + nm31); dest._m32(-m02 * ox - m12 * oy - m22 * oz + nm32); dest._m33(-m03 * ox - m13 * oy - m23 * oz + nm33); boolean one = Math.abs(sx) == 1.0f && Math.abs(sy) == 1.0f && Math.abs(sz) == 1.0f; dest._properties(properties & ~(PROPERTY_PERSPECTIVE | PROPERTY_IDENTITY | PROPERTY_TRANSLATION | (one ? 0 : PROPERTY_ORTHONORMAL))); return dest; }
[ "public", "Matrix4f", "scaleAround", "(", "float", "sx", ",", "float", "sy", ",", "float", "sz", ",", "float", "ox", ",", "float", "oy", ",", "float", "oz", ",", "Matrix4f", "dest", ")", "{", "float", "nm30", "=", "m00", "*", "ox", "+", "m10", "*",...
/* (non-Javadoc) @see org.joml.Matrix4fc#scaleAround(float, float, float, float, float, float, org.joml.Matrix4f)
[ "/", "*", "(", "non", "-", "Javadoc", ")" ]
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4f.java#L4789-L4814
jmxtrans/jmxtrans
jmxtrans-output/jmxtrans-output-jrobin/src/main/java/com/googlecode/jmxtrans/model/output/RRDToolWriter.java
RRDToolWriter.checkErrorStream
private void checkErrorStream(Process process) throws Exception { // rrdtool should use platform encoding (unless you did something // very strange with your installation of rrdtool). So let's be // explicit and use the presumed correct encoding to read errors. try ( InputStream is = process.getErrorStream(); InputStreamReader isr = new InputStreamReader(is, Charset.defaultCharset()); BufferedReader br = new BufferedReader(isr) ) { StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line); } if (sb.length() > 0) { throw new RuntimeException(sb.toString()); } } }
java
private void checkErrorStream(Process process) throws Exception { // rrdtool should use platform encoding (unless you did something // very strange with your installation of rrdtool). So let's be // explicit and use the presumed correct encoding to read errors. try ( InputStream is = process.getErrorStream(); InputStreamReader isr = new InputStreamReader(is, Charset.defaultCharset()); BufferedReader br = new BufferedReader(isr) ) { StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line); } if (sb.length() > 0) { throw new RuntimeException(sb.toString()); } } }
[ "private", "void", "checkErrorStream", "(", "Process", "process", ")", "throws", "Exception", "{", "// rrdtool should use platform encoding (unless you did something", "// very strange with your installation of rrdtool). So let's be", "// explicit and use the presumed correct encoding to rea...
Check to see if there was an error processing an rrdtool command
[ "Check", "to", "see", "if", "there", "was", "an", "error", "processing", "an", "rrdtool", "command" ]
train
https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-output/jmxtrans-output-jrobin/src/main/java/com/googlecode/jmxtrans/model/output/RRDToolWriter.java#L249-L267
Azure/azure-sdk-for-java
cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ListManagementTermListsImpl.java
ListManagementTermListsImpl.refreshIndexMethod
public RefreshIndex refreshIndexMethod(String listId, String language) { return refreshIndexMethodWithServiceResponseAsync(listId, language).toBlocking().single().body(); }
java
public RefreshIndex refreshIndexMethod(String listId, String language) { return refreshIndexMethodWithServiceResponseAsync(listId, language).toBlocking().single().body(); }
[ "public", "RefreshIndex", "refreshIndexMethod", "(", "String", "listId", ",", "String", "language", ")", "{", "return", "refreshIndexMethodWithServiceResponseAsync", "(", "listId", ",", "language", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", ...
Refreshes the index of the list with list Id equal to list ID passed. @param listId List Id of the image list. @param language Language of the terms. @throws IllegalArgumentException thrown if parameters fail the validation @throws APIErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the RefreshIndex object if successful.
[ "Refreshes", "the", "index", "of", "the", "list", "with", "list", "Id", "equal", "to", "list", "ID", "passed", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ListManagementTermListsImpl.java#L502-L504
JOML-CI/JOML
src/org/joml/Matrix4f.java
Matrix4f.rotateTowards
public Matrix4f rotateTowards(float dirX, float dirY, float dirZ, float upX, float upY, float upZ, Matrix4f dest) { // Normalize direction float invDirLength = 1.0f / (float) Math.sqrt(dirX * dirX + dirY * dirY + dirZ * dirZ); float ndirX = dirX * invDirLength; float ndirY = dirY * invDirLength; float ndirZ = dirZ * invDirLength; // left = up x direction float leftX, leftY, leftZ; leftX = upY * ndirZ - upZ * ndirY; leftY = upZ * ndirX - upX * ndirZ; leftZ = upX * ndirY - upY * ndirX; // normalize left float invLeftLength = 1.0f / (float) Math.sqrt(leftX * leftX + leftY * leftY + leftZ * leftZ); leftX *= invLeftLength; leftY *= invLeftLength; leftZ *= invLeftLength; // up = direction x left float upnX = ndirY * leftZ - ndirZ * leftY; float upnY = ndirZ * leftX - ndirX * leftZ; float upnZ = ndirX * leftY - ndirY * leftX; float rm00 = leftX; float rm01 = leftY; float rm02 = leftZ; float rm10 = upnX; float rm11 = upnY; float rm12 = upnZ; float rm20 = ndirX; float rm21 = ndirY; float rm22 = ndirZ; dest._m30(m30); dest._m31(m31); dest._m32(m32); dest._m33(m33); float nm00 = m00 * rm00 + m10 * rm01 + m20 * rm02; float nm01 = m01 * rm00 + m11 * rm01 + m21 * rm02; float nm02 = m02 * rm00 + m12 * rm01 + m22 * rm02; float nm03 = m03 * rm00 + m13 * rm01 + m23 * rm02; float nm10 = m00 * rm10 + m10 * rm11 + m20 * rm12; float nm11 = m01 * rm10 + m11 * rm11 + m21 * rm12; float nm12 = m02 * rm10 + m12 * rm11 + m22 * rm12; float nm13 = m03 * rm10 + m13 * rm11 + m23 * rm12; dest._m20(m00 * rm20 + m10 * rm21 + m20 * rm22); dest._m21(m01 * rm20 + m11 * rm21 + m21 * rm22); dest._m22(m02 * rm20 + m12 * rm21 + m22 * rm22); dest._m23(m03 * rm20 + m13 * rm21 + m23 * rm22); dest._m00(nm00); dest._m01(nm01); dest._m02(nm02); dest._m03(nm03); dest._m10(nm10); dest._m11(nm11); dest._m12(nm12); dest._m13(nm13); dest._properties(properties & ~(PROPERTY_PERSPECTIVE | PROPERTY_IDENTITY | PROPERTY_TRANSLATION)); return dest; }
java
public Matrix4f rotateTowards(float dirX, float dirY, float dirZ, float upX, float upY, float upZ, Matrix4f dest) { // Normalize direction float invDirLength = 1.0f / (float) Math.sqrt(dirX * dirX + dirY * dirY + dirZ * dirZ); float ndirX = dirX * invDirLength; float ndirY = dirY * invDirLength; float ndirZ = dirZ * invDirLength; // left = up x direction float leftX, leftY, leftZ; leftX = upY * ndirZ - upZ * ndirY; leftY = upZ * ndirX - upX * ndirZ; leftZ = upX * ndirY - upY * ndirX; // normalize left float invLeftLength = 1.0f / (float) Math.sqrt(leftX * leftX + leftY * leftY + leftZ * leftZ); leftX *= invLeftLength; leftY *= invLeftLength; leftZ *= invLeftLength; // up = direction x left float upnX = ndirY * leftZ - ndirZ * leftY; float upnY = ndirZ * leftX - ndirX * leftZ; float upnZ = ndirX * leftY - ndirY * leftX; float rm00 = leftX; float rm01 = leftY; float rm02 = leftZ; float rm10 = upnX; float rm11 = upnY; float rm12 = upnZ; float rm20 = ndirX; float rm21 = ndirY; float rm22 = ndirZ; dest._m30(m30); dest._m31(m31); dest._m32(m32); dest._m33(m33); float nm00 = m00 * rm00 + m10 * rm01 + m20 * rm02; float nm01 = m01 * rm00 + m11 * rm01 + m21 * rm02; float nm02 = m02 * rm00 + m12 * rm01 + m22 * rm02; float nm03 = m03 * rm00 + m13 * rm01 + m23 * rm02; float nm10 = m00 * rm10 + m10 * rm11 + m20 * rm12; float nm11 = m01 * rm10 + m11 * rm11 + m21 * rm12; float nm12 = m02 * rm10 + m12 * rm11 + m22 * rm12; float nm13 = m03 * rm10 + m13 * rm11 + m23 * rm12; dest._m20(m00 * rm20 + m10 * rm21 + m20 * rm22); dest._m21(m01 * rm20 + m11 * rm21 + m21 * rm22); dest._m22(m02 * rm20 + m12 * rm21 + m22 * rm22); dest._m23(m03 * rm20 + m13 * rm21 + m23 * rm22); dest._m00(nm00); dest._m01(nm01); dest._m02(nm02); dest._m03(nm03); dest._m10(nm10); dest._m11(nm11); dest._m12(nm12); dest._m13(nm13); dest._properties(properties & ~(PROPERTY_PERSPECTIVE | PROPERTY_IDENTITY | PROPERTY_TRANSLATION)); return dest; }
[ "public", "Matrix4f", "rotateTowards", "(", "float", "dirX", ",", "float", "dirY", ",", "float", "dirZ", ",", "float", "upX", ",", "float", "upY", ",", "float", "upZ", ",", "Matrix4f", "dest", ")", "{", "// Normalize direction", "float", "invDirLength", "=",...
Apply a model transformation to this matrix for a right-handed coordinate system, that aligns the local <code>+Z</code> axis with <code>(dirX, dirY, dirZ)</code> and store the result in <code>dest</code>. <p> If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookat matrix, then the new matrix will be <code>M * L</code>. So when transforming a vector <code>v</code> with the new matrix by using <code>M * L * v</code>, the lookat transformation will be applied first! <p> In order to set the matrix to a rotation transformation without post-multiplying it, use {@link #rotationTowards(float, float, float, float, float, float) rotationTowards()}. <p> This method is equivalent to calling: <code>mulAffine(new Matrix4f().lookAt(0, 0, 0, -dirX, -dirY, -dirZ, upX, upY, upZ).invertAffine(), dest)</code> @see #rotateTowards(Vector3fc, Vector3fc) @see #rotationTowards(float, float, float, float, float, float) @param dirX the x-coordinate of the direction to rotate towards @param dirY the y-coordinate of the direction to rotate towards @param dirZ the z-coordinate of the direction to rotate towards @param upX the x-coordinate of the up vector @param upY the y-coordinate of the up vector @param upZ the z-coordinate of the up vector @param dest will hold the result @return dest
[ "Apply", "a", "model", "transformation", "to", "this", "matrix", "for", "a", "right", "-", "handed", "coordinate", "system", "that", "aligns", "the", "local", "<code", ">", "+", "Z<", "/", "code", ">", "axis", "with", "<code", ">", "(", "dirX", "dirY", ...
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4f.java#L14231-L14286
alkacon/opencms-core
src/org/opencms/util/CmsStringUtil.java
CmsStringUtil.getCommonPrefixPath
public static String getCommonPrefixPath(String first, String second) { List<String> firstComponents = getPathComponents(first); List<String> secondComponents = getPathComponents(second); int minSize = Math.min(firstComponents.size(), secondComponents.size()); StringBuffer resultBuffer = new StringBuffer(); for (int i = 0; i < minSize; i++) { if (firstComponents.get(i).equals(secondComponents.get(i))) { resultBuffer.append("/"); resultBuffer.append(firstComponents.get(i)); } else { break; } } String result = resultBuffer.toString(); if (result.length() == 0) { result = "/"; } return result; }
java
public static String getCommonPrefixPath(String first, String second) { List<String> firstComponents = getPathComponents(first); List<String> secondComponents = getPathComponents(second); int minSize = Math.min(firstComponents.size(), secondComponents.size()); StringBuffer resultBuffer = new StringBuffer(); for (int i = 0; i < minSize; i++) { if (firstComponents.get(i).equals(secondComponents.get(i))) { resultBuffer.append("/"); resultBuffer.append(firstComponents.get(i)); } else { break; } } String result = resultBuffer.toString(); if (result.length() == 0) { result = "/"; } return result; }
[ "public", "static", "String", "getCommonPrefixPath", "(", "String", "first", ",", "String", "second", ")", "{", "List", "<", "String", ">", "firstComponents", "=", "getPathComponents", "(", "first", ")", ";", "List", "<", "String", ">", "secondComponents", "="...
Returns the common parent path of two paths.<p> <b>Directly exposed for JSP EL</b>, not through {@link org.opencms.jsp.util.CmsJspElFunctions}.<p> @param first the first path @param second the second path @return the common prefix path
[ "Returns", "the", "common", "parent", "path", "of", "two", "paths", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/util/CmsStringUtil.java#L745-L764
brettwooldridge/HikariCP
src/main/java/com/zaxxer/hikari/pool/HikariPool.java
HikariPool.softEvictConnection
private boolean softEvictConnection(final PoolEntry poolEntry, final String reason, final boolean owner) { poolEntry.markEvicted(); if (owner || connectionBag.reserve(poolEntry)) { closeConnection(poolEntry, reason); return true; } return false; }
java
private boolean softEvictConnection(final PoolEntry poolEntry, final String reason, final boolean owner) { poolEntry.markEvicted(); if (owner || connectionBag.reserve(poolEntry)) { closeConnection(poolEntry, reason); return true; } return false; }
[ "private", "boolean", "softEvictConnection", "(", "final", "PoolEntry", "poolEntry", ",", "final", "String", "reason", ",", "final", "boolean", "owner", ")", "{", "poolEntry", ".", "markEvicted", "(", ")", ";", "if", "(", "owner", "||", "connectionBag", ".", ...
"Soft" evict a Connection (/PoolEntry) from the pool. If this method is being called by the user directly through {@link com.zaxxer.hikari.HikariDataSource#evictConnection(Connection)} then {@code owner} is {@code true}. If the caller is the owner, or if the Connection is idle (i.e. can be "reserved" in the {@link ConcurrentBag}), then we can close the connection immediately. Otherwise, we leave it "marked" for eviction so that it is evicted the next time someone tries to acquire it from the pool. @param poolEntry the PoolEntry (/Connection) to "soft" evict from the pool @param reason the reason that the connection is being evicted @param owner true if the caller is the owner of the connection, false otherwise @return true if the connection was evicted (closed), false if it was merely marked for eviction
[ "Soft", "evict", "a", "Connection", "(", "/", "PoolEntry", ")", "from", "the", "pool", ".", "If", "this", "method", "is", "being", "called", "by", "the", "user", "directly", "through", "{", "@link", "com", ".", "zaxxer", ".", "hikari", ".", "HikariDataSo...
train
https://github.com/brettwooldridge/HikariCP/blob/c509ec1a3f1e19769ee69323972f339cf098ff4b/src/main/java/com/zaxxer/hikari/pool/HikariPool.java#L613-L622
greenmail-mail-test/greenmail
greenmail-core/src/main/java/com/icegreen/greenmail/imap/commands/CommandParser.java
CommandParser.consumeChar
protected void consumeChar(ImapRequestLineReader request, char expected) throws ProtocolException { char consumed = request.consume(); if (consumed != expected) { throw new ProtocolException("Expected:'" + expected + "' found:'" + consumed + '\''); } }
java
protected void consumeChar(ImapRequestLineReader request, char expected) throws ProtocolException { char consumed = request.consume(); if (consumed != expected) { throw new ProtocolException("Expected:'" + expected + "' found:'" + consumed + '\''); } }
[ "protected", "void", "consumeChar", "(", "ImapRequestLineReader", "request", ",", "char", "expected", ")", "throws", "ProtocolException", "{", "char", "consumed", "=", "request", ".", "consume", "(", ")", ";", "if", "(", "consumed", "!=", "expected", ")", "{",...
Consumes the next character in the request, checking that it matches the expected one. This method should be used when the
[ "Consumes", "the", "next", "character", "in", "the", "request", "checking", "that", "it", "matches", "the", "expected", "one", ".", "This", "method", "should", "be", "used", "when", "the" ]
train
https://github.com/greenmail-mail-test/greenmail/blob/6d19a62233d1ef6fedbbd1f6fdde2d28e713834a/greenmail-core/src/main/java/com/icegreen/greenmail/imap/commands/CommandParser.java#L237-L243
aws/aws-sdk-java
aws-java-sdk-core/src/main/java/com/amazonaws/util/URLEncodedUtils.java
URLEncodedUtils.format
public static String format( final List <? extends NameValuePair> parameters, final String charset) { return format(parameters, QP_SEP_A, charset); }
java
public static String format( final List <? extends NameValuePair> parameters, final String charset) { return format(parameters, QP_SEP_A, charset); }
[ "public", "static", "String", "format", "(", "final", "List", "<", "?", "extends", "NameValuePair", ">", "parameters", ",", "final", "String", "charset", ")", "{", "return", "format", "(", "parameters", ",", "QP_SEP_A", ",", "charset", ")", ";", "}" ]
Returns a String that is suitable for use as an {@code application/x-www-form-urlencoded} list of parameters in an HTTP PUT or HTTP POST. @param parameters The parameters to include. @param charset The encoding to use. @return An {@code application/x-www-form-urlencoded} string
[ "Returns", "a", "String", "that", "is", "suitable", "for", "use", "as", "an", "{", "@code", "application", "/", "x", "-", "www", "-", "form", "-", "urlencoded", "}", "list", "of", "parameters", "in", "an", "HTTP", "PUT", "or", "HTTP", "POST", "." ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-core/src/main/java/com/amazonaws/util/URLEncodedUtils.java#L56-L60
RestComm/sipunit
src/main/java/org/cafesip/sipunit/SipAssert.java
SipAssert.assertHeaderNotPresent
public static void assertHeaderNotPresent(String msg, SipMessage sipMessage, String header) { assertNotNull("Null assert object passed in", sipMessage); assertFalse(msg, sipMessage.getHeaders(header).hasNext()); }
java
public static void assertHeaderNotPresent(String msg, SipMessage sipMessage, String header) { assertNotNull("Null assert object passed in", sipMessage); assertFalse(msg, sipMessage.getHeaders(header).hasNext()); }
[ "public", "static", "void", "assertHeaderNotPresent", "(", "String", "msg", ",", "SipMessage", "sipMessage", ",", "String", "header", ")", "{", "assertNotNull", "(", "\"Null assert object passed in\"", ",", "sipMessage", ")", ";", "assertFalse", "(", "msg", ",", "...
Asserts that the given SIP message contains no occurrence of the specified header. Assertion failure output includes the given message text. @param msg message text to output if the assertion fails. @param sipMessage the SIP message. @param header the string identifying the header as specified in RFC-3261.
[ "Asserts", "that", "the", "given", "SIP", "message", "contains", "no", "occurrence", "of", "the", "specified", "header", ".", "Assertion", "failure", "output", "includes", "the", "given", "message", "text", "." ]
train
https://github.com/RestComm/sipunit/blob/18a6be2e29be3fbdc14226e8c41b25e2d57378b1/src/main/java/org/cafesip/sipunit/SipAssert.java#L146-L149
pravega/pravega
segmentstore/server/src/main/java/io/pravega/segmentstore/server/writer/SegmentAggregator.java
SegmentAggregator.reconcileAppendOperation
private CompletableFuture<WriterFlushResult> reconcileAppendOperation(AggregatedAppendOperation op, SegmentProperties storageInfo, TimeoutTimer timer) { CompletableFuture<Boolean> reconcileResult; WriterFlushResult flushResult = new WriterFlushResult(); if (op.getLength() > 0) { // This operation has data. Reconcile that first. reconcileResult = reconcileData(op, storageInfo, timer) .thenApply(reconciledBytes -> { flushResult.withFlushedBytes(reconciledBytes); return reconciledBytes >= op.getLength() && op.getLastStreamSegmentOffset() <= storageInfo.getLength(); }); } else { // No data to reconcile, so we consider this part done. reconcileResult = CompletableFuture.completedFuture(true); } if (!op.attributes.isEmpty()) { // This operation has Attributes. Reconcile them, but only if the data reconciliation succeeded for the whole operation. reconcileResult = reconcileResult.thenComposeAsync(fullyReconciledData -> { if (fullyReconciledData) { return reconcileAttributes(op, timer) .thenApply(v -> { flushResult.withFlushedAttributes(op.attributes.size()); return fullyReconciledData; }); } else { return CompletableFuture.completedFuture(fullyReconciledData); } }, this.executor); } return reconcileResult.thenApplyAsync(fullyReconciled -> { if (fullyReconciled) { // Operation has been completely validated; pop it off the list. StorageOperation removedOp = this.operations.removeFirst(); assert op == removedOp : "Reconciled operation is not the same as removed operation"; } return flushResult; }); }
java
private CompletableFuture<WriterFlushResult> reconcileAppendOperation(AggregatedAppendOperation op, SegmentProperties storageInfo, TimeoutTimer timer) { CompletableFuture<Boolean> reconcileResult; WriterFlushResult flushResult = new WriterFlushResult(); if (op.getLength() > 0) { // This operation has data. Reconcile that first. reconcileResult = reconcileData(op, storageInfo, timer) .thenApply(reconciledBytes -> { flushResult.withFlushedBytes(reconciledBytes); return reconciledBytes >= op.getLength() && op.getLastStreamSegmentOffset() <= storageInfo.getLength(); }); } else { // No data to reconcile, so we consider this part done. reconcileResult = CompletableFuture.completedFuture(true); } if (!op.attributes.isEmpty()) { // This operation has Attributes. Reconcile them, but only if the data reconciliation succeeded for the whole operation. reconcileResult = reconcileResult.thenComposeAsync(fullyReconciledData -> { if (fullyReconciledData) { return reconcileAttributes(op, timer) .thenApply(v -> { flushResult.withFlushedAttributes(op.attributes.size()); return fullyReconciledData; }); } else { return CompletableFuture.completedFuture(fullyReconciledData); } }, this.executor); } return reconcileResult.thenApplyAsync(fullyReconciled -> { if (fullyReconciled) { // Operation has been completely validated; pop it off the list. StorageOperation removedOp = this.operations.removeFirst(); assert op == removedOp : "Reconciled operation is not the same as removed operation"; } return flushResult; }); }
[ "private", "CompletableFuture", "<", "WriterFlushResult", ">", "reconcileAppendOperation", "(", "AggregatedAppendOperation", "op", ",", "SegmentProperties", "storageInfo", ",", "TimeoutTimer", "timer", ")", "{", "CompletableFuture", "<", "Boolean", ">", "reconcileResult", ...
Attempts to reconcile data and attributes for the given AggregatedAppendOperation. Since Append Operations can be partially flushed, reconciliation may be for the full operation or for a part of it. @param op The AggregatedAppendOperation to reconcile. @param storageInfo The current state of the Segment in Storage. @param timer Timer for the operation. @return A CompletableFuture containing a FlushResult with the number of bytes reconciled, or failed with a ReconciliationFailureException, if the operation cannot be reconciled, based on the in-memory metadata or the current state of the Segment in Storage.
[ "Attempts", "to", "reconcile", "data", "and", "attributes", "for", "the", "given", "AggregatedAppendOperation", ".", "Since", "Append", "Operations", "can", "be", "partially", "flushed", "reconciliation", "may", "be", "for", "the", "full", "operation", "or", "for"...
train
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/segmentstore/server/src/main/java/io/pravega/segmentstore/server/writer/SegmentAggregator.java#L1306-L1344
davidcarboni/cryptolite-java
src/main/java/com/github/davidcarboni/cryptolite/Keys.java
Keys.newKeyPair
public static KeyPair newKeyPair() { // Construct a key generator KeyPairGenerator keyPairGenerator; try { keyPairGenerator = KeyPairGenerator.getInstance(ASYMMETRIC_ALGORITHM); keyPairGenerator.initialize(ASYMMETRIC_KEY_SIZE); } catch (NoSuchAlgorithmException e) { if (SecurityProvider.addProvider()) { return newKeyPair(); } else { throw new IllegalStateException("Algorithm unavailable: " + ASYMMETRIC_ALGORITHM, e); } } // Generate a key: KeyPair result = keyPairGenerator.generateKeyPair(); return result; }
java
public static KeyPair newKeyPair() { // Construct a key generator KeyPairGenerator keyPairGenerator; try { keyPairGenerator = KeyPairGenerator.getInstance(ASYMMETRIC_ALGORITHM); keyPairGenerator.initialize(ASYMMETRIC_KEY_SIZE); } catch (NoSuchAlgorithmException e) { if (SecurityProvider.addProvider()) { return newKeyPair(); } else { throw new IllegalStateException("Algorithm unavailable: " + ASYMMETRIC_ALGORITHM, e); } } // Generate a key: KeyPair result = keyPairGenerator.generateKeyPair(); return result; }
[ "public", "static", "KeyPair", "newKeyPair", "(", ")", "{", "// Construct a key generator\r", "KeyPairGenerator", "keyPairGenerator", ";", "try", "{", "keyPairGenerator", "=", "KeyPairGenerator", ".", "getInstance", "(", "ASYMMETRIC_ALGORITHM", ")", ";", "keyPairGenerator...
Generates a new public-private (or asymmetric) key pair for use with {@value #ASYMMETRIC_ALGORITHM}. <p> The key size will be {@value #ASYMMETRIC_KEY_SIZE} bits. <p> BouncyCastle will automatically generate a "Chinese Remainder Theorem" or CRT key, which makes using a symmetric encryption significantly faster. @return A new, randomly generated asymmetric key pair.
[ "Generates", "a", "new", "public", "-", "private", "(", "or", "asymmetric", ")", "key", "pair", "for", "use", "with", "{", "@value", "#ASYMMETRIC_ALGORITHM", "}", ".", "<p", ">", "The", "key", "size", "will", "be", "{", "@value", "#ASYMMETRIC_KEY_SIZE", "}...
train
https://github.com/davidcarboni/cryptolite-java/blob/e67954181a04ffc9beb1d9abca1421195fcf9764/src/main/java/com/github/davidcarboni/cryptolite/Keys.java#L227-L246
carewebframework/carewebframework-core
org.carewebframework.shell/src/main/java/org/carewebframework/shell/elements/ElementTreeView.java
ElementTreeView.afterMoveChild
@Override protected void afterMoveChild(ElementBase child, ElementBase before) { ElementTreePane childpane = (ElementTreePane) child; ElementTreePane beforepane = (ElementTreePane) before; moveChild(childpane.getNode(), beforepane.getNode()); }
java
@Override protected void afterMoveChild(ElementBase child, ElementBase before) { ElementTreePane childpane = (ElementTreePane) child; ElementTreePane beforepane = (ElementTreePane) before; moveChild(childpane.getNode(), beforepane.getNode()); }
[ "@", "Override", "protected", "void", "afterMoveChild", "(", "ElementBase", "child", ",", "ElementBase", "before", ")", "{", "ElementTreePane", "childpane", "=", "(", "ElementTreePane", ")", "child", ";", "ElementTreePane", "beforepane", "=", "(", "ElementTreePane",...
Only the node needs to be resequenced, since pane sequencing is arbitrary.
[ "Only", "the", "node", "needs", "to", "be", "resequenced", "since", "pane", "sequencing", "is", "arbitrary", "." ]
train
https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.shell/src/main/java/org/carewebframework/shell/elements/ElementTreeView.java#L70-L75
tvesalainen/util
util/src/main/java/org/vesalainen/bean/BeanHelper.java
BeanHelper.addList
public static final <T> void addList(Object bean, String property, T value) { addList(bean, property, null, (Class<T> c, String h)->{return value;}); }
java
public static final <T> void addList(Object bean, String property, T value) { addList(bean, property, null, (Class<T> c, String h)->{return value;}); }
[ "public", "static", "final", "<", "T", ">", "void", "addList", "(", "Object", "bean", ",", "String", "property", ",", "T", "value", ")", "{", "addList", "(", "bean", ",", "property", ",", "null", ",", "(", "Class", "<", "T", ">", "c", ",", "String"...
Adds pattern item to end of list @param <T> @param bean @param property @param value
[ "Adds", "pattern", "item", "to", "end", "of", "list" ]
train
https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/util/src/main/java/org/vesalainen/bean/BeanHelper.java#L582-L585
tootedom/related
app/domain/src/main/java/org/greencheek/related/api/RelatedItemAdditionalProperties.java
RelatedItemAdditionalProperties.convertToStringArray
public String[][] convertToStringArray() { int numberOfProps = numberOfProperties; String[][] props = new String[numberOfProps][2]; while(numberOfProps--!=0) { RelatedItemAdditionalProperty prop = additionalProperties[numberOfProps]; props[numberOfProps][0] = new String(prop.name,0,prop.nameLength); props[numberOfProps][1] = new String(prop.value,0,prop.valueLength); } return props; }
java
public String[][] convertToStringArray() { int numberOfProps = numberOfProperties; String[][] props = new String[numberOfProps][2]; while(numberOfProps--!=0) { RelatedItemAdditionalProperty prop = additionalProperties[numberOfProps]; props[numberOfProps][0] = new String(prop.name,0,prop.nameLength); props[numberOfProps][1] = new String(prop.value,0,prop.valueLength); } return props; }
[ "public", "String", "[", "]", "[", "]", "convertToStringArray", "(", ")", "{", "int", "numberOfProps", "=", "numberOfProperties", ";", "String", "[", "]", "[", "]", "props", "=", "new", "String", "[", "numberOfProps", "]", "[", "2", "]", ";", "while", ...
Returns a two dimensional array that is like that of a map: [ key ],[ value ] [ key ],[ value ] [ key ],[ value ] @return
[ "Returns", "a", "two", "dimensional", "array", "that", "is", "like", "that", "of", "a", "map", ":", "[", "key", "]", "[", "value", "]", "[", "key", "]", "[", "value", "]", "[", "key", "]", "[", "value", "]" ]
train
https://github.com/tootedom/related/blob/3782dd5a839bbcdc15661d598e8b895aae8aabb7/app/domain/src/main/java/org/greencheek/related/api/RelatedItemAdditionalProperties.java#L183-L192
xhsun/gw2wrapper
src/main/java/me/xhsun/guildwars2wrapper/AsynchronousRequest.java
AsynchronousRequest.getWvWMatchDetail
public void getWvWMatchDetail(String[] ids, Callback<List<WvWMatchDetail>> callback) throws GuildWars2Exception, NullPointerException { isParamValid(new ParamChecker(ids)); gw2API.getWvWMatchInfoUsingID(processIds(ids)).enqueue(callback); }
java
public void getWvWMatchDetail(String[] ids, Callback<List<WvWMatchDetail>> callback) throws GuildWars2Exception, NullPointerException { isParamValid(new ParamChecker(ids)); gw2API.getWvWMatchInfoUsingID(processIds(ids)).enqueue(callback); }
[ "public", "void", "getWvWMatchDetail", "(", "String", "[", "]", "ids", ",", "Callback", "<", "List", "<", "WvWMatchDetail", ">", ">", "callback", ")", "throws", "GuildWars2Exception", ",", "NullPointerException", "{", "isParamValid", "(", "new", "ParamChecker", ...
For more info on WvW matches API go <a href="https://wiki.guildwars2.com/wiki/API:2/wvw/matches">here</a><br/> Give user the access to {@link Callback#onResponse(Call, Response)} and {@link Callback#onFailure(Call, Throwable)} methods for custom interactions @param ids list of wvw match id(s) @param callback callback that is going to be used for {@link Call#enqueue(Callback)} @throws NullPointerException if given {@link Callback} is empty @throws GuildWars2Exception empty ID list @see WvWMatchDetail WvW match detailed info
[ "For", "more", "info", "on", "WvW", "matches", "API", "go", "<a", "href", "=", "https", ":", "//", "wiki", ".", "guildwars2", ".", "com", "/", "wiki", "/", "API", ":", "2", "/", "wvw", "/", "matches", ">", "here<", "/", "a", ">", "<br", "/", ">...
train
https://github.com/xhsun/gw2wrapper/blob/c8a43b51f363b032074fb152ee6efe657e33e525/src/main/java/me/xhsun/guildwars2wrapper/AsynchronousRequest.java#L2624-L2627
j-easy/easy-random
easy-random-core/src/main/java/org/jeasy/random/EasyRandom.java
EasyRandom.nextObject
public <T> T nextObject(final Class<T> type) { return doPopulateBean(type, new RandomizationContext(type, parameters)); }
java
public <T> T nextObject(final Class<T> type) { return doPopulateBean(type, new RandomizationContext(type, parameters)); }
[ "public", "<", "T", ">", "T", "nextObject", "(", "final", "Class", "<", "T", ">", "type", ")", "{", "return", "doPopulateBean", "(", "type", ",", "new", "RandomizationContext", "(", "type", ",", "parameters", ")", ")", ";", "}" ]
Generate a random instance of the given type. @param type the type for which an instance will be generated @param <T> the actual type of the target object @return a random instance of the given type @throws ObjectCreationException when unable to create a new instance of the given type
[ "Generate", "a", "random", "instance", "of", "the", "given", "type", "." ]
train
https://github.com/j-easy/easy-random/blob/816b0d6a74c7288af111e70ae1b0b57d7fe3b59d/easy-random-core/src/main/java/org/jeasy/random/EasyRandom.java#L96-L98
lessthanoptimal/BoofCV
main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/qrcode/GaliosFieldTableOps.java
GaliosFieldTableOps.polyAdd
public void polyAdd(GrowQueue_I8 polyA , GrowQueue_I8 polyB , GrowQueue_I8 output ) { output.resize(Math.max(polyA.size,polyB.size)); // compute offset that would align the smaller polynomial with the larger polynomial int offsetA = Math.max(0,polyB.size-polyA.size); int offsetB = Math.max(0,polyA.size-polyB.size); int N = output.size; for (int i = 0; i < offsetB; i++) { output.data[i] = polyA.data[i]; } for (int i = 0; i < offsetA; i++) { output.data[i] = polyB.data[i]; } for (int i = Math.max(offsetA,offsetB); i < N; i++) { output.data[i] = (byte)((polyA.data[i-offsetA]&0xFF) ^ (polyB.data[i-offsetB]&0xFF)); } }
java
public void polyAdd(GrowQueue_I8 polyA , GrowQueue_I8 polyB , GrowQueue_I8 output ) { output.resize(Math.max(polyA.size,polyB.size)); // compute offset that would align the smaller polynomial with the larger polynomial int offsetA = Math.max(0,polyB.size-polyA.size); int offsetB = Math.max(0,polyA.size-polyB.size); int N = output.size; for (int i = 0; i < offsetB; i++) { output.data[i] = polyA.data[i]; } for (int i = 0; i < offsetA; i++) { output.data[i] = polyB.data[i]; } for (int i = Math.max(offsetA,offsetB); i < N; i++) { output.data[i] = (byte)((polyA.data[i-offsetA]&0xFF) ^ (polyB.data[i-offsetB]&0xFF)); } }
[ "public", "void", "polyAdd", "(", "GrowQueue_I8", "polyA", ",", "GrowQueue_I8", "polyB", ",", "GrowQueue_I8", "output", ")", "{", "output", ".", "resize", "(", "Math", ".", "max", "(", "polyA", ".", "size", ",", "polyB", ".", "size", ")", ")", ";", "//...
Adds two polynomials together. output = polyA + polyB <p>Coefficients for largest powers are first, e.g. 2*x**3 + 8*x**2+1 = [2,8,0,1]</p> @param polyA (Input) First polynomial @param polyB (Input) Second polynomial @param output (Output) Results of addition
[ "Adds", "two", "polynomials", "together", ".", "output", "=", "polyA", "+", "polyB" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/qrcode/GaliosFieldTableOps.java#L147-L164
OSSIndex/heuristic-version
src/main/java/net/ossindex/version/impl/SemanticVersion.java
SemanticVersion.getNextVersion
public SemanticVersion getNextVersion() { int major = head.getMajorVersion(); int minor = head.getMinorVersion(); int patch = head.getPatchVersion(); return new SemanticVersion(major, minor, patch + 1); }
java
public SemanticVersion getNextVersion() { int major = head.getMajorVersion(); int minor = head.getMinorVersion(); int patch = head.getPatchVersion(); return new SemanticVersion(major, minor, patch + 1); }
[ "public", "SemanticVersion", "getNextVersion", "(", ")", "{", "int", "major", "=", "head", ".", "getMajorVersion", "(", ")", ";", "int", "minor", "=", "head", ".", "getMinorVersion", "(", ")", ";", "int", "patch", "=", "head", ".", "getPatchVersion", "(", ...
Get the next logical version in line. For example: 1.2.3 becomes 1.2.4
[ "Get", "the", "next", "logical", "version", "in", "line", ".", "For", "example", ":" ]
train
https://github.com/OSSIndex/heuristic-version/blob/9fe33a49d74acec54ddb91de9a3c3cd2f98fba40/src/main/java/net/ossindex/version/impl/SemanticVersion.java#L278-L283
mgm-tp/jfunk
jfunk-core/src/main/java/com/mgmtp/jfunk/core/scripting/ModuleArchiver.java
ModuleArchiver.addToArchive
public void addToArchive(final File relativeDir, final File fileOrDirToAdd) throws IOException { checkArgument(!relativeDir.isAbsolute(), "'relativeDir' must be a relative directory"); if (isArchivingDisabled()) { return; } if (fileOrDirToAdd.getCanonicalPath().startsWith(moduleArchiveDir.getCanonicalPath())) { // File already in archive dir log.info("File '" + fileOrDirToAdd + "' already in archive directory. No copying necessary."); return; } File archiveTargetDir = new File(moduleArchiveDir, relativeDir.getPath()); if (fileOrDirToAdd.isDirectory()) { copyDirectory(fileOrDirToAdd, archiveTargetDir); } else { copyFileToDirectory(fileOrDirToAdd, archiveTargetDir); } }
java
public void addToArchive(final File relativeDir, final File fileOrDirToAdd) throws IOException { checkArgument(!relativeDir.isAbsolute(), "'relativeDir' must be a relative directory"); if (isArchivingDisabled()) { return; } if (fileOrDirToAdd.getCanonicalPath().startsWith(moduleArchiveDir.getCanonicalPath())) { // File already in archive dir log.info("File '" + fileOrDirToAdd + "' already in archive directory. No copying necessary."); return; } File archiveTargetDir = new File(moduleArchiveDir, relativeDir.getPath()); if (fileOrDirToAdd.isDirectory()) { copyDirectory(fileOrDirToAdd, archiveTargetDir); } else { copyFileToDirectory(fileOrDirToAdd, archiveTargetDir); } }
[ "public", "void", "addToArchive", "(", "final", "File", "relativeDir", ",", "final", "File", "fileOrDirToAdd", ")", "throws", "IOException", "{", "checkArgument", "(", "!", "relativeDir", ".", "isAbsolute", "(", ")", ",", "\"'relativeDir' must be a relative directory\...
Adds a file or directory (recursively) to the archive directory if it is not already present in the archive directory. @param relativeDir the directory relative to the archive root directory which the specified file or directory is added to @param fileOrDirToAdd the file or directory to add @throws IOException if an IO error occurs during copying
[ "Adds", "a", "file", "or", "directory", "(", "recursively", ")", "to", "the", "archive", "directory", "if", "it", "is", "not", "already", "present", "in", "the", "archive", "directory", "." ]
train
https://github.com/mgm-tp/jfunk/blob/5b9fecac5778b988bb458085ded39ea9a4c7c2ae/jfunk-core/src/main/java/com/mgmtp/jfunk/core/scripting/ModuleArchiver.java#L250-L269
emilsjolander/StickyListHeaders
library/src/se/emilsjolander/stickylistheaders/ExpandableStickyListHeadersListView.java
ExpandableStickyListHeadersListView.animateView
private void animateView(final View target, final int type) { if(ANIMATION_EXPAND==type&&target.getVisibility()==VISIBLE){ return; } if(ANIMATION_COLLAPSE==type&&target.getVisibility()!=VISIBLE){ return; } if(mDefaultAnimExecutor !=null){ mDefaultAnimExecutor.executeAnim(target,type); } }
java
private void animateView(final View target, final int type) { if(ANIMATION_EXPAND==type&&target.getVisibility()==VISIBLE){ return; } if(ANIMATION_COLLAPSE==type&&target.getVisibility()!=VISIBLE){ return; } if(mDefaultAnimExecutor !=null){ mDefaultAnimExecutor.executeAnim(target,type); } }
[ "private", "void", "animateView", "(", "final", "View", "target", ",", "final", "int", "type", ")", "{", "if", "(", "ANIMATION_EXPAND", "==", "type", "&&", "target", ".", "getVisibility", "(", ")", "==", "VISIBLE", ")", "{", "return", ";", "}", "if", "...
Performs either COLLAPSE or EXPAND animation on the target view @param target the view to animate @param type the animation type, either ExpandCollapseAnimation.COLLAPSE or ExpandCollapseAnimation.EXPAND
[ "Performs", "either", "COLLAPSE", "or", "EXPAND", "animation", "on", "the", "target", "view" ]
train
https://github.com/emilsjolander/StickyListHeaders/blob/cec8d6a6ddfc29c530df5864794a5a0a2d2f3675/library/src/se/emilsjolander/stickylistheaders/ExpandableStickyListHeadersListView.java#L113-L124
lessthanoptimal/ejml
main/ejml-core/src/org/ejml/data/DMatrixSparseCSC.java
DMatrixSparseCSC.nz_index
public int nz_index( int row , int col ) { int col0 = col_idx[col]; int col1 = col_idx[col+1]; for (int i = col0; i < col1; i++) { if( nz_rows[i] == row ) { return i; } } return -1; }
java
public int nz_index( int row , int col ) { int col0 = col_idx[col]; int col1 = col_idx[col+1]; for (int i = col0; i < col1; i++) { if( nz_rows[i] == row ) { return i; } } return -1; }
[ "public", "int", "nz_index", "(", "int", "row", ",", "int", "col", ")", "{", "int", "col0", "=", "col_idx", "[", "col", "]", ";", "int", "col1", "=", "col_idx", "[", "col", "+", "1", "]", ";", "for", "(", "int", "i", "=", "col0", ";", "i", "<...
Returns the index in nz_rows for the element at (row,col) if it already exists in the matrix. If not then -1 is returned. @param row row coordinate @param col column coordinate @return nz_row index or -1 if the element does not exist
[ "Returns", "the", "index", "in", "nz_rows", "for", "the", "element", "at", "(", "row", "col", ")", "if", "it", "already", "exists", "in", "the", "matrix", ".", "If", "not", "then", "-", "1", "is", "returned", "." ]
train
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-core/src/org/ejml/data/DMatrixSparseCSC.java#L195-L205
LevelFourAB/commons
commons-types/src/main/java/se/l4/commons/types/matching/AbstractClassMatchingMap.java
AbstractClassMatchingMap.findMatching
protected void findMatching(Class<? extends T> type, BiPredicate<Class<? extends T>, D> predicate) { traverseType(type, predicate, new HashSet<>()); }
java
protected void findMatching(Class<? extends T> type, BiPredicate<Class<? extends T>, D> predicate) { traverseType(type, predicate, new HashSet<>()); }
[ "protected", "void", "findMatching", "(", "Class", "<", "?", "extends", "T", ">", "type", ",", "BiPredicate", "<", "Class", "<", "?", "extends", "T", ">", ",", "D", ">", "predicate", ")", "{", "traverseType", "(", "type", ",", "predicate", ",", "new", ...
Perform matching against the given type. This will go through the hierarchy and interfaces of the type trying to find if this map has an entry for them.
[ "Perform", "matching", "against", "the", "given", "type", ".", "This", "will", "go", "through", "the", "hierarchy", "and", "interfaces", "of", "the", "type", "trying", "to", "find", "if", "this", "map", "has", "an", "entry", "for", "them", "." ]
train
https://github.com/LevelFourAB/commons/blob/aa121b3a5504b43d0c10450a1b984694fcd2b8ee/commons-types/src/main/java/se/l4/commons/types/matching/AbstractClassMatchingMap.java#L82-L85
Azure/azure-sdk-for-java
appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/implementation/AppServicePlansInner.java
AppServicePlansInner.updateVnetRoute
public VnetRouteInner updateVnetRoute(String resourceGroupName, String name, String vnetName, String routeName, VnetRouteInner route) { return updateVnetRouteWithServiceResponseAsync(resourceGroupName, name, vnetName, routeName, route).toBlocking().single().body(); }
java
public VnetRouteInner updateVnetRoute(String resourceGroupName, String name, String vnetName, String routeName, VnetRouteInner route) { return updateVnetRouteWithServiceResponseAsync(resourceGroupName, name, vnetName, routeName, route).toBlocking().single().body(); }
[ "public", "VnetRouteInner", "updateVnetRoute", "(", "String", "resourceGroupName", ",", "String", "name", ",", "String", "vnetName", ",", "String", "routeName", ",", "VnetRouteInner", "route", ")", "{", "return", "updateVnetRouteWithServiceResponseAsync", "(", "resource...
Create or update a Virtual Network route in an App Service plan. Create or update a Virtual Network route in an App Service plan. @param resourceGroupName Name of the resource group to which the resource belongs. @param name Name of the App Service plan. @param vnetName Name of the Virtual Network. @param routeName Name of the Virtual Network route. @param route Definition of the Virtual Network route. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the VnetRouteInner object if successful.
[ "Create", "or", "update", "a", "Virtual", "Network", "route", "in", "an", "App", "Service", "plan", ".", "Create", "or", "update", "a", "Virtual", "Network", "route", "in", "an", "App", "Service", "plan", "." ]
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/AppServicePlansInner.java#L3811-L3813
lessthanoptimal/BoofCV
main/boofcv-feature/src/main/java/boofcv/alg/feature/color/Histogram_F64.java
Histogram_F64.getDimensionIndex
public int getDimensionIndex( int dimension , int value ) { double min = valueMin[dimension]; double max = valueMax[dimension]; double fraction = ((value-min)/(max-min+1.0)); return (int)(fraction*length[dimension]); }
java
public int getDimensionIndex( int dimension , int value ) { double min = valueMin[dimension]; double max = valueMax[dimension]; double fraction = ((value-min)/(max-min+1.0)); return (int)(fraction*length[dimension]); }
[ "public", "int", "getDimensionIndex", "(", "int", "dimension", ",", "int", "value", ")", "{", "double", "min", "=", "valueMin", "[", "dimension", "]", ";", "double", "max", "=", "valueMax", "[", "dimension", "]", ";", "double", "fraction", "=", "(", "(",...
Given a value it returns the corresponding bin index in this histogram for integer values. The discretion is taken in account and 1 is added to the range. @param dimension Which dimension the value belongs to @param value Floating point value between min and max, inclusive. @return The index/bin
[ "Given", "a", "value", "it", "returns", "the", "corresponding", "bin", "index", "in", "this", "histogram", "for", "integer", "values", ".", "The", "discretion", "is", "taken", "in", "account", "and", "1", "is", "added", "to", "the", "range", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/feature/color/Histogram_F64.java#L184-L190
cchabanois/transmorph
src/main/java/net/entropysoft/transmorph/converters/MultiConverter.java
MultiConverter.addConverter
public void addConverter(int index, IConverter converter) { converterList.add(index, converter); if (converter instanceof IContainerConverter) { IContainerConverter containerConverter = (IContainerConverter) converter; if (containerConverter.getElementConverter() == null) { containerConverter.setElementConverter(elementConverter); } } }
java
public void addConverter(int index, IConverter converter) { converterList.add(index, converter); if (converter instanceof IContainerConverter) { IContainerConverter containerConverter = (IContainerConverter) converter; if (containerConverter.getElementConverter() == null) { containerConverter.setElementConverter(elementConverter); } } }
[ "public", "void", "addConverter", "(", "int", "index", ",", "IConverter", "converter", ")", "{", "converterList", ".", "add", "(", "index", ",", "converter", ")", ";", "if", "(", "converter", "instanceof", "IContainerConverter", ")", "{", "IContainerConverter", ...
add converter at given index. The index can be changed during conversion if canReorder is true @param index @param converter
[ "add", "converter", "at", "given", "index", ".", "The", "index", "can", "be", "changed", "during", "conversion", "if", "canReorder", "is", "true" ]
train
https://github.com/cchabanois/transmorph/blob/118550f30b9680a84eab7496bd8b04118740dcec/src/main/java/net/entropysoft/transmorph/converters/MultiConverter.java#L60-L68
sdaschner/jaxrs-analyzer
src/main/java/com/sebastian_daschner/jaxrs_analyzer/analysis/ProjectAnalyzer.java
ProjectAnalyzer.addJarClasses
private void addJarClasses(final Path location) { try (final JarFile jarFile = new JarFile(location.toFile())) { final Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { final JarEntry entry = entries.nextElement(); final String entryName = entry.getName(); if (entryName.endsWith(".class")) classes.add(toQualifiedClassName(entryName)); } } catch (IOException e) { throw new IllegalArgumentException("Could not read jar-file '" + location + "', reason: " + e.getMessage()); } }
java
private void addJarClasses(final Path location) { try (final JarFile jarFile = new JarFile(location.toFile())) { final Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { final JarEntry entry = entries.nextElement(); final String entryName = entry.getName(); if (entryName.endsWith(".class")) classes.add(toQualifiedClassName(entryName)); } } catch (IOException e) { throw new IllegalArgumentException("Could not read jar-file '" + location + "', reason: " + e.getMessage()); } }
[ "private", "void", "addJarClasses", "(", "final", "Path", "location", ")", "{", "try", "(", "final", "JarFile", "jarFile", "=", "new", "JarFile", "(", "location", ".", "toFile", "(", ")", ")", ")", "{", "final", "Enumeration", "<", "JarEntry", ">", "entr...
Adds all classes in the given jar-file location to the set of known classes. @param location The location of the jar-file
[ "Adds", "all", "classes", "in", "the", "given", "jar", "-", "file", "location", "to", "the", "set", "of", "known", "classes", "." ]
train
https://github.com/sdaschner/jaxrs-analyzer/blob/4ac62942202d05632977d6c14d3cd7e2d27e2b9b/src/main/java/com/sebastian_daschner/jaxrs_analyzer/analysis/ProjectAnalyzer.java#L169-L181
artikcloud/artikcloud-java
src/main/java/cloud/artik/api/UsersApi.java
UsersApi.deleteUserProperties
public PropertiesEnvelope deleteUserProperties(String userId, String aid) throws ApiException { ApiResponse<PropertiesEnvelope> resp = deleteUserPropertiesWithHttpInfo(userId, aid); return resp.getData(); }
java
public PropertiesEnvelope deleteUserProperties(String userId, String aid) throws ApiException { ApiResponse<PropertiesEnvelope> resp = deleteUserPropertiesWithHttpInfo(userId, aid); return resp.getData(); }
[ "public", "PropertiesEnvelope", "deleteUserProperties", "(", "String", "userId", ",", "String", "aid", ")", "throws", "ApiException", "{", "ApiResponse", "<", "PropertiesEnvelope", ">", "resp", "=", "deleteUserPropertiesWithHttpInfo", "(", "userId", ",", "aid", ")", ...
Delete User Application Properties Deletes a user&#39;s application properties @param userId User Id (required) @param aid Application ID (optional) @return PropertiesEnvelope @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
[ "Delete", "User", "Application", "Properties", "Deletes", "a", "user&#39", ";", "s", "application", "properties" ]
train
https://github.com/artikcloud/artikcloud-java/blob/412f447573e7796ab4f685c0bdd5eb76185a365c/src/main/java/cloud/artik/api/UsersApi.java#L265-L268
facebookarchive/hadoop-20
src/hdfs/org/apache/hadoop/hdfs/server/namenode/FSNamesystem.java
FSNamesystem.verifyNodeRegistration
private boolean verifyNodeRegistration(DatanodeRegistration nodeReg, String ipAddr) throws IOException { assert (hasWriteLock()); return inHostsList(nodeReg, ipAddr); }
java
private boolean verifyNodeRegistration(DatanodeRegistration nodeReg, String ipAddr) throws IOException { assert (hasWriteLock()); return inHostsList(nodeReg, ipAddr); }
[ "private", "boolean", "verifyNodeRegistration", "(", "DatanodeRegistration", "nodeReg", ",", "String", "ipAddr", ")", "throws", "IOException", "{", "assert", "(", "hasWriteLock", "(", ")", ")", ";", "return", "inHostsList", "(", "nodeReg", ",", "ipAddr", ")", ";...
Checks if the node is not on the hosts list. If it is not, then it will be disallowed from registering.
[ "Checks", "if", "the", "node", "is", "not", "on", "the", "hosts", "list", ".", "If", "it", "is", "not", "then", "it", "will", "be", "disallowed", "from", "registering", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/server/namenode/FSNamesystem.java#L8393-L8397
Azure/azure-sdk-for-java
appservice/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/appservice/v2018_02_01/implementation/AppServiceCertificateOrdersInner.java
AppServiceCertificateOrdersInner.retrieveSiteSeal
public SiteSealInner retrieveSiteSeal(String resourceGroupName, String certificateOrderName, SiteSealRequest siteSealRequest) { return retrieveSiteSealWithServiceResponseAsync(resourceGroupName, certificateOrderName, siteSealRequest).toBlocking().single().body(); }
java
public SiteSealInner retrieveSiteSeal(String resourceGroupName, String certificateOrderName, SiteSealRequest siteSealRequest) { return retrieveSiteSealWithServiceResponseAsync(resourceGroupName, certificateOrderName, siteSealRequest).toBlocking().single().body(); }
[ "public", "SiteSealInner", "retrieveSiteSeal", "(", "String", "resourceGroupName", ",", "String", "certificateOrderName", ",", "SiteSealRequest", "siteSealRequest", ")", "{", "return", "retrieveSiteSealWithServiceResponseAsync", "(", "resourceGroupName", ",", "certificateOrderN...
Verify domain ownership for this certificate order. Verify domain ownership for this certificate order. @param resourceGroupName Name of the resource group to which the resource belongs. @param certificateOrderName Name of the certificate order. @param siteSealRequest Site seal request. @throws IllegalArgumentException thrown if parameters fail the validation @throws DefaultErrorResponseException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the SiteSealInner object if successful.
[ "Verify", "domain", "ownership", "for", "this", "certificate", "order", ".", "Verify", "domain", "ownership", "for", "this", "certificate", "order", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/appservice/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/appservice/v2018_02_01/implementation/AppServiceCertificateOrdersInner.java#L2048-L2050
apereo/cas
support/cas-server-support-generic-remote-webflow/src/main/java/org/apereo/cas/adaptors/generic/remote/RemoteAddressAuthenticationHandler.java
RemoteAddressAuthenticationHandler.containsAddress
private static boolean containsAddress(final InetAddress network, final InetAddress netmask, final InetAddress ip) { LOGGER.debug("Checking IP address: [{}] in [{}] by [{}]", ip, network, netmask); val networkBytes = network.getAddress(); val netmaskBytes = netmask.getAddress(); val ipBytes = ip.getAddress(); /* check IPv4/v6-compatibility or parameters: */ if (networkBytes.length != netmaskBytes.length || netmaskBytes.length != ipBytes.length) { LOGGER.debug("Network address [{}], subnet mask [{}] and/or host address [{}]" + " have different sizes! (return false ...)", network, netmask, ip); return false; } /* Check if the masked network and ip addresses match: */ for (var i = 0; i < netmaskBytes.length; i++) { val mask = netmaskBytes[i] & HEX_RIGHT_SHIFT_COEFFICIENT; if ((networkBytes[i] & mask) != (ipBytes[i] & mask)) { LOGGER.debug("[{}] is not in [{}]/[{}]", ip, network, netmask); return false; } } LOGGER.debug("[{}] is in [{}]/[{}]", ip, network, netmask); return true; }
java
private static boolean containsAddress(final InetAddress network, final InetAddress netmask, final InetAddress ip) { LOGGER.debug("Checking IP address: [{}] in [{}] by [{}]", ip, network, netmask); val networkBytes = network.getAddress(); val netmaskBytes = netmask.getAddress(); val ipBytes = ip.getAddress(); /* check IPv4/v6-compatibility or parameters: */ if (networkBytes.length != netmaskBytes.length || netmaskBytes.length != ipBytes.length) { LOGGER.debug("Network address [{}], subnet mask [{}] and/or host address [{}]" + " have different sizes! (return false ...)", network, netmask, ip); return false; } /* Check if the masked network and ip addresses match: */ for (var i = 0; i < netmaskBytes.length; i++) { val mask = netmaskBytes[i] & HEX_RIGHT_SHIFT_COEFFICIENT; if ((networkBytes[i] & mask) != (ipBytes[i] & mask)) { LOGGER.debug("[{}] is not in [{}]/[{}]", ip, network, netmask); return false; } } LOGGER.debug("[{}] is in [{}]/[{}]", ip, network, netmask); return true; }
[ "private", "static", "boolean", "containsAddress", "(", "final", "InetAddress", "network", ",", "final", "InetAddress", "netmask", ",", "final", "InetAddress", "ip", ")", "{", "LOGGER", ".", "debug", "(", "\"Checking IP address: [{}] in [{}] by [{}]\"", ",", "ip", "...
Checks if a subnet contains a specific IP address. @param network The network address. @param netmask The subnet mask. @param ip The IP address to check. @return A boolean value.
[ "Checks", "if", "a", "subnet", "contains", "a", "specific", "IP", "address", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-generic-remote-webflow/src/main/java/org/apereo/cas/adaptors/generic/remote/RemoteAddressAuthenticationHandler.java#L60-L80
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/concurrent/CopyOnWriteArraySet.java
CopyOnWriteArraySet.compareSets
private static int compareSets(Object[] snapshot, Set<?> set) { // Uses O(n^2) algorithm, that is only appropriate for small // sets, which CopyOnWriteArraySets should be. // // Optimize up to O(n) if the two sets share a long common prefix, // as might happen if one set was created as a copy of the other set. final int len = snapshot.length; // Mark matched elements to avoid re-checking final boolean[] matched = new boolean[len]; // j is the largest int with matched[i] true for { i | 0 <= i < j } int j = 0; outer: for (Object x : set) { for (int i = j; i < len; i++) { if (!matched[i] && Objects.equals(x, snapshot[i])) { matched[i] = true; if (i == j) do { j++; } while (j < len && matched[j]); continue outer; } } return -1; } return (j == len) ? 0 : 1; }
java
private static int compareSets(Object[] snapshot, Set<?> set) { // Uses O(n^2) algorithm, that is only appropriate for small // sets, which CopyOnWriteArraySets should be. // // Optimize up to O(n) if the two sets share a long common prefix, // as might happen if one set was created as a copy of the other set. final int len = snapshot.length; // Mark matched elements to avoid re-checking final boolean[] matched = new boolean[len]; // j is the largest int with matched[i] true for { i | 0 <= i < j } int j = 0; outer: for (Object x : set) { for (int i = j; i < len; i++) { if (!matched[i] && Objects.equals(x, snapshot[i])) { matched[i] = true; if (i == j) do { j++; } while (j < len && matched[j]); continue outer; } } return -1; } return (j == len) ? 0 : 1; }
[ "private", "static", "int", "compareSets", "(", "Object", "[", "]", "snapshot", ",", "Set", "<", "?", ">", "set", ")", "{", "// Uses O(n^2) algorithm, that is only appropriate for small", "// sets, which CopyOnWriteArraySets should be.", "//", "// Optimize up to O(n) if the t...
Tells whether the objects in snapshot (regarded as a set) are a superset of the given set. @return -1 if snapshot is not a superset, 0 if the two sets contain precisely the same elements, and 1 if snapshot is a proper superset of the given set
[ "Tells", "whether", "the", "objects", "in", "snapshot", "(", "regarded", "as", "a", "set", ")", "are", "a", "superset", "of", "the", "given", "set", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/concurrent/CopyOnWriteArraySet.java#L290-L315