repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
218
func_name
stringlengths
4
140
whole_func_string
stringlengths
153
5.32k
language
stringclasses
1 value
func_code_string
stringlengths
72
4k
func_code_tokens
listlengths
20
832
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
listlengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
102
339
j-a-w-r/jawr-main-repo
jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/factory/util/PropertiesConfigHelper.java
PropertiesConfigHelper.getBooleanValue
public static boolean getBooleanValue(Properties prop, String name, boolean defaultValue) { """ Returns the boolean value of a property @param prop the properties @param name the name of the property @param defaultValue the default value @return false; """ String strProp = prop.getProperty(name, Boolean.toString(defaultValue)); return Boolean.valueOf(strProp); }
java
public static boolean getBooleanValue(Properties prop, String name, boolean defaultValue) { String strProp = prop.getProperty(name, Boolean.toString(defaultValue)); return Boolean.valueOf(strProp); }
[ "public", "static", "boolean", "getBooleanValue", "(", "Properties", "prop", ",", "String", "name", ",", "boolean", "defaultValue", ")", "{", "String", "strProp", "=", "prop", ".", "getProperty", "(", "name", ",", "Boolean", ".", "toString", "(", "defaultValue", ")", ")", ";", "return", "Boolean", ".", "valueOf", "(", "strProp", ")", ";", "}" ]
Returns the boolean value of a property @param prop the properties @param name the name of the property @param defaultValue the default value @return false;
[ "Returns", "the", "boolean", "value", "of", "a", "property" ]
train
https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/factory/util/PropertiesConfigHelper.java#L386-L389
google/error-prone-javac
src/jdk.compiler/share/classes/com/sun/tools/javac/comp/TransTypes.java
TransTypes.retype
JCExpression retype(JCExpression tree, Type erasedType, Type target) { """ Given an erased reference type, assume this type as the tree's type. Then, coerce to some given target type unless target type is null. This operation is used in situations like the following: <pre>{@code class Cell<A> { A value; } ... Cell<Integer> cell; Integer x = cell.value; }</pre> Since the erasure of Cell.value is Object, but the type of cell.value in the assignment is Integer, we need to adjust the original type of cell.value to Object, and insert a cast to Integer. That is, the last assignment becomes: <pre>{@code Integer x = (Integer)cell.value; }</pre> @param tree The expression tree whose type might need adjustment. @param erasedType The expression's type after erasure. @param target The target type, which is usually the erasure of the expression's original type. """ // System.err.println("retype " + tree + " to " + erasedType);//DEBUG if (!erasedType.isPrimitive()) { if (target != null && target.isPrimitive()) { target = erasure(tree.type); } tree.type = erasedType; if (target != null) { return coerce(tree, target); } } return tree; }
java
JCExpression retype(JCExpression tree, Type erasedType, Type target) { // System.err.println("retype " + tree + " to " + erasedType);//DEBUG if (!erasedType.isPrimitive()) { if (target != null && target.isPrimitive()) { target = erasure(tree.type); } tree.type = erasedType; if (target != null) { return coerce(tree, target); } } return tree; }
[ "JCExpression", "retype", "(", "JCExpression", "tree", ",", "Type", "erasedType", ",", "Type", "target", ")", "{", "// System.err.println(\"retype \" + tree + \" to \" + erasedType);//DEBUG", "if", "(", "!", "erasedType", ".", "isPrimitive", "(", ")", ")", "{", "if", "(", "target", "!=", "null", "&&", "target", ".", "isPrimitive", "(", ")", ")", "{", "target", "=", "erasure", "(", "tree", ".", "type", ")", ";", "}", "tree", ".", "type", "=", "erasedType", ";", "if", "(", "target", "!=", "null", ")", "{", "return", "coerce", "(", "tree", ",", "target", ")", ";", "}", "}", "return", "tree", ";", "}" ]
Given an erased reference type, assume this type as the tree's type. Then, coerce to some given target type unless target type is null. This operation is used in situations like the following: <pre>{@code class Cell<A> { A value; } ... Cell<Integer> cell; Integer x = cell.value; }</pre> Since the erasure of Cell.value is Object, but the type of cell.value in the assignment is Integer, we need to adjust the original type of cell.value to Object, and insert a cast to Integer. That is, the last assignment becomes: <pre>{@code Integer x = (Integer)cell.value; }</pre> @param tree The expression tree whose type might need adjustment. @param erasedType The expression's type after erasure. @param target The target type, which is usually the erasure of the expression's original type.
[ "Given", "an", "erased", "reference", "type", "assume", "this", "type", "as", "the", "tree", "s", "type", ".", "Then", "coerce", "to", "some", "given", "target", "type", "unless", "target", "type", "is", "null", ".", "This", "operation", "is", "used", "in", "situations", "like", "the", "following", ":" ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/TransTypes.java#L175-L187
Azure/azure-sdk-for-java
network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/ExpressRouteCrossConnectionsInner.java
ExpressRouteCrossConnectionsInner.listRoutesTableSummaryAsync
public Observable<ExpressRouteCrossConnectionsRoutesTableSummaryListResultInner> listRoutesTableSummaryAsync(String resourceGroupName, String crossConnectionName, String peeringName, String devicePath) { """ Gets the route table summary associated with the express route cross connection in a resource group. @param resourceGroupName The name of the resource group. @param crossConnectionName The name of the ExpressRouteCrossConnection. @param peeringName The name of the peering. @param devicePath The path of the device. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request """ return listRoutesTableSummaryWithServiceResponseAsync(resourceGroupName, crossConnectionName, peeringName, devicePath).map(new Func1<ServiceResponse<ExpressRouteCrossConnectionsRoutesTableSummaryListResultInner>, ExpressRouteCrossConnectionsRoutesTableSummaryListResultInner>() { @Override public ExpressRouteCrossConnectionsRoutesTableSummaryListResultInner call(ServiceResponse<ExpressRouteCrossConnectionsRoutesTableSummaryListResultInner> response) { return response.body(); } }); }
java
public Observable<ExpressRouteCrossConnectionsRoutesTableSummaryListResultInner> listRoutesTableSummaryAsync(String resourceGroupName, String crossConnectionName, String peeringName, String devicePath) { return listRoutesTableSummaryWithServiceResponseAsync(resourceGroupName, crossConnectionName, peeringName, devicePath).map(new Func1<ServiceResponse<ExpressRouteCrossConnectionsRoutesTableSummaryListResultInner>, ExpressRouteCrossConnectionsRoutesTableSummaryListResultInner>() { @Override public ExpressRouteCrossConnectionsRoutesTableSummaryListResultInner call(ServiceResponse<ExpressRouteCrossConnectionsRoutesTableSummaryListResultInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "ExpressRouteCrossConnectionsRoutesTableSummaryListResultInner", ">", "listRoutesTableSummaryAsync", "(", "String", "resourceGroupName", ",", "String", "crossConnectionName", ",", "String", "peeringName", ",", "String", "devicePath", ")", "{", "return", "listRoutesTableSummaryWithServiceResponseAsync", "(", "resourceGroupName", ",", "crossConnectionName", ",", "peeringName", ",", "devicePath", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "ExpressRouteCrossConnectionsRoutesTableSummaryListResultInner", ">", ",", "ExpressRouteCrossConnectionsRoutesTableSummaryListResultInner", ">", "(", ")", "{", "@", "Override", "public", "ExpressRouteCrossConnectionsRoutesTableSummaryListResultInner", "call", "(", "ServiceResponse", "<", "ExpressRouteCrossConnectionsRoutesTableSummaryListResultInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Gets the route table summary associated with the express route cross connection in a resource group. @param resourceGroupName The name of the resource group. @param crossConnectionName The name of the ExpressRouteCrossConnection. @param peeringName The name of the peering. @param devicePath The path of the device. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request
[ "Gets", "the", "route", "table", "summary", "associated", "with", "the", "express", "route", "cross", "connection", "in", "a", "resource", "group", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/ExpressRouteCrossConnectionsInner.java#L1135-L1142
looly/hutool
hutool-http/src/main/java/cn/hutool/http/HttpUtil.java
HttpUtil.downloadFile
public static long downloadFile(String url, File destFile, StreamProgress streamProgress) { """ 下载远程文件 @param url 请求的url @param destFile 目标文件或目录,当为目录时,取URL中的文件名,取不到使用编码后的URL做为文件名 @param streamProgress 进度条 @return 文件大小 """ return downloadFile(url, destFile, -1, streamProgress); }
java
public static long downloadFile(String url, File destFile, StreamProgress streamProgress) { return downloadFile(url, destFile, -1, streamProgress); }
[ "public", "static", "long", "downloadFile", "(", "String", "url", ",", "File", "destFile", ",", "StreamProgress", "streamProgress", ")", "{", "return", "downloadFile", "(", "url", ",", "destFile", ",", "-", "1", ",", "streamProgress", ")", ";", "}" ]
下载远程文件 @param url 请求的url @param destFile 目标文件或目录,当为目录时,取URL中的文件名,取不到使用编码后的URL做为文件名 @param streamProgress 进度条 @return 文件大小
[ "下载远程文件" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-http/src/main/java/cn/hutool/http/HttpUtil.java#L290-L292
VoltDB/voltdb
src/hsqldb19b3/org/hsqldb_voltpatches/persist/LockFile.java
LockFile.writeHeartbeat
private final void writeHeartbeat() throws LockFile.FileSecurityException, LockFile.UnexpectedEndOfFileException, LockFile.UnexpectedFileIOException { """ Writes the current hearbeat timestamp value to this object's lock file. <p> @throws FileSecurityException possibly never (seek and write are native methods whose JavaDoc entries do not actually specifiy throwing <tt>SecurityException</tt>). However, it is conceivable that these native methods may, in turn, access Java methods that do throw <tt>SecurityException</tt>. In this case, a <tt>SecurityException</tt> might be thrown if a required system property value cannot be accessed, or if a security manager exists and its <tt>{@link java.lang.SecurityManager#checkWrite(java.io.FileDescriptor)}</tt> method denies write access to the file @throws UnexpectedEndOfFileException if an end of file exception is thrown while attepting to write the heartbeat timestamp value to the target file (typically, this cannot happen, but the case is included to distiguish it from the general IOException case). @throws UnexpectedFileIOException if the current heartbeat timestamp value cannot be written due to an underlying I/O error """ try { raf.seek(MAGIC.length); raf.writeLong(System.currentTimeMillis()); } catch (SecurityException ex) { throw new FileSecurityException(this, "writeHeartbeat", ex); } catch (EOFException ex) { throw new UnexpectedEndOfFileException(this, "writeHeartbeat", ex); } catch (IOException ex) { throw new UnexpectedFileIOException(this, "writeHeartbeat", ex); } }
java
private final void writeHeartbeat() throws LockFile.FileSecurityException, LockFile.UnexpectedEndOfFileException, LockFile.UnexpectedFileIOException { try { raf.seek(MAGIC.length); raf.writeLong(System.currentTimeMillis()); } catch (SecurityException ex) { throw new FileSecurityException(this, "writeHeartbeat", ex); } catch (EOFException ex) { throw new UnexpectedEndOfFileException(this, "writeHeartbeat", ex); } catch (IOException ex) { throw new UnexpectedFileIOException(this, "writeHeartbeat", ex); } }
[ "private", "final", "void", "writeHeartbeat", "(", ")", "throws", "LockFile", ".", "FileSecurityException", ",", "LockFile", ".", "UnexpectedEndOfFileException", ",", "LockFile", ".", "UnexpectedFileIOException", "{", "try", "{", "raf", ".", "seek", "(", "MAGIC", ".", "length", ")", ";", "raf", ".", "writeLong", "(", "System", ".", "currentTimeMillis", "(", ")", ")", ";", "}", "catch", "(", "SecurityException", "ex", ")", "{", "throw", "new", "FileSecurityException", "(", "this", ",", "\"writeHeartbeat\"", ",", "ex", ")", ";", "}", "catch", "(", "EOFException", "ex", ")", "{", "throw", "new", "UnexpectedEndOfFileException", "(", "this", ",", "\"writeHeartbeat\"", ",", "ex", ")", ";", "}", "catch", "(", "IOException", "ex", ")", "{", "throw", "new", "UnexpectedFileIOException", "(", "this", ",", "\"writeHeartbeat\"", ",", "ex", ")", ";", "}", "}" ]
Writes the current hearbeat timestamp value to this object's lock file. <p> @throws FileSecurityException possibly never (seek and write are native methods whose JavaDoc entries do not actually specifiy throwing <tt>SecurityException</tt>). However, it is conceivable that these native methods may, in turn, access Java methods that do throw <tt>SecurityException</tt>. In this case, a <tt>SecurityException</tt> might be thrown if a required system property value cannot be accessed, or if a security manager exists and its <tt>{@link java.lang.SecurityManager#checkWrite(java.io.FileDescriptor)}</tt> method denies write access to the file @throws UnexpectedEndOfFileException if an end of file exception is thrown while attepting to write the heartbeat timestamp value to the target file (typically, this cannot happen, but the case is included to distiguish it from the general IOException case). @throws UnexpectedFileIOException if the current heartbeat timestamp value cannot be written due to an underlying I/O error
[ "Writes", "the", "current", "hearbeat", "timestamp", "value", "to", "this", "object", "s", "lock", "file", ".", "<p", ">" ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/persist/LockFile.java#L1259-L1274
ibm-bluemix-mobile-services/bms-clientsdk-android-core
lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/security/mca/api/MCAAuthorizationManager.java
MCAAuthorizationManager.obtainAuthorization
public synchronized void obtainAuthorization(Context context, ResponseListener listener, Object... params) { """ Invoke process for obtaining authorization header. during this process @param context Android Activity that will handle the authorization (like facebook or google) @param listener Response listener """ authorizationProcessManager.startAuthorizationProcess(context, listener); }
java
public synchronized void obtainAuthorization(Context context, ResponseListener listener, Object... params) { authorizationProcessManager.startAuthorizationProcess(context, listener); }
[ "public", "synchronized", "void", "obtainAuthorization", "(", "Context", "context", ",", "ResponseListener", "listener", ",", "Object", "...", "params", ")", "{", "authorizationProcessManager", ".", "startAuthorizationProcess", "(", "context", ",", "listener", ")", ";", "}" ]
Invoke process for obtaining authorization header. during this process @param context Android Activity that will handle the authorization (like facebook or google) @param listener Response listener
[ "Invoke", "process", "for", "obtaining", "authorization", "header", ".", "during", "this", "process" ]
train
https://github.com/ibm-bluemix-mobile-services/bms-clientsdk-android-core/blob/8db4f00d0d564792397bfc0e5bd57d52a238b858/lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/security/mca/api/MCAAuthorizationManager.java#L154-L156
kaazing/java.client
amqp-0-9-1/amqp/src/main/java/org/kaazing/net/ws/amqp/AmqpClient.java
AmqpClient.tuneOkConnection
AmqpClient tuneOkConnection(int channelMax, int frameMax, int heartbeat) { """ Sends a TuneOkConnection to server. @param channelMax @param frameMax @param heartbeat @return AmqpClient """ this.tuneOkConnection(channelMax, frameMax, heartbeat, null, null); return this; }
java
AmqpClient tuneOkConnection(int channelMax, int frameMax, int heartbeat) { this.tuneOkConnection(channelMax, frameMax, heartbeat, null, null); return this; }
[ "AmqpClient", "tuneOkConnection", "(", "int", "channelMax", ",", "int", "frameMax", ",", "int", "heartbeat", ")", "{", "this", ".", "tuneOkConnection", "(", "channelMax", ",", "frameMax", ",", "heartbeat", ",", "null", ",", "null", ")", ";", "return", "this", ";", "}" ]
Sends a TuneOkConnection to server. @param channelMax @param frameMax @param heartbeat @return AmqpClient
[ "Sends", "a", "TuneOkConnection", "to", "server", "." ]
train
https://github.com/kaazing/java.client/blob/25ad2ae5bb24aa9d6b79400fce649b518dcfbe26/amqp-0-9-1/amqp/src/main/java/org/kaazing/net/ws/amqp/AmqpClient.java#L814-L817
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/reflect/FieldUtils.java
FieldUtils.readDeclaredStaticField
public static Object readDeclaredStaticField(final Class<?> cls, final String fieldName, final boolean forceAccess) throws IllegalAccessException { """ Gets the value of a {@code static} {@link Field} by name. Only the specified class will be considered. @param cls the {@link Class} to reflect, must not be {@code null} @param fieldName the field name to obtain @param forceAccess whether to break scope restrictions using the {@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} method. {@code false} will only match {@code public} fields. @return the Field object @throws IllegalArgumentException if the class is {@code null}, or the field name is blank or empty, is not {@code static}, or could not be found @throws IllegalAccessException if the field is not made accessible """ final Field field = getDeclaredField(cls, fieldName, forceAccess); Validate.isTrue(field != null, "Cannot locate declared field %s.%s", cls.getName(), fieldName); // already forced access above, don't repeat it here: return readStaticField(field, false); }
java
public static Object readDeclaredStaticField(final Class<?> cls, final String fieldName, final boolean forceAccess) throws IllegalAccessException { final Field field = getDeclaredField(cls, fieldName, forceAccess); Validate.isTrue(field != null, "Cannot locate declared field %s.%s", cls.getName(), fieldName); // already forced access above, don't repeat it here: return readStaticField(field, false); }
[ "public", "static", "Object", "readDeclaredStaticField", "(", "final", "Class", "<", "?", ">", "cls", ",", "final", "String", "fieldName", ",", "final", "boolean", "forceAccess", ")", "throws", "IllegalAccessException", "{", "final", "Field", "field", "=", "getDeclaredField", "(", "cls", ",", "fieldName", ",", "forceAccess", ")", ";", "Validate", ".", "isTrue", "(", "field", "!=", "null", ",", "\"Cannot locate declared field %s.%s\"", ",", "cls", ".", "getName", "(", ")", ",", "fieldName", ")", ";", "// already forced access above, don't repeat it here:", "return", "readStaticField", "(", "field", ",", "false", ")", ";", "}" ]
Gets the value of a {@code static} {@link Field} by name. Only the specified class will be considered. @param cls the {@link Class} to reflect, must not be {@code null} @param fieldName the field name to obtain @param forceAccess whether to break scope restrictions using the {@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} method. {@code false} will only match {@code public} fields. @return the Field object @throws IllegalArgumentException if the class is {@code null}, or the field name is blank or empty, is not {@code static}, or could not be found @throws IllegalAccessException if the field is not made accessible
[ "Gets", "the", "value", "of", "a", "{", "@code", "static", "}", "{", "@link", "Field", "}", "by", "name", ".", "Only", "the", "specified", "class", "will", "be", "considered", "." ]
train
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/reflect/FieldUtils.java#L382-L387
google/error-prone-javac
src/jdk.compiler/share/classes/com/sun/source/util/SimpleDocTreeVisitor.java
SimpleDocTreeVisitor.visitErroneous
@Override public R visitErroneous(ErroneousTree node, P p) { """ {@inheritDoc} This implementation calls {@code defaultAction}. @param node {@inheritDoc} @param p {@inheritDoc} @return the result of {@code defaultAction} """ return defaultAction(node, p); }
java
@Override public R visitErroneous(ErroneousTree node, P p) { return defaultAction(node, p); }
[ "@", "Override", "public", "R", "visitErroneous", "(", "ErroneousTree", "node", ",", "P", "p", ")", "{", "return", "defaultAction", "(", "node", ",", "p", ")", ";", "}" ]
{@inheritDoc} This implementation calls {@code defaultAction}. @param node {@inheritDoc} @param p {@inheritDoc} @return the result of {@code defaultAction}
[ "{", "@inheritDoc", "}", "This", "implementation", "calls", "{", "@code", "defaultAction", "}", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/source/util/SimpleDocTreeVisitor.java#L201-L204
Omertron/api-themoviedb
src/main/java/com/omertron/themoviedbapi/methods/TmdbCompanies.java
TmdbCompanies.getCompanyInfo
public Company getCompanyInfo(int companyId) throws MovieDbException { """ This method is used to retrieve the basic information about a production company on TMDb. @param companyId @return @throws MovieDbException """ TmdbParameters parameters = new TmdbParameters(); parameters.add(Param.ID, companyId); URL url = new ApiUrl(apiKey, MethodBase.COMPANY).buildUrl(parameters); String webpage = httpTools.getRequest(url); try { return MAPPER.readValue(webpage, Company.class); } catch (IOException ex) { throw new MovieDbException(ApiExceptionType.MAPPING_FAILED, "Failed to get company information", url, ex); } }
java
public Company getCompanyInfo(int companyId) throws MovieDbException { TmdbParameters parameters = new TmdbParameters(); parameters.add(Param.ID, companyId); URL url = new ApiUrl(apiKey, MethodBase.COMPANY).buildUrl(parameters); String webpage = httpTools.getRequest(url); try { return MAPPER.readValue(webpage, Company.class); } catch (IOException ex) { throw new MovieDbException(ApiExceptionType.MAPPING_FAILED, "Failed to get company information", url, ex); } }
[ "public", "Company", "getCompanyInfo", "(", "int", "companyId", ")", "throws", "MovieDbException", "{", "TmdbParameters", "parameters", "=", "new", "TmdbParameters", "(", ")", ";", "parameters", ".", "add", "(", "Param", ".", "ID", ",", "companyId", ")", ";", "URL", "url", "=", "new", "ApiUrl", "(", "apiKey", ",", "MethodBase", ".", "COMPANY", ")", ".", "buildUrl", "(", "parameters", ")", ";", "String", "webpage", "=", "httpTools", ".", "getRequest", "(", "url", ")", ";", "try", "{", "return", "MAPPER", ".", "readValue", "(", "webpage", ",", "Company", ".", "class", ")", ";", "}", "catch", "(", "IOException", "ex", ")", "{", "throw", "new", "MovieDbException", "(", "ApiExceptionType", ".", "MAPPING_FAILED", ",", "\"Failed to get company information\"", ",", "url", ",", "ex", ")", ";", "}", "}" ]
This method is used to retrieve the basic information about a production company on TMDb. @param companyId @return @throws MovieDbException
[ "This", "method", "is", "used", "to", "retrieve", "the", "basic", "information", "about", "a", "production", "company", "on", "TMDb", "." ]
train
https://github.com/Omertron/api-themoviedb/blob/bf132d7c7271734e13b58ba3bc92bba46f220118/src/main/java/com/omertron/themoviedbapi/methods/TmdbCompanies.java#L61-L73
matthewhorridge/owlapi-gwt
owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLDataHasValueImpl_CustomFieldSerializer.java
OWLDataHasValueImpl_CustomFieldSerializer.serializeInstance
@Override public void serializeInstance(SerializationStreamWriter streamWriter, OWLDataHasValueImpl instance) throws SerializationException { """ Serializes the content of the object into the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter}. @param streamWriter the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter} to write the object's content to @param instance the object instance to serialize @throws com.google.gwt.user.client.rpc.SerializationException if the serialization operation is not successful """ serialize(streamWriter, instance); }
java
@Override public void serializeInstance(SerializationStreamWriter streamWriter, OWLDataHasValueImpl instance) throws SerializationException { serialize(streamWriter, instance); }
[ "@", "Override", "public", "void", "serializeInstance", "(", "SerializationStreamWriter", "streamWriter", ",", "OWLDataHasValueImpl", "instance", ")", "throws", "SerializationException", "{", "serialize", "(", "streamWriter", ",", "instance", ")", ";", "}" ]
Serializes the content of the object into the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter}. @param streamWriter the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter} to write the object's content to @param instance the object instance to serialize @throws com.google.gwt.user.client.rpc.SerializationException if the serialization operation is not successful
[ "Serializes", "the", "content", "of", "the", "object", "into", "the", "{", "@link", "com", ".", "google", ".", "gwt", ".", "user", ".", "client", ".", "rpc", ".", "SerializationStreamWriter", "}", "." ]
train
https://github.com/matthewhorridge/owlapi-gwt/blob/7ab975fb6cef3c8947099983551672a3b5d4e2fd/owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLDataHasValueImpl_CustomFieldSerializer.java#L72-L75
fedups/com.obdobion.algebrain
src/main/java/com/obdobion/algebrain/Function.java
Function.updateParameterCount
public void updateParameterCount(final EquPart[] equParts, final int myLocInArray) { """ <p> updateParameterCount. </p> @param equParts an array of {@link com.obdobion.algebrain.EquPart} objects. @param myLocInArray a int. """ setParameterCount(0); for (int p = myLocInArray + 1; p < equParts.length; p++) { final EquPart part = equParts[p]; if (part.getLevel() <= getLevel()) break; if ((part.getLevel() == (getLevel() + 1)) && part instanceof OpComma) setParameterCount(getParameterCount() + 1); } if (getParameterCount() > 0) setParameterCount(getParameterCount() + 1); }
java
public void updateParameterCount(final EquPart[] equParts, final int myLocInArray) { setParameterCount(0); for (int p = myLocInArray + 1; p < equParts.length; p++) { final EquPart part = equParts[p]; if (part.getLevel() <= getLevel()) break; if ((part.getLevel() == (getLevel() + 1)) && part instanceof OpComma) setParameterCount(getParameterCount() + 1); } if (getParameterCount() > 0) setParameterCount(getParameterCount() + 1); }
[ "public", "void", "updateParameterCount", "(", "final", "EquPart", "[", "]", "equParts", ",", "final", "int", "myLocInArray", ")", "{", "setParameterCount", "(", "0", ")", ";", "for", "(", "int", "p", "=", "myLocInArray", "+", "1", ";", "p", "<", "equParts", ".", "length", ";", "p", "++", ")", "{", "final", "EquPart", "part", "=", "equParts", "[", "p", "]", ";", "if", "(", "part", ".", "getLevel", "(", ")", "<=", "getLevel", "(", ")", ")", "break", ";", "if", "(", "(", "part", ".", "getLevel", "(", ")", "==", "(", "getLevel", "(", ")", "+", "1", ")", ")", "&&", "part", "instanceof", "OpComma", ")", "setParameterCount", "(", "getParameterCount", "(", ")", "+", "1", ")", ";", "}", "if", "(", "getParameterCount", "(", ")", ">", "0", ")", "setParameterCount", "(", "getParameterCount", "(", ")", "+", "1", ")", ";", "}" ]
<p> updateParameterCount. </p> @param equParts an array of {@link com.obdobion.algebrain.EquPart} objects. @param myLocInArray a int.
[ "<p", ">", "updateParameterCount", ".", "<", "/", "p", ">" ]
train
https://github.com/fedups/com.obdobion.algebrain/blob/d0adaa9fbbba907bdcf820961e9058b0d2b15a8a/src/main/java/com/obdobion/algebrain/Function.java#L80-L97
alkacon/opencms-core
src/org/opencms/i18n/CmsLocaleManager.java
CmsLocaleManager.getLocales
public static List<Locale> getLocales(String localeNames) { """ Returns a List of locales from a comma-separated string of locale names.<p> @param localeNames a comma-separated string of locale names @return a List of locales derived from the given locale names """ if (localeNames == null) { return null; } return getLocales(CmsStringUtil.splitAsList(localeNames, ',')); }
java
public static List<Locale> getLocales(String localeNames) { if (localeNames == null) { return null; } return getLocales(CmsStringUtil.splitAsList(localeNames, ',')); }
[ "public", "static", "List", "<", "Locale", ">", "getLocales", "(", "String", "localeNames", ")", "{", "if", "(", "localeNames", "==", "null", ")", "{", "return", "null", ";", "}", "return", "getLocales", "(", "CmsStringUtil", ".", "splitAsList", "(", "localeNames", ",", "'", "'", ")", ")", ";", "}" ]
Returns a List of locales from a comma-separated string of locale names.<p> @param localeNames a comma-separated string of locale names @return a List of locales derived from the given locale names
[ "Returns", "a", "List", "of", "locales", "from", "a", "comma", "-", "separated", "string", "of", "locale", "names", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/i18n/CmsLocaleManager.java#L256-L262
structurizr/java
structurizr-core/src/com/structurizr/documentation/Documentation.java
Documentation.addDecision
public Decision addDecision(String id, Date date, String title, DecisionStatus status, Format format, String content) { """ Adds a new decision to this workspace. @param id the ID of the decision @param date the date of the decision @param title the title of the decision @param status the status of the decision @param format the format of the decision content @param content the content of the decision @return a Decision object """ return addDecision(null, id, date, title, status, format, content); }
java
public Decision addDecision(String id, Date date, String title, DecisionStatus status, Format format, String content) { return addDecision(null, id, date, title, status, format, content); }
[ "public", "Decision", "addDecision", "(", "String", "id", ",", "Date", "date", ",", "String", "title", ",", "DecisionStatus", "status", ",", "Format", "format", ",", "String", "content", ")", "{", "return", "addDecision", "(", "null", ",", "id", ",", "date", ",", "title", ",", "status", ",", "format", ",", "content", ")", ";", "}" ]
Adds a new decision to this workspace. @param id the ID of the decision @param date the date of the decision @param title the title of the decision @param status the status of the decision @param format the format of the decision content @param content the content of the decision @return a Decision object
[ "Adds", "a", "new", "decision", "to", "this", "workspace", "." ]
train
https://github.com/structurizr/java/blob/4b204f077877a24bcac363f5ecf0e129a0f9f4c5/structurizr-core/src/com/structurizr/documentation/Documentation.java#L131-L133
couchbase/couchbase-java-client
src/main/java/com/couchbase/client/java/query/dsl/functions/PatternMatchingFunctions.java
PatternMatchingFunctions.regexpContains
public static Expression regexpContains(String expression, String pattern) { """ Returned expression results in True if the string value contains the regular expression pattern. """ return regexpContains(x(expression), pattern); }
java
public static Expression regexpContains(String expression, String pattern) { return regexpContains(x(expression), pattern); }
[ "public", "static", "Expression", "regexpContains", "(", "String", "expression", ",", "String", "pattern", ")", "{", "return", "regexpContains", "(", "x", "(", "expression", ")", ",", "pattern", ")", ";", "}" ]
Returned expression results in True if the string value contains the regular expression pattern.
[ "Returned", "expression", "results", "in", "True", "if", "the", "string", "value", "contains", "the", "regular", "expression", "pattern", "." ]
train
https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/query/dsl/functions/PatternMatchingFunctions.java#L49-L51
m-m-m/util
datatype/src/main/java/net/sf/mmm/util/datatype/api/color/GenericColor.java
GenericColor.valueOf
public static GenericColor valueOf(Hue hue, Saturation saturation, Brightness brightness, Alpha alpha) { """ Creates a {@link GenericColor} from the given {@link Segment}s of {@link ColorModel#HSB}. @param hue is the {@link Hue} part. @param saturation is the {@link Saturation} part. @param brightness is the {@link Brightness} part. @param alpha is the {@link Alpha} value. @return the {@link GenericColor}. """ Objects.requireNonNull(hue, "hue"); Objects.requireNonNull(saturation, "saturation"); Objects.requireNonNull(brightness, "brightness"); Objects.requireNonNull(alpha, "alpha"); GenericColor genericColor = new GenericColor(); genericColor.hue = hue; genericColor.saturationHsb = saturation; genericColor.brightness = brightness; genericColor.alpha = alpha; double b = brightness.getValueAsFactor(); double chroma = b * saturation.getValueAsFactor(); genericColor.chroma = new Chroma(chroma); double min = b - chroma; double lightness = (min + b) / 2; genericColor.lightness = new Lightness(lightness); double saturationHsl = calculateSaturationHsl(chroma, lightness); genericColor.saturationHsl = new Saturation(saturationHsl); calculateRgb(genericColor, hue, min, chroma); return genericColor; }
java
public static GenericColor valueOf(Hue hue, Saturation saturation, Brightness brightness, Alpha alpha) { Objects.requireNonNull(hue, "hue"); Objects.requireNonNull(saturation, "saturation"); Objects.requireNonNull(brightness, "brightness"); Objects.requireNonNull(alpha, "alpha"); GenericColor genericColor = new GenericColor(); genericColor.hue = hue; genericColor.saturationHsb = saturation; genericColor.brightness = brightness; genericColor.alpha = alpha; double b = brightness.getValueAsFactor(); double chroma = b * saturation.getValueAsFactor(); genericColor.chroma = new Chroma(chroma); double min = b - chroma; double lightness = (min + b) / 2; genericColor.lightness = new Lightness(lightness); double saturationHsl = calculateSaturationHsl(chroma, lightness); genericColor.saturationHsl = new Saturation(saturationHsl); calculateRgb(genericColor, hue, min, chroma); return genericColor; }
[ "public", "static", "GenericColor", "valueOf", "(", "Hue", "hue", ",", "Saturation", "saturation", ",", "Brightness", "brightness", ",", "Alpha", "alpha", ")", "{", "Objects", ".", "requireNonNull", "(", "hue", ",", "\"hue\"", ")", ";", "Objects", ".", "requireNonNull", "(", "saturation", ",", "\"saturation\"", ")", ";", "Objects", ".", "requireNonNull", "(", "brightness", ",", "\"brightness\"", ")", ";", "Objects", ".", "requireNonNull", "(", "alpha", ",", "\"alpha\"", ")", ";", "GenericColor", "genericColor", "=", "new", "GenericColor", "(", ")", ";", "genericColor", ".", "hue", "=", "hue", ";", "genericColor", ".", "saturationHsb", "=", "saturation", ";", "genericColor", ".", "brightness", "=", "brightness", ";", "genericColor", ".", "alpha", "=", "alpha", ";", "double", "b", "=", "brightness", ".", "getValueAsFactor", "(", ")", ";", "double", "chroma", "=", "b", "*", "saturation", ".", "getValueAsFactor", "(", ")", ";", "genericColor", ".", "chroma", "=", "new", "Chroma", "(", "chroma", ")", ";", "double", "min", "=", "b", "-", "chroma", ";", "double", "lightness", "=", "(", "min", "+", "b", ")", "/", "2", ";", "genericColor", ".", "lightness", "=", "new", "Lightness", "(", "lightness", ")", ";", "double", "saturationHsl", "=", "calculateSaturationHsl", "(", "chroma", ",", "lightness", ")", ";", "genericColor", ".", "saturationHsl", "=", "new", "Saturation", "(", "saturationHsl", ")", ";", "calculateRgb", "(", "genericColor", ",", "hue", ",", "min", ",", "chroma", ")", ";", "return", "genericColor", ";", "}" ]
Creates a {@link GenericColor} from the given {@link Segment}s of {@link ColorModel#HSB}. @param hue is the {@link Hue} part. @param saturation is the {@link Saturation} part. @param brightness is the {@link Brightness} part. @param alpha is the {@link Alpha} value. @return the {@link GenericColor}.
[ "Creates", "a", "{", "@link", "GenericColor", "}", "from", "the", "given", "{", "@link", "Segment", "}", "s", "of", "{", "@link", "ColorModel#HSB", "}", "." ]
train
https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/datatype/src/main/java/net/sf/mmm/util/datatype/api/color/GenericColor.java#L264-L285
denisneuling/apitrary.jar
apitrary-orm/apitrary-orm-core/src/main/java/com/apitrary/orm/core/unmarshalling/JsonResponseConsumer.java
JsonResponseConsumer.onDouble
protected void onDouble(Double floating, String fieldName, JsonParser jp) { """ <p> onDouble. </p> @param floating a {@link java.lang.Double} object. @param fieldName a {@link java.lang.String} object. @param jp a {@link org.codehaus.jackson.JsonParser} object. """ log.trace(fieldName + " " + floating); }
java
protected void onDouble(Double floating, String fieldName, JsonParser jp) { log.trace(fieldName + " " + floating); }
[ "protected", "void", "onDouble", "(", "Double", "floating", ",", "String", "fieldName", ",", "JsonParser", "jp", ")", "{", "log", ".", "trace", "(", "fieldName", "+", "\" \"", "+", "floating", ")", ";", "}" ]
<p> onDouble. </p> @param floating a {@link java.lang.Double} object. @param fieldName a {@link java.lang.String} object. @param jp a {@link org.codehaus.jackson.JsonParser} object.
[ "<p", ">", "onDouble", ".", "<", "/", "p", ">" ]
train
https://github.com/denisneuling/apitrary.jar/blob/b7f639a1e735c60ba2b1b62851926757f5de8628/apitrary-orm/apitrary-orm-core/src/main/java/com/apitrary/orm/core/unmarshalling/JsonResponseConsumer.java#L250-L252
liferay/com-liferay-commerce
commerce-user-segment-service/src/main/java/com/liferay/commerce/user/segment/service/persistence/impl/CommerceUserSegmentEntryPersistenceImpl.java
CommerceUserSegmentEntryPersistenceImpl.findByGroupId
@Override public List<CommerceUserSegmentEntry> findByGroupId(long groupId, int start, int end) { """ Returns a range of all the commerce user segment entries where groupId = &#63;. <p> Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommerceUserSegmentEntryModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. </p> @param groupId the group ID @param start the lower bound of the range of commerce user segment entries @param end the upper bound of the range of commerce user segment entries (not inclusive) @return the range of matching commerce user segment entries """ return findByGroupId(groupId, start, end, null); }
java
@Override public List<CommerceUserSegmentEntry> findByGroupId(long groupId, int start, int end) { return findByGroupId(groupId, start, end, null); }
[ "@", "Override", "public", "List", "<", "CommerceUserSegmentEntry", ">", "findByGroupId", "(", "long", "groupId", ",", "int", "start", ",", "int", "end", ")", "{", "return", "findByGroupId", "(", "groupId", ",", "start", ",", "end", ",", "null", ")", ";", "}" ]
Returns a range of all the commerce user segment entries where groupId = &#63;. <p> Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommerceUserSegmentEntryModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. </p> @param groupId the group ID @param start the lower bound of the range of commerce user segment entries @param end the upper bound of the range of commerce user segment entries (not inclusive) @return the range of matching commerce user segment entries
[ "Returns", "a", "range", "of", "all", "the", "commerce", "user", "segment", "entries", "where", "groupId", "=", "&#63", ";", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-user-segment-service/src/main/java/com/liferay/commerce/user/segment/service/persistence/impl/CommerceUserSegmentEntryPersistenceImpl.java#L144-L148
neo4j-contrib/neo4j-apoc-procedures
src/main/java/apoc/schema/Schemas.java
Schemas.constraintsExists
private Boolean constraintsExists(String labelName, List<String> propertyNames) { """ Checks if a constraint exists for a given label and a list of properties This method checks for constraints on node @param labelName @param propertyNames @return true if the constraint exists otherwise it returns false """ Schema schema = db.schema(); for (ConstraintDefinition constraintDefinition : Iterables.asList(schema.getConstraints(Label.label(labelName)))) { List<String> properties = Iterables.asList(constraintDefinition.getPropertyKeys()); if (properties.equals(propertyNames)) { return true; } } return false; }
java
private Boolean constraintsExists(String labelName, List<String> propertyNames) { Schema schema = db.schema(); for (ConstraintDefinition constraintDefinition : Iterables.asList(schema.getConstraints(Label.label(labelName)))) { List<String> properties = Iterables.asList(constraintDefinition.getPropertyKeys()); if (properties.equals(propertyNames)) { return true; } } return false; }
[ "private", "Boolean", "constraintsExists", "(", "String", "labelName", ",", "List", "<", "String", ">", "propertyNames", ")", "{", "Schema", "schema", "=", "db", ".", "schema", "(", ")", ";", "for", "(", "ConstraintDefinition", "constraintDefinition", ":", "Iterables", ".", "asList", "(", "schema", ".", "getConstraints", "(", "Label", ".", "label", "(", "labelName", ")", ")", ")", ")", "{", "List", "<", "String", ">", "properties", "=", "Iterables", ".", "asList", "(", "constraintDefinition", ".", "getPropertyKeys", "(", ")", ")", ";", "if", "(", "properties", ".", "equals", "(", "propertyNames", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Checks if a constraint exists for a given label and a list of properties This method checks for constraints on node @param labelName @param propertyNames @return true if the constraint exists otherwise it returns false
[ "Checks", "if", "a", "constraint", "exists", "for", "a", "given", "label", "and", "a", "list", "of", "properties", "This", "method", "checks", "for", "constraints", "on", "node" ]
train
https://github.com/neo4j-contrib/neo4j-apoc-procedures/blob/e8386975d1c512c0e4388a1a61f5496121c04f86/src/main/java/apoc/schema/Schemas.java#L232-L244
ops4j/org.ops4j.base
ops4j-base-io/src/main/java/org/ops4j/io/ZipExploder.java
ZipExploder.processZips
public void processZips(File[] zipFiles, File destDir) throws IOException { """ Explode source ZIP files into a target directory @param zipFiles list of source files @param destDir target directory name (should already exist) @exception IOException error creating a target file """ for (int i = 0; i < zipFiles.length; i++) { processFile(zipFiles[i], destDir); } }
java
public void processZips(File[] zipFiles, File destDir) throws IOException { for (int i = 0; i < zipFiles.length; i++) { processFile(zipFiles[i], destDir); } }
[ "public", "void", "processZips", "(", "File", "[", "]", "zipFiles", ",", "File", "destDir", ")", "throws", "IOException", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "zipFiles", ".", "length", ";", "i", "++", ")", "{", "processFile", "(", "zipFiles", "[", "i", "]", ",", "destDir", ")", ";", "}", "}" ]
Explode source ZIP files into a target directory @param zipFiles list of source files @param destDir target directory name (should already exist) @exception IOException error creating a target file
[ "Explode", "source", "ZIP", "files", "into", "a", "target", "directory" ]
train
https://github.com/ops4j/org.ops4j.base/blob/b0e742c0d9511f6b19ca64da2ebaf30b7a47256a/ops4j-base-io/src/main/java/org/ops4j/io/ZipExploder.java#L202-L206
OpenLiberty/open-liberty
dev/com.ibm.ws.jca.management.j2ee/src/com/ibm/ws/jca/management/j2ee/internal/ResourceAdapterModuleMBeanImpl.java
ResourceAdapterModuleMBeanImpl.setResourceAdapterChild
protected ResourceAdapterMBeanImpl setResourceAdapterChild(String key, ResourceAdapterMBeanImpl ra) { """ setResourceAdapterChild add a child of type ResourceAdapterMBeanImpl to this MBean. @param key the String value which will be used as the key for the ResourceAdapterMBeanImpl item @param ra the ResourceAdapterMBeanImpl value to be associated with the specified key @return The previous value associated with key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with key.) """ return raMBeanChildrenList.put(key, ra); }
java
protected ResourceAdapterMBeanImpl setResourceAdapterChild(String key, ResourceAdapterMBeanImpl ra) { return raMBeanChildrenList.put(key, ra); }
[ "protected", "ResourceAdapterMBeanImpl", "setResourceAdapterChild", "(", "String", "key", ",", "ResourceAdapterMBeanImpl", "ra", ")", "{", "return", "raMBeanChildrenList", ".", "put", "(", "key", ",", "ra", ")", ";", "}" ]
setResourceAdapterChild add a child of type ResourceAdapterMBeanImpl to this MBean. @param key the String value which will be used as the key for the ResourceAdapterMBeanImpl item @param ra the ResourceAdapterMBeanImpl value to be associated with the specified key @return The previous value associated with key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with key.)
[ "setResourceAdapterChild", "add", "a", "child", "of", "type", "ResourceAdapterMBeanImpl", "to", "this", "MBean", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jca.management.j2ee/src/com/ibm/ws/jca/management/j2ee/internal/ResourceAdapterModuleMBeanImpl.java#L367-L369
UrielCh/ovh-java-sdk
ovh-java-sdk-vps/src/main/java/net/minidev/ovh/api/ApiOvhVps.java
ApiOvhVps.serviceName_tasks_GET
public ArrayList<Long> serviceName_tasks_GET(String serviceName, OvhTaskStateEnum state, OvhTaskTypeEnum type) throws IOException { """ Tasks associated to this virtual server REST: GET /vps/{serviceName}/tasks @param type [required] Filter the value of type property (=) @param state [required] Filter the value of state property (=) @param serviceName [required] The internal name of your VPS offer """ String qPath = "/vps/{serviceName}/tasks"; StringBuilder sb = path(qPath, serviceName); query(sb, "state", state); query(sb, "type", type); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, t4); }
java
public ArrayList<Long> serviceName_tasks_GET(String serviceName, OvhTaskStateEnum state, OvhTaskTypeEnum type) throws IOException { String qPath = "/vps/{serviceName}/tasks"; StringBuilder sb = path(qPath, serviceName); query(sb, "state", state); query(sb, "type", type); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, t4); }
[ "public", "ArrayList", "<", "Long", ">", "serviceName_tasks_GET", "(", "String", "serviceName", ",", "OvhTaskStateEnum", "state", ",", "OvhTaskTypeEnum", "type", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/vps/{serviceName}/tasks\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ")", ";", "query", "(", "sb", ",", "\"state\"", ",", "state", ")", ";", "query", "(", "sb", ",", "\"type\"", ",", "type", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"GET\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "return", "convertTo", "(", "resp", ",", "t4", ")", ";", "}" ]
Tasks associated to this virtual server REST: GET /vps/{serviceName}/tasks @param type [required] Filter the value of type property (=) @param state [required] Filter the value of state property (=) @param serviceName [required] The internal name of your VPS offer
[ "Tasks", "associated", "to", "this", "virtual", "server" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-vps/src/main/java/net/minidev/ovh/api/ApiOvhVps.java#L388-L395
adorsys/hbci4java-adorsys
src/main/java/org/kapott/hbci/manager/BankInfo.java
BankInfo.getValue
private static String getValue(String[] cols, int idx) { """ Liefert den Wert aus der angegebenen Spalte. @param cols die Werte. @param idx die Spalte - beginnend bei 0. @return der Wert der Spalte oder NULL, wenn er nicht existiert. Die Funktion wirft keine {@link ArrayIndexOutOfBoundsException} """ if (cols == null || idx >= cols.length) return null; return cols[idx]; }
java
private static String getValue(String[] cols, int idx) { if (cols == null || idx >= cols.length) return null; return cols[idx]; }
[ "private", "static", "String", "getValue", "(", "String", "[", "]", "cols", ",", "int", "idx", ")", "{", "if", "(", "cols", "==", "null", "||", "idx", ">=", "cols", ".", "length", ")", "return", "null", ";", "return", "cols", "[", "idx", "]", ";", "}" ]
Liefert den Wert aus der angegebenen Spalte. @param cols die Werte. @param idx die Spalte - beginnend bei 0. @return der Wert der Spalte oder NULL, wenn er nicht existiert. Die Funktion wirft keine {@link ArrayIndexOutOfBoundsException}
[ "Liefert", "den", "Wert", "aus", "der", "angegebenen", "Spalte", "." ]
train
https://github.com/adorsys/hbci4java-adorsys/blob/5e24f7e429d6b555e1d993196b4cf1adda6433cf/src/main/java/org/kapott/hbci/manager/BankInfo.java#L56-L60
Wadpam/guja
guja-contact/src/main/java/com/wadpam/guja/dao/GeneratedDContactDaoImpl.java
GeneratedDContactDaoImpl.queryByEmail
public Iterable<DContact> queryByEmail(Object parent, java.lang.String email) { """ query-by method for field email @param email the specified attribute @return an Iterable of DContacts for the specified email """ return queryByField(parent, DContactMapper.Field.EMAIL.getFieldName(), email); }
java
public Iterable<DContact> queryByEmail(Object parent, java.lang.String email) { return queryByField(parent, DContactMapper.Field.EMAIL.getFieldName(), email); }
[ "public", "Iterable", "<", "DContact", ">", "queryByEmail", "(", "Object", "parent", ",", "java", ".", "lang", ".", "String", "email", ")", "{", "return", "queryByField", "(", "parent", ",", "DContactMapper", ".", "Field", ".", "EMAIL", ".", "getFieldName", "(", ")", ",", "email", ")", ";", "}" ]
query-by method for field email @param email the specified attribute @return an Iterable of DContacts for the specified email
[ "query", "-", "by", "method", "for", "field", "email" ]
train
https://github.com/Wadpam/guja/blob/eb8ba8e6794a96ea0dd9744cada4f9ad9618f114/guja-contact/src/main/java/com/wadpam/guja/dao/GeneratedDContactDaoImpl.java#L151-L153
UrielCh/ovh-java-sdk
ovh-java-sdk-dedicatedCloud/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedCloud.java
ApiOvhDedicatedCloud.commercialRange_commercialRangeName_GET
public OvhCommercialRange commercialRange_commercialRangeName_GET(String commercialRangeName) throws IOException { """ Get this object properties REST: GET /dedicatedCloud/commercialRange/{commercialRangeName} @param commercialRangeName [required] The name of this commercial range """ String qPath = "/dedicatedCloud/commercialRange/{commercialRangeName}"; StringBuilder sb = path(qPath, commercialRangeName); String resp = execN(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhCommercialRange.class); }
java
public OvhCommercialRange commercialRange_commercialRangeName_GET(String commercialRangeName) throws IOException { String qPath = "/dedicatedCloud/commercialRange/{commercialRangeName}"; StringBuilder sb = path(qPath, commercialRangeName); String resp = execN(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhCommercialRange.class); }
[ "public", "OvhCommercialRange", "commercialRange_commercialRangeName_GET", "(", "String", "commercialRangeName", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/dedicatedCloud/commercialRange/{commercialRangeName}\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "commercialRangeName", ")", ";", "String", "resp", "=", "execN", "(", "qPath", ",", "\"GET\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhCommercialRange", ".", "class", ")", ";", "}" ]
Get this object properties REST: GET /dedicatedCloud/commercialRange/{commercialRangeName} @param commercialRangeName [required] The name of this commercial range
[ "Get", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dedicatedCloud/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedCloud.java#L3119-L3124
Pi4J/pi4j
pi4j-gpio-extension/src/main/java/com/pi4j/gpio/extension/pca/PCA9685GpioProvider.java
PCA9685GpioProvider.setAlwaysOn
public void setAlwaysOn(Pin pin) { """ Permanently sets the output to High (no PWM anymore).<br> The LEDn_ON_H output control bit 4, when set to logic 1, causes the output to be always ON. @param pin represents channel 0..15 """ final int pwmOnValue = 0x1000; final int pwmOffValue = 0x0000; validatePin(pin, pwmOnValue, pwmOffValue); final int channel = pin.getAddress(); try { device.write(PCA9685A_LED0_ON_L + 4 * channel, (byte) 0x00); device.write(PCA9685A_LED0_ON_H + 4 * channel, (byte) 0x10); // set bit 4 to high device.write(PCA9685A_LED0_OFF_L + 4 * channel, (byte) 0x00); device.write(PCA9685A_LED0_OFF_H + 4 * channel, (byte) 0x00); } catch (IOException e) { throw new RuntimeException("Error while trying to set channel [" + channel + "] always ON.", e); } cachePinValues(pin, pwmOnValue, pwmOffValue); }
java
public void setAlwaysOn(Pin pin) { final int pwmOnValue = 0x1000; final int pwmOffValue = 0x0000; validatePin(pin, pwmOnValue, pwmOffValue); final int channel = pin.getAddress(); try { device.write(PCA9685A_LED0_ON_L + 4 * channel, (byte) 0x00); device.write(PCA9685A_LED0_ON_H + 4 * channel, (byte) 0x10); // set bit 4 to high device.write(PCA9685A_LED0_OFF_L + 4 * channel, (byte) 0x00); device.write(PCA9685A_LED0_OFF_H + 4 * channel, (byte) 0x00); } catch (IOException e) { throw new RuntimeException("Error while trying to set channel [" + channel + "] always ON.", e); } cachePinValues(pin, pwmOnValue, pwmOffValue); }
[ "public", "void", "setAlwaysOn", "(", "Pin", "pin", ")", "{", "final", "int", "pwmOnValue", "=", "0x1000", ";", "final", "int", "pwmOffValue", "=", "0x0000", ";", "validatePin", "(", "pin", ",", "pwmOnValue", ",", "pwmOffValue", ")", ";", "final", "int", "channel", "=", "pin", ".", "getAddress", "(", ")", ";", "try", "{", "device", ".", "write", "(", "PCA9685A_LED0_ON_L", "+", "4", "*", "channel", ",", "(", "byte", ")", "0x00", ")", ";", "device", ".", "write", "(", "PCA9685A_LED0_ON_H", "+", "4", "*", "channel", ",", "(", "byte", ")", "0x10", ")", ";", "// set bit 4 to high", "device", ".", "write", "(", "PCA9685A_LED0_OFF_L", "+", "4", "*", "channel", ",", "(", "byte", ")", "0x00", ")", ";", "device", ".", "write", "(", "PCA9685A_LED0_OFF_H", "+", "4", "*", "channel", ",", "(", "byte", ")", "0x00", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Error while trying to set channel [\"", "+", "channel", "+", "\"] always ON.\"", ",", "e", ")", ";", "}", "cachePinValues", "(", "pin", ",", "pwmOnValue", ",", "pwmOffValue", ")", ";", "}" ]
Permanently sets the output to High (no PWM anymore).<br> The LEDn_ON_H output control bit 4, when set to logic 1, causes the output to be always ON. @param pin represents channel 0..15
[ "Permanently", "sets", "the", "output", "to", "High", "(", "no", "PWM", "anymore", ")", ".", "<br", ">", "The", "LEDn_ON_H", "output", "control", "bit", "4", "when", "set", "to", "logic", "1", "causes", "the", "output", "to", "be", "always", "ON", "." ]
train
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-gpio-extension/src/main/java/com/pi4j/gpio/extension/pca/PCA9685GpioProvider.java#L211-L225
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-scaleout/spark/dl4j-spark/src/main/java/org/deeplearning4j/spark/util/SparkUtils.java
SparkUtils.balancedRandomSplit
public static <T> JavaRDD<T>[] balancedRandomSplit(int totalObjectCount, int numObjectsPerSplit, JavaRDD<T> data) { """ Random split the specified RDD into a number of RDDs, where each has {@code numObjectsPerSplit} in them. <p> This similar to how RDD.randomSplit works (i.e., split via filtering), but this should result in more equal splits (instead of independent binomial sampling that is used there, based on weighting) This balanced splitting approach is important when the number of DataSet objects we want in each split is small, as random sampling variance of {@link JavaRDD#randomSplit(double[])} is quite large relative to the number of examples in each split. Note however that this method doesn't <i>guarantee</i> that partitions will be balanced <p> Downside is we need total object count (whereas {@link JavaRDD#randomSplit(double[])} does not). However, randomSplit requires a full pass of the data anyway (in order to do filtering upon it) so this should not add much overhead in practice @param totalObjectCount Total number of objects in the RDD to split @param numObjectsPerSplit Number of objects in each split @param data Data to split @param <T> Generic type for the RDD @return The RDD split up (without replacement) into a number of smaller RDDs """ return balancedRandomSplit(totalObjectCount, numObjectsPerSplit, data, new Random().nextLong()); }
java
public static <T> JavaRDD<T>[] balancedRandomSplit(int totalObjectCount, int numObjectsPerSplit, JavaRDD<T> data) { return balancedRandomSplit(totalObjectCount, numObjectsPerSplit, data, new Random().nextLong()); }
[ "public", "static", "<", "T", ">", "JavaRDD", "<", "T", ">", "[", "]", "balancedRandomSplit", "(", "int", "totalObjectCount", ",", "int", "numObjectsPerSplit", ",", "JavaRDD", "<", "T", ">", "data", ")", "{", "return", "balancedRandomSplit", "(", "totalObjectCount", ",", "numObjectsPerSplit", ",", "data", ",", "new", "Random", "(", ")", ".", "nextLong", "(", ")", ")", ";", "}" ]
Random split the specified RDD into a number of RDDs, where each has {@code numObjectsPerSplit} in them. <p> This similar to how RDD.randomSplit works (i.e., split via filtering), but this should result in more equal splits (instead of independent binomial sampling that is used there, based on weighting) This balanced splitting approach is important when the number of DataSet objects we want in each split is small, as random sampling variance of {@link JavaRDD#randomSplit(double[])} is quite large relative to the number of examples in each split. Note however that this method doesn't <i>guarantee</i> that partitions will be balanced <p> Downside is we need total object count (whereas {@link JavaRDD#randomSplit(double[])} does not). However, randomSplit requires a full pass of the data anyway (in order to do filtering upon it) so this should not add much overhead in practice @param totalObjectCount Total number of objects in the RDD to split @param numObjectsPerSplit Number of objects in each split @param data Data to split @param <T> Generic type for the RDD @return The RDD split up (without replacement) into a number of smaller RDDs
[ "Random", "split", "the", "specified", "RDD", "into", "a", "number", "of", "RDDs", "where", "each", "has", "{", "@code", "numObjectsPerSplit", "}", "in", "them", ".", "<p", ">", "This", "similar", "to", "how", "RDD", ".", "randomSplit", "works", "(", "i", ".", "e", ".", "split", "via", "filtering", ")", "but", "this", "should", "result", "in", "more", "equal", "splits", "(", "instead", "of", "independent", "binomial", "sampling", "that", "is", "used", "there", "based", "on", "weighting", ")", "This", "balanced", "splitting", "approach", "is", "important", "when", "the", "number", "of", "DataSet", "objects", "we", "want", "in", "each", "split", "is", "small", "as", "random", "sampling", "variance", "of", "{", "@link", "JavaRDD#randomSplit", "(", "double", "[]", ")", "}", "is", "quite", "large", "relative", "to", "the", "number", "of", "examples", "in", "each", "split", ".", "Note", "however", "that", "this", "method", "doesn", "t", "<i", ">", "guarantee<", "/", "i", ">", "that", "partitions", "will", "be", "balanced", "<p", ">", "Downside", "is", "we", "need", "total", "object", "count", "(", "whereas", "{", "@link", "JavaRDD#randomSplit", "(", "double", "[]", ")", "}", "does", "not", ")", ".", "However", "randomSplit", "requires", "a", "full", "pass", "of", "the", "data", "anyway", "(", "in", "order", "to", "do", "filtering", "upon", "it", ")", "so", "this", "should", "not", "add", "much", "overhead", "in", "practice" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-scaleout/spark/dl4j-spark/src/main/java/org/deeplearning4j/spark/util/SparkUtils.java#L460-L462
apereo/cas
support/cas-server-support-saml-core-api/src/main/java/org/apereo/cas/support/saml/SamlUtils.java
SamlUtils.transformSamlObject
public static StringWriter transformSamlObject(final OpenSamlConfigBean configBean, final XMLObject samlObject) throws SamlException { """ Transform saml object into string without indenting the final string. @param configBean the config bean @param samlObject the saml object @return the string writer @throws SamlException the saml exception """ return transformSamlObject(configBean, samlObject, false); }
java
public static StringWriter transformSamlObject(final OpenSamlConfigBean configBean, final XMLObject samlObject) throws SamlException { return transformSamlObject(configBean, samlObject, false); }
[ "public", "static", "StringWriter", "transformSamlObject", "(", "final", "OpenSamlConfigBean", "configBean", ",", "final", "XMLObject", "samlObject", ")", "throws", "SamlException", "{", "return", "transformSamlObject", "(", "configBean", ",", "samlObject", ",", "false", ")", ";", "}" ]
Transform saml object into string without indenting the final string. @param configBean the config bean @param samlObject the saml object @return the string writer @throws SamlException the saml exception
[ "Transform", "saml", "object", "into", "string", "without", "indenting", "the", "final", "string", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-saml-core-api/src/main/java/org/apereo/cas/support/saml/SamlUtils.java#L71-L73
ngageoint/geopackage-android-map
geopackage-map/src/main/java/mil/nga/geopackage/map/tiles/overlay/FeatureOverlayQuery.java
FeatureOverlayQuery.buildMapClickMessageWithMapBounds
public String buildMapClickMessageWithMapBounds(LatLng latLng, double zoom, BoundingBox mapBounds, double tolerance) { """ Perform a query based upon the map click location and build a info message @param latLng location @param zoom current zoom level @param mapBounds map view bounds @param tolerance tolerance distance @return information message on what was clicked, or nil @since 2.0.0 """ return buildMapClickMessageWithMapBounds(latLng, zoom, mapBounds, tolerance, null); }
java
public String buildMapClickMessageWithMapBounds(LatLng latLng, double zoom, BoundingBox mapBounds, double tolerance) { return buildMapClickMessageWithMapBounds(latLng, zoom, mapBounds, tolerance, null); }
[ "public", "String", "buildMapClickMessageWithMapBounds", "(", "LatLng", "latLng", ",", "double", "zoom", ",", "BoundingBox", "mapBounds", ",", "double", "tolerance", ")", "{", "return", "buildMapClickMessageWithMapBounds", "(", "latLng", ",", "zoom", ",", "mapBounds", ",", "tolerance", ",", "null", ")", ";", "}" ]
Perform a query based upon the map click location and build a info message @param latLng location @param zoom current zoom level @param mapBounds map view bounds @param tolerance tolerance distance @return information message on what was clicked, or nil @since 2.0.0
[ "Perform", "a", "query", "based", "upon", "the", "map", "click", "location", "and", "build", "a", "info", "message" ]
train
https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/tiles/overlay/FeatureOverlayQuery.java#L382-L384
saxsys/SynchronizeFX
synchronizefx-core/src/main/java/de/saxsys/synchronizefx/core/metamodel/CommandListCreator.java
CommandListCreator.removeFromList
public List<Command> removeFromList(final UUID listId, final int startPosition, final int removeCount) { """ Creates the list with commands necessary to remove a object from a list. @param listId The ID of the list where an element should be removed. @param startPosition The index of the first element in the list which should be removed. @param removeCount The element count to remove from the list, starting from <code>startPosition</code>. @return The command list. """ final ListVersionChange change = increaseListVersion(listId); final RemoveFromList msg = new RemoveFromList(listId, change, startPosition, removeCount); final List<Command> commands = new ArrayList<>(1); commands.add(msg); return commands; }
java
public List<Command> removeFromList(final UUID listId, final int startPosition, final int removeCount) { final ListVersionChange change = increaseListVersion(listId); final RemoveFromList msg = new RemoveFromList(listId, change, startPosition, removeCount); final List<Command> commands = new ArrayList<>(1); commands.add(msg); return commands; }
[ "public", "List", "<", "Command", ">", "removeFromList", "(", "final", "UUID", "listId", ",", "final", "int", "startPosition", ",", "final", "int", "removeCount", ")", "{", "final", "ListVersionChange", "change", "=", "increaseListVersion", "(", "listId", ")", ";", "final", "RemoveFromList", "msg", "=", "new", "RemoveFromList", "(", "listId", ",", "change", ",", "startPosition", ",", "removeCount", ")", ";", "final", "List", "<", "Command", ">", "commands", "=", "new", "ArrayList", "<>", "(", "1", ")", ";", "commands", ".", "add", "(", "msg", ")", ";", "return", "commands", ";", "}" ]
Creates the list with commands necessary to remove a object from a list. @param listId The ID of the list where an element should be removed. @param startPosition The index of the first element in the list which should be removed. @param removeCount The element count to remove from the list, starting from <code>startPosition</code>. @return The command list.
[ "Creates", "the", "list", "with", "commands", "necessary", "to", "remove", "a", "object", "from", "a", "list", "." ]
train
https://github.com/saxsys/SynchronizeFX/blob/f3683020e4749110b38514eb5bc73a247998b579/synchronizefx-core/src/main/java/de/saxsys/synchronizefx/core/metamodel/CommandListCreator.java#L209-L215
jeremylong/DependencyCheck
core/src/main/java/org/owasp/dependencycheck/xml/pom/Model.java
Model.interpolateString
public static String interpolateString(String text, Properties properties) { """ <p> A utility function that will interpolate strings based on values given in the properties file. It will also interpolate the strings contained within the properties file so that properties can reference other properties.</p> <p> <b>Note:</b> if there is no property found the reference will be removed. In other words, if the interpolated string will be replaced with an empty string. </p> <p> Example:</p> <code> Properties p = new Properties(); p.setProperty("key", "value"); String s = interpolateString("'${key}' and '${nothing}'", p); System.out.println(s); </code> <p> Will result in:</p> <code> 'value' and '' </code> @param text the string that contains references to properties. @param properties a collection of properties that may be referenced within the text. @return the interpolated text. """ if (null == text || null == properties) { return text; } final StringSubstitutor substitutor = new StringSubstitutor(new PropertyLookup(properties)); return substitutor.replace(text); }
java
public static String interpolateString(String text, Properties properties) { if (null == text || null == properties) { return text; } final StringSubstitutor substitutor = new StringSubstitutor(new PropertyLookup(properties)); return substitutor.replace(text); }
[ "public", "static", "String", "interpolateString", "(", "String", "text", ",", "Properties", "properties", ")", "{", "if", "(", "null", "==", "text", "||", "null", "==", "properties", ")", "{", "return", "text", ";", "}", "final", "StringSubstitutor", "substitutor", "=", "new", "StringSubstitutor", "(", "new", "PropertyLookup", "(", "properties", ")", ")", ";", "return", "substitutor", ".", "replace", "(", "text", ")", ";", "}" ]
<p> A utility function that will interpolate strings based on values given in the properties file. It will also interpolate the strings contained within the properties file so that properties can reference other properties.</p> <p> <b>Note:</b> if there is no property found the reference will be removed. In other words, if the interpolated string will be replaced with an empty string. </p> <p> Example:</p> <code> Properties p = new Properties(); p.setProperty("key", "value"); String s = interpolateString("'${key}' and '${nothing}'", p); System.out.println(s); </code> <p> Will result in:</p> <code> 'value' and '' </code> @param text the string that contains references to properties. @param properties a collection of properties that may be referenced within the text. @return the interpolated text.
[ "<p", ">", "A", "utility", "function", "that", "will", "interpolate", "strings", "based", "on", "values", "given", "in", "the", "properties", "file", ".", "It", "will", "also", "interpolate", "the", "strings", "contained", "within", "the", "properties", "file", "so", "that", "properties", "can", "reference", "other", "properties", ".", "<", "/", "p", ">", "<p", ">", "<b", ">", "Note", ":", "<", "/", "b", ">", "if", "there", "is", "no", "property", "found", "the", "reference", "will", "be", "removed", ".", "In", "other", "words", "if", "the", "interpolated", "string", "will", "be", "replaced", "with", "an", "empty", "string", ".", "<", "/", "p", ">", "<p", ">", "Example", ":", "<", "/", "p", ">", "<code", ">", "Properties", "p", "=", "new", "Properties", "()", ";", "p", ".", "setProperty", "(", "key", "value", ")", ";", "String", "s", "=", "interpolateString", "(", "$", "{", "key", "}", "and", "$", "{", "nothing", "}", "p", ")", ";", "System", ".", "out", ".", "println", "(", "s", ")", ";", "<", "/", "code", ">", "<p", ">", "Will", "result", "in", ":", "<", "/", "p", ">", "<code", ">", "value", "and", "<", "/", "code", ">" ]
train
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/xml/pom/Model.java#L353-L359
spring-projects/spring-android
spring-android-rest-template/src/main/java/org/springframework/http/ContentCodingType.java
ContentCodingType.parseCodingType
public static ContentCodingType parseCodingType(String codingType) { """ Parse the given String into a single {@code ContentCodingType}. @param codingType the string to parse @return the content coding type @throws IllegalArgumentException if the string cannot be parsed """ Assert.hasLength(codingType, "'codingType' must not be empty"); String[] parts = StringUtils.tokenizeToStringArray(codingType, ";"); String type = parts[0].trim(); Map<String, String> parameters = null; if (parts.length > 1) { parameters = new LinkedHashMap<String, String>(parts.length - 1); for (int i = 1; i < parts.length; i++) { String parameter = parts[i]; int eqIndex = parameter.indexOf('='); if (eqIndex != -1) { String attribute = parameter.substring(0, eqIndex); String value = parameter.substring(eqIndex + 1, parameter.length()); parameters.put(attribute, value); } } } return new ContentCodingType(type, parameters); }
java
public static ContentCodingType parseCodingType(String codingType) { Assert.hasLength(codingType, "'codingType' must not be empty"); String[] parts = StringUtils.tokenizeToStringArray(codingType, ";"); String type = parts[0].trim(); Map<String, String> parameters = null; if (parts.length > 1) { parameters = new LinkedHashMap<String, String>(parts.length - 1); for (int i = 1; i < parts.length; i++) { String parameter = parts[i]; int eqIndex = parameter.indexOf('='); if (eqIndex != -1) { String attribute = parameter.substring(0, eqIndex); String value = parameter.substring(eqIndex + 1, parameter.length()); parameters.put(attribute, value); } } } return new ContentCodingType(type, parameters); }
[ "public", "static", "ContentCodingType", "parseCodingType", "(", "String", "codingType", ")", "{", "Assert", ".", "hasLength", "(", "codingType", ",", "\"'codingType' must not be empty\"", ")", ";", "String", "[", "]", "parts", "=", "StringUtils", ".", "tokenizeToStringArray", "(", "codingType", ",", "\";\"", ")", ";", "String", "type", "=", "parts", "[", "0", "]", ".", "trim", "(", ")", ";", "Map", "<", "String", ",", "String", ">", "parameters", "=", "null", ";", "if", "(", "parts", ".", "length", ">", "1", ")", "{", "parameters", "=", "new", "LinkedHashMap", "<", "String", ",", "String", ">", "(", "parts", ".", "length", "-", "1", ")", ";", "for", "(", "int", "i", "=", "1", ";", "i", "<", "parts", ".", "length", ";", "i", "++", ")", "{", "String", "parameter", "=", "parts", "[", "i", "]", ";", "int", "eqIndex", "=", "parameter", ".", "indexOf", "(", "'", "'", ")", ";", "if", "(", "eqIndex", "!=", "-", "1", ")", "{", "String", "attribute", "=", "parameter", ".", "substring", "(", "0", ",", "eqIndex", ")", ";", "String", "value", "=", "parameter", ".", "substring", "(", "eqIndex", "+", "1", ",", "parameter", ".", "length", "(", ")", ")", ";", "parameters", ".", "put", "(", "attribute", ",", "value", ")", ";", "}", "}", "}", "return", "new", "ContentCodingType", "(", "type", ",", "parameters", ")", ";", "}" ]
Parse the given String into a single {@code ContentCodingType}. @param codingType the string to parse @return the content coding type @throws IllegalArgumentException if the string cannot be parsed
[ "Parse", "the", "given", "String", "into", "a", "single", "{" ]
train
https://github.com/spring-projects/spring-android/blob/941296e152d49a40e0745a3e81628a974f72b7e4/spring-android-rest-template/src/main/java/org/springframework/http/ContentCodingType.java#L373-L393
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/SameDiff.java
SameDiff.execBackwards
public void execBackwards(Map<String,INDArray> placeholders, List<String> variableGradNamesList) { """ As per {@link #execBackwards(Map)}, but the set of gradients to calculate can be specified manually.<br> For example, to calculate the gradient for placeholder variable "myPlaceholder", use {@code execBackwards(placeholders, Arrays.asList(myPlaceholder.gradient().getVarName())}. @param placeholders Values for the placeholder variables in the graph. For graphs without placeholders, use null or an empty map @param variableGradNamesList Names of the gradient variables to calculate """ if (getFunction("grad") == null) { createGradFunction(); } log.trace("About to execute backward function"); //Edge case: if no variables, no variable gradients to calculate... if(variableGradNamesList.isEmpty()){ log.warn("Skipping gradient calculation (backward pass) - no variables to be calculated (variableGradNamesList is empty)"); return; } sameDiffFunctionInstances.get("grad").exec(placeholders, variableGradNamesList); }
java
public void execBackwards(Map<String,INDArray> placeholders, List<String> variableGradNamesList){ if (getFunction("grad") == null) { createGradFunction(); } log.trace("About to execute backward function"); //Edge case: if no variables, no variable gradients to calculate... if(variableGradNamesList.isEmpty()){ log.warn("Skipping gradient calculation (backward pass) - no variables to be calculated (variableGradNamesList is empty)"); return; } sameDiffFunctionInstances.get("grad").exec(placeholders, variableGradNamesList); }
[ "public", "void", "execBackwards", "(", "Map", "<", "String", ",", "INDArray", ">", "placeholders", ",", "List", "<", "String", ">", "variableGradNamesList", ")", "{", "if", "(", "getFunction", "(", "\"grad\"", ")", "==", "null", ")", "{", "createGradFunction", "(", ")", ";", "}", "log", ".", "trace", "(", "\"About to execute backward function\"", ")", ";", "//Edge case: if no variables, no variable gradients to calculate...", "if", "(", "variableGradNamesList", ".", "isEmpty", "(", ")", ")", "{", "log", ".", "warn", "(", "\"Skipping gradient calculation (backward pass) - no variables to be calculated (variableGradNamesList is empty)\"", ")", ";", "return", ";", "}", "sameDiffFunctionInstances", ".", "get", "(", "\"grad\"", ")", ".", "exec", "(", "placeholders", ",", "variableGradNamesList", ")", ";", "}" ]
As per {@link #execBackwards(Map)}, but the set of gradients to calculate can be specified manually.<br> For example, to calculate the gradient for placeholder variable "myPlaceholder", use {@code execBackwards(placeholders, Arrays.asList(myPlaceholder.gradient().getVarName())}. @param placeholders Values for the placeholder variables in the graph. For graphs without placeholders, use null or an empty map @param variableGradNamesList Names of the gradient variables to calculate
[ "As", "per", "{", "@link", "#execBackwards", "(", "Map", ")", "}", "but", "the", "set", "of", "gradients", "to", "calculate", "can", "be", "specified", "manually", ".", "<br", ">", "For", "example", "to", "calculate", "the", "gradient", "for", "placeholder", "variable", "myPlaceholder", "use", "{", "@code", "execBackwards", "(", "placeholders", "Arrays", ".", "asList", "(", "myPlaceholder", ".", "gradient", "()", ".", "getVarName", "()", ")", "}", "." ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/SameDiff.java#L3249-L3263
gallandarakhneorg/afc
core/vmutils/src/main/java/org/arakhne/afc/vmutil/AbstractOperatingSystemWrapper.java
AbstractOperatingSystemWrapper.runCommand
protected static String runCommand(String... command) { """ Run a shell command. @param command is the shell command to run. @return the standard output """ try { final Process p = Runtime.getRuntime().exec(command); if (p == null) { return null; } final StringBuilder bStr = new StringBuilder(); try (InputStream standardOutput = p.getInputStream()) { final byte[] buffer = new byte[BUFFER_SIZE]; int len; while ((len = standardOutput.read(buffer)) > 0) { bStr.append(new String(buffer, 0, len)); } p.waitFor(); return bStr.toString(); } } catch (Exception e) { return null; } }
java
protected static String runCommand(String... command) { try { final Process p = Runtime.getRuntime().exec(command); if (p == null) { return null; } final StringBuilder bStr = new StringBuilder(); try (InputStream standardOutput = p.getInputStream()) { final byte[] buffer = new byte[BUFFER_SIZE]; int len; while ((len = standardOutput.read(buffer)) > 0) { bStr.append(new String(buffer, 0, len)); } p.waitFor(); return bStr.toString(); } } catch (Exception e) { return null; } }
[ "protected", "static", "String", "runCommand", "(", "String", "...", "command", ")", "{", "try", "{", "final", "Process", "p", "=", "Runtime", ".", "getRuntime", "(", ")", ".", "exec", "(", "command", ")", ";", "if", "(", "p", "==", "null", ")", "{", "return", "null", ";", "}", "final", "StringBuilder", "bStr", "=", "new", "StringBuilder", "(", ")", ";", "try", "(", "InputStream", "standardOutput", "=", "p", ".", "getInputStream", "(", ")", ")", "{", "final", "byte", "[", "]", "buffer", "=", "new", "byte", "[", "BUFFER_SIZE", "]", ";", "int", "len", ";", "while", "(", "(", "len", "=", "standardOutput", ".", "read", "(", "buffer", ")", ")", ">", "0", ")", "{", "bStr", ".", "append", "(", "new", "String", "(", "buffer", ",", "0", ",", "len", ")", ")", ";", "}", "p", ".", "waitFor", "(", ")", ";", "return", "bStr", ".", "toString", "(", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "return", "null", ";", "}", "}" ]
Run a shell command. @param command is the shell command to run. @return the standard output
[ "Run", "a", "shell", "command", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/vmutils/src/main/java/org/arakhne/afc/vmutil/AbstractOperatingSystemWrapper.java#L54-L73
BlueBrain/bluima
modules/bluima_typesystem/src/main/java/de/julielab/jules/types/ace/Document.java
Document.setTimex2
public void setTimex2(int i, Timex2 v) { """ indexed setter for timex2 - sets an indexed value - @generated @param i index in the array to set @param v value to set into the array """ if (Document_Type.featOkTst && ((Document_Type)jcasType).casFeat_timex2 == null) jcasType.jcas.throwFeatMissing("timex2", "de.julielab.jules.types.ace.Document"); jcasType.jcas.checkArrayBounds(jcasType.ll_cas.ll_getRefValue(addr, ((Document_Type)jcasType).casFeatCode_timex2), i); jcasType.ll_cas.ll_setRefArrayValue(jcasType.ll_cas.ll_getRefValue(addr, ((Document_Type)jcasType).casFeatCode_timex2), i, jcasType.ll_cas.ll_getFSRef(v));}
java
public void setTimex2(int i, Timex2 v) { if (Document_Type.featOkTst && ((Document_Type)jcasType).casFeat_timex2 == null) jcasType.jcas.throwFeatMissing("timex2", "de.julielab.jules.types.ace.Document"); jcasType.jcas.checkArrayBounds(jcasType.ll_cas.ll_getRefValue(addr, ((Document_Type)jcasType).casFeatCode_timex2), i); jcasType.ll_cas.ll_setRefArrayValue(jcasType.ll_cas.ll_getRefValue(addr, ((Document_Type)jcasType).casFeatCode_timex2), i, jcasType.ll_cas.ll_getFSRef(v));}
[ "public", "void", "setTimex2", "(", "int", "i", ",", "Timex2", "v", ")", "{", "if", "(", "Document_Type", ".", "featOkTst", "&&", "(", "(", "Document_Type", ")", "jcasType", ")", ".", "casFeat_timex2", "==", "null", ")", "jcasType", ".", "jcas", ".", "throwFeatMissing", "(", "\"timex2\"", ",", "\"de.julielab.jules.types.ace.Document\"", ")", ";", "jcasType", ".", "jcas", ".", "checkArrayBounds", "(", "jcasType", ".", "ll_cas", ".", "ll_getRefValue", "(", "addr", ",", "(", "(", "Document_Type", ")", "jcasType", ")", ".", "casFeatCode_timex2", ")", ",", "i", ")", ";", "jcasType", ".", "ll_cas", ".", "ll_setRefArrayValue", "(", "jcasType", ".", "ll_cas", ".", "ll_getRefValue", "(", "addr", ",", "(", "(", "Document_Type", ")", "jcasType", ")", ".", "casFeatCode_timex2", ")", ",", "i", ",", "jcasType", ".", "ll_cas", ".", "ll_getFSRef", "(", "v", ")", ")", ";", "}" ]
indexed setter for timex2 - sets an indexed value - @generated @param i index in the array to set @param v value to set into the array
[ "indexed", "setter", "for", "timex2", "-", "sets", "an", "indexed", "value", "-" ]
train
https://github.com/BlueBrain/bluima/blob/793ea3f46761dce72094e057a56cddfa677156ae/modules/bluima_typesystem/src/main/java/de/julielab/jules/types/ace/Document.java#L226-L230
groupon/monsoon
intf/src/main/java/com/groupon/lex/metrics/resolver/NamedResolverMap.java
NamedResolverMap.getStringOrDefault
public String getStringOrDefault(int key, @NonNull String dfl) { """ Return the string value indicated by the given numeric key. @param key The key of the value to return. @param dfl The default value to return, if the key is absent. @return The string value stored under the given key, or dfl. @throws IllegalArgumentException if the value is present, but not a string. """ Any3<Boolean, Integer, String> value = data.getOrDefault(Any2.<Integer, String>left(key), Any3.<Boolean, Integer, String>create3(dfl)); return value.get3().orElseThrow(() -> new IllegalArgumentException("expected string argument for param " + key)); }
java
public String getStringOrDefault(int key, @NonNull String dfl) { Any3<Boolean, Integer, String> value = data.getOrDefault(Any2.<Integer, String>left(key), Any3.<Boolean, Integer, String>create3(dfl)); return value.get3().orElseThrow(() -> new IllegalArgumentException("expected string argument for param " + key)); }
[ "public", "String", "getStringOrDefault", "(", "int", "key", ",", "@", "NonNull", "String", "dfl", ")", "{", "Any3", "<", "Boolean", ",", "Integer", ",", "String", ">", "value", "=", "data", ".", "getOrDefault", "(", "Any2", ".", "<", "Integer", ",", "String", ">", "left", "(", "key", ")", ",", "Any3", ".", "<", "Boolean", ",", "Integer", ",", "String", ">", "create3", "(", "dfl", ")", ")", ";", "return", "value", ".", "get3", "(", ")", ".", "orElseThrow", "(", "(", ")", "->", "new", "IllegalArgumentException", "(", "\"expected string argument for param \"", "+", "key", ")", ")", ";", "}" ]
Return the string value indicated by the given numeric key. @param key The key of the value to return. @param dfl The default value to return, if the key is absent. @return The string value stored under the given key, or dfl. @throws IllegalArgumentException if the value is present, but not a string.
[ "Return", "the", "string", "value", "indicated", "by", "the", "given", "numeric", "key", "." ]
train
https://github.com/groupon/monsoon/blob/eb68d72ba4c01fe018dc981097dbee033908f5c7/intf/src/main/java/com/groupon/lex/metrics/resolver/NamedResolverMap.java#L101-L104
OpenLiberty/open-liberty
dev/com.ibm.ws.messaging.common/src/com/ibm/ws/sib/mfp/impl/SchemaSet.java
SchemaSet.hashToTable
private int hashToTable(Long id, Entry[] table) { """ The Long Id is already effectively a hashcode for the Schema and should be unique. All we should need to do is get a positive integer version of it & divide by the table size. """ int posVal = id.intValue() & Integer.MAX_VALUE; return (posVal % table.length); }
java
private int hashToTable(Long id, Entry[] table) { int posVal = id.intValue() & Integer.MAX_VALUE; return (posVal % table.length); }
[ "private", "int", "hashToTable", "(", "Long", "id", ",", "Entry", "[", "]", "table", ")", "{", "int", "posVal", "=", "id", ".", "intValue", "(", ")", "&", "Integer", ".", "MAX_VALUE", ";", "return", "(", "posVal", "%", "table", ".", "length", ")", ";", "}" ]
The Long Id is already effectively a hashcode for the Schema and should be unique. All we should need to do is get a positive integer version of it & divide by the table size.
[ "The", "Long", "Id", "is", "already", "effectively", "a", "hashcode", "for", "the", "Schema", "and", "should", "be", "unique", ".", "All", "we", "should", "need", "to", "do", "is", "get", "a", "positive", "integer", "version", "of", "it", "&", "divide", "by", "the", "table", "size", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.common/src/com/ibm/ws/sib/mfp/impl/SchemaSet.java#L289-L292
alkacon/opencms-core
src/org/opencms/i18n/CmsMessages.java
CmsMessages.keyWithParams
public String keyWithParams(String keyName) { """ Returns the localized resource string for a given message key, treating all values appended with "|" as replacement parameters.<p> If the key was found in the bundle, it will be formatted using a <code>{@link MessageFormat}</code> using the provided parameters. The parameters have to be appended to the key separated by a "|". For example, the keyName <code>error.message|First|Second</code> would use the key <code>error.message</code> with the parameters <code>First</code> and <code>Second</code>. This would be the same as calling <code>{@link CmsMessages#key(String, Object[])}</code>.<p> If no parameters are appended with "|", this is the same as calling <code>{@link CmsMessages#key(String)}</code>.<p> If the key was not found in the bundle, the return value is <code>"??? " + keyName + " ???"</code>. This will also be returned if the bundle was not properly initialized first. @param keyName the key for the desired string, optinally containing parameters appended with a "|" @return the resource string for the given key @see #key(String, Object[]) @see #key(String) """ if (keyName.indexOf('|') == -1) { // no separator found, key has no parameters return key(keyName, false); } else { // this key contains parameters String[] values = CmsStringUtil.splitAsArray(keyName, '|'); String cutKeyName = values[0]; String[] params = new String[values.length - 1]; System.arraycopy(values, 1, params, 0, params.length); return key(cutKeyName, params); } }
java
public String keyWithParams(String keyName) { if (keyName.indexOf('|') == -1) { // no separator found, key has no parameters return key(keyName, false); } else { // this key contains parameters String[] values = CmsStringUtil.splitAsArray(keyName, '|'); String cutKeyName = values[0]; String[] params = new String[values.length - 1]; System.arraycopy(values, 1, params, 0, params.length); return key(cutKeyName, params); } }
[ "public", "String", "keyWithParams", "(", "String", "keyName", ")", "{", "if", "(", "keyName", ".", "indexOf", "(", "'", "'", ")", "==", "-", "1", ")", "{", "// no separator found, key has no parameters", "return", "key", "(", "keyName", ",", "false", ")", ";", "}", "else", "{", "// this key contains parameters", "String", "[", "]", "values", "=", "CmsStringUtil", ".", "splitAsArray", "(", "keyName", ",", "'", "'", ")", ";", "String", "cutKeyName", "=", "values", "[", "0", "]", ";", "String", "[", "]", "params", "=", "new", "String", "[", "values", ".", "length", "-", "1", "]", ";", "System", ".", "arraycopy", "(", "values", ",", "1", ",", "params", ",", "0", ",", "params", ".", "length", ")", ";", "return", "key", "(", "cutKeyName", ",", "params", ")", ";", "}", "}" ]
Returns the localized resource string for a given message key, treating all values appended with "|" as replacement parameters.<p> If the key was found in the bundle, it will be formatted using a <code>{@link MessageFormat}</code> using the provided parameters. The parameters have to be appended to the key separated by a "|". For example, the keyName <code>error.message|First|Second</code> would use the key <code>error.message</code> with the parameters <code>First</code> and <code>Second</code>. This would be the same as calling <code>{@link CmsMessages#key(String, Object[])}</code>.<p> If no parameters are appended with "|", this is the same as calling <code>{@link CmsMessages#key(String)}</code>.<p> If the key was not found in the bundle, the return value is <code>"??? " + keyName + " ???"</code>. This will also be returned if the bundle was not properly initialized first. @param keyName the key for the desired string, optinally containing parameters appended with a "|" @return the resource string for the given key @see #key(String, Object[]) @see #key(String)
[ "Returns", "the", "localized", "resource", "string", "for", "a", "given", "message", "key", "treating", "all", "values", "appended", "with", "|", "as", "replacement", "parameters", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/i18n/CmsMessages.java#L535-L548
Azure/azure-sdk-for-java
sql/resource-manager/v2015_05_01_preview/src/main/java/com/microsoft/azure/management/sql/v2015_05_01_preview/implementation/SyncGroupsInner.java
SyncGroupsInner.listLogsWithServiceResponseAsync
public Observable<ServiceResponse<Page<SyncGroupLogPropertiesInner>>> listLogsWithServiceResponseAsync(final String resourceGroupName, final String serverName, final String databaseName, final String syncGroupName, final String startTime, final String endTime, final String type, final String continuationToken) { """ Gets a collection of sync group logs. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param serverName The name of the server. @param databaseName The name of the database on which the sync group is hosted. @param syncGroupName The name of the sync group. @param startTime Get logs generated after this time. @param endTime Get logs generated before this time. @param type The types of logs to retrieve. Possible values include: 'All', 'Error', 'Warning', 'Success' @param continuationToken The continuation token for this operation. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;SyncGroupLogPropertiesInner&gt; object """ return listLogsSinglePageAsync(resourceGroupName, serverName, databaseName, syncGroupName, startTime, endTime, type, continuationToken) .concatMap(new Func1<ServiceResponse<Page<SyncGroupLogPropertiesInner>>, Observable<ServiceResponse<Page<SyncGroupLogPropertiesInner>>>>() { @Override public Observable<ServiceResponse<Page<SyncGroupLogPropertiesInner>>> call(ServiceResponse<Page<SyncGroupLogPropertiesInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listLogsNextWithServiceResponseAsync(nextPageLink)); } }); }
java
public Observable<ServiceResponse<Page<SyncGroupLogPropertiesInner>>> listLogsWithServiceResponseAsync(final String resourceGroupName, final String serverName, final String databaseName, final String syncGroupName, final String startTime, final String endTime, final String type, final String continuationToken) { return listLogsSinglePageAsync(resourceGroupName, serverName, databaseName, syncGroupName, startTime, endTime, type, continuationToken) .concatMap(new Func1<ServiceResponse<Page<SyncGroupLogPropertiesInner>>, Observable<ServiceResponse<Page<SyncGroupLogPropertiesInner>>>>() { @Override public Observable<ServiceResponse<Page<SyncGroupLogPropertiesInner>>> call(ServiceResponse<Page<SyncGroupLogPropertiesInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listLogsNextWithServiceResponseAsync(nextPageLink)); } }); }
[ "public", "Observable", "<", "ServiceResponse", "<", "Page", "<", "SyncGroupLogPropertiesInner", ">", ">", ">", "listLogsWithServiceResponseAsync", "(", "final", "String", "resourceGroupName", ",", "final", "String", "serverName", ",", "final", "String", "databaseName", ",", "final", "String", "syncGroupName", ",", "final", "String", "startTime", ",", "final", "String", "endTime", ",", "final", "String", "type", ",", "final", "String", "continuationToken", ")", "{", "return", "listLogsSinglePageAsync", "(", "resourceGroupName", ",", "serverName", ",", "databaseName", ",", "syncGroupName", ",", "startTime", ",", "endTime", ",", "type", ",", "continuationToken", ")", ".", "concatMap", "(", "new", "Func1", "<", "ServiceResponse", "<", "Page", "<", "SyncGroupLogPropertiesInner", ">", ">", ",", "Observable", "<", "ServiceResponse", "<", "Page", "<", "SyncGroupLogPropertiesInner", ">", ">", ">", ">", "(", ")", "{", "@", "Override", "public", "Observable", "<", "ServiceResponse", "<", "Page", "<", "SyncGroupLogPropertiesInner", ">", ">", ">", "call", "(", "ServiceResponse", "<", "Page", "<", "SyncGroupLogPropertiesInner", ">", ">", "page", ")", "{", "String", "nextPageLink", "=", "page", ".", "body", "(", ")", ".", "nextPageLink", "(", ")", ";", "if", "(", "nextPageLink", "==", "null", ")", "{", "return", "Observable", ".", "just", "(", "page", ")", ";", "}", "return", "Observable", ".", "just", "(", "page", ")", ".", "concatWith", "(", "listLogsNextWithServiceResponseAsync", "(", "nextPageLink", ")", ")", ";", "}", "}", ")", ";", "}" ]
Gets a collection of sync group logs. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param serverName The name of the server. @param databaseName The name of the database on which the sync group is hosted. @param syncGroupName The name of the sync group. @param startTime Get logs generated after this time. @param endTime Get logs generated before this time. @param type The types of logs to retrieve. Possible values include: 'All', 'Error', 'Warning', 'Success' @param continuationToken The continuation token for this operation. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;SyncGroupLogPropertiesInner&gt; object
[ "Gets", "a", "collection", "of", "sync", "group", "logs", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2015_05_01_preview/src/main/java/com/microsoft/azure/management/sql/v2015_05_01_preview/implementation/SyncGroupsInner.java#L828-L840
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/optimize/listeners/CheckpointListener.java
CheckpointListener.loadCheckpointCG
public static ComputationGraph loadCheckpointCG(File rootDir, int checkpointNum) { """ Load a ComputationGraph for the given checkpoint that resides in the specified root directory @param rootDir Directory that the checkpoint resides in @param checkpointNum Checkpoint model number to load @return The loaded model """ File f = getFileForCheckpoint(rootDir, checkpointNum); try { return ModelSerializer.restoreComputationGraph(f, true); } catch (IOException e){ throw new RuntimeException(e); } }
java
public static ComputationGraph loadCheckpointCG(File rootDir, int checkpointNum){ File f = getFileForCheckpoint(rootDir, checkpointNum); try { return ModelSerializer.restoreComputationGraph(f, true); } catch (IOException e){ throw new RuntimeException(e); } }
[ "public", "static", "ComputationGraph", "loadCheckpointCG", "(", "File", "rootDir", ",", "int", "checkpointNum", ")", "{", "File", "f", "=", "getFileForCheckpoint", "(", "rootDir", ",", "checkpointNum", ")", ";", "try", "{", "return", "ModelSerializer", ".", "restoreComputationGraph", "(", "f", ",", "true", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "}" ]
Load a ComputationGraph for the given checkpoint that resides in the specified root directory @param rootDir Directory that the checkpoint resides in @param checkpointNum Checkpoint model number to load @return The loaded model
[ "Load", "a", "ComputationGraph", "for", "the", "given", "checkpoint", "that", "resides", "in", "the", "specified", "root", "directory" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/optimize/listeners/CheckpointListener.java#L521-L528
joniles/mpxj
src/main/java/net/sf/mpxj/RecurringData.java
RecurringData.getYearlyAbsoluteDates
private void getYearlyAbsoluteDates(Calendar calendar, List<Date> dates) { """ Calculate start dates for a yearly absolute recurrence. @param calendar current date @param dates array of start dates """ long startDate = calendar.getTimeInMillis(); calendar.set(Calendar.DAY_OF_MONTH, 1); calendar.set(Calendar.MONTH, NumberHelper.getInt(m_monthNumber) - 1); int requiredDayNumber = NumberHelper.getInt(m_dayNumber); while (moreDates(calendar, dates)) { int useDayNumber = requiredDayNumber; int maxDayNumber = calendar.getActualMaximum(Calendar.DAY_OF_MONTH); if (useDayNumber > maxDayNumber) { useDayNumber = maxDayNumber; } calendar.set(Calendar.DAY_OF_MONTH, useDayNumber); if (calendar.getTimeInMillis() < startDate) { calendar.add(Calendar.YEAR, 1); } dates.add(calendar.getTime()); calendar.set(Calendar.DAY_OF_MONTH, 1); calendar.add(Calendar.YEAR, 1); } }
java
private void getYearlyAbsoluteDates(Calendar calendar, List<Date> dates) { long startDate = calendar.getTimeInMillis(); calendar.set(Calendar.DAY_OF_MONTH, 1); calendar.set(Calendar.MONTH, NumberHelper.getInt(m_monthNumber) - 1); int requiredDayNumber = NumberHelper.getInt(m_dayNumber); while (moreDates(calendar, dates)) { int useDayNumber = requiredDayNumber; int maxDayNumber = calendar.getActualMaximum(Calendar.DAY_OF_MONTH); if (useDayNumber > maxDayNumber) { useDayNumber = maxDayNumber; } calendar.set(Calendar.DAY_OF_MONTH, useDayNumber); if (calendar.getTimeInMillis() < startDate) { calendar.add(Calendar.YEAR, 1); } dates.add(calendar.getTime()); calendar.set(Calendar.DAY_OF_MONTH, 1); calendar.add(Calendar.YEAR, 1); } }
[ "private", "void", "getYearlyAbsoluteDates", "(", "Calendar", "calendar", ",", "List", "<", "Date", ">", "dates", ")", "{", "long", "startDate", "=", "calendar", ".", "getTimeInMillis", "(", ")", ";", "calendar", ".", "set", "(", "Calendar", ".", "DAY_OF_MONTH", ",", "1", ")", ";", "calendar", ".", "set", "(", "Calendar", ".", "MONTH", ",", "NumberHelper", ".", "getInt", "(", "m_monthNumber", ")", "-", "1", ")", ";", "int", "requiredDayNumber", "=", "NumberHelper", ".", "getInt", "(", "m_dayNumber", ")", ";", "while", "(", "moreDates", "(", "calendar", ",", "dates", ")", ")", "{", "int", "useDayNumber", "=", "requiredDayNumber", ";", "int", "maxDayNumber", "=", "calendar", ".", "getActualMaximum", "(", "Calendar", ".", "DAY_OF_MONTH", ")", ";", "if", "(", "useDayNumber", ">", "maxDayNumber", ")", "{", "useDayNumber", "=", "maxDayNumber", ";", "}", "calendar", ".", "set", "(", "Calendar", ".", "DAY_OF_MONTH", ",", "useDayNumber", ")", ";", "if", "(", "calendar", ".", "getTimeInMillis", "(", ")", "<", "startDate", ")", "{", "calendar", ".", "add", "(", "Calendar", ".", "YEAR", ",", "1", ")", ";", "}", "dates", ".", "add", "(", "calendar", ".", "getTime", "(", ")", ")", ";", "calendar", ".", "set", "(", "Calendar", ".", "DAY_OF_MONTH", ",", "1", ")", ";", "calendar", ".", "add", "(", "Calendar", ".", "YEAR", ",", "1", ")", ";", "}", "}" ]
Calculate start dates for a yearly absolute recurrence. @param calendar current date @param dates array of start dates
[ "Calculate", "start", "dates", "for", "a", "yearly", "absolute", "recurrence", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/RecurringData.java#L606-L632
liferay/com-liferay-commerce
commerce-account-service/src/main/java/com/liferay/commerce/account/service/persistence/impl/CommerceAccountUserRelPersistenceImpl.java
CommerceAccountUserRelPersistenceImpl.findByCommerceAccountId
@Override public List<CommerceAccountUserRel> findByCommerceAccountId( long commerceAccountId, int start, int end) { """ Returns a range of all the commerce account user rels where commerceAccountId = &#63;. <p> Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommerceAccountUserRelModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. </p> @param commerceAccountId the commerce account ID @param start the lower bound of the range of commerce account user rels @param end the upper bound of the range of commerce account user rels (not inclusive) @return the range of matching commerce account user rels """ return findByCommerceAccountId(commerceAccountId, start, end, null); }
java
@Override public List<CommerceAccountUserRel> findByCommerceAccountId( long commerceAccountId, int start, int end) { return findByCommerceAccountId(commerceAccountId, start, end, null); }
[ "@", "Override", "public", "List", "<", "CommerceAccountUserRel", ">", "findByCommerceAccountId", "(", "long", "commerceAccountId", ",", "int", "start", ",", "int", "end", ")", "{", "return", "findByCommerceAccountId", "(", "commerceAccountId", ",", "start", ",", "end", ",", "null", ")", ";", "}" ]
Returns a range of all the commerce account user rels where commerceAccountId = &#63;. <p> Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommerceAccountUserRelModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. </p> @param commerceAccountId the commerce account ID @param start the lower bound of the range of commerce account user rels @param end the upper bound of the range of commerce account user rels (not inclusive) @return the range of matching commerce account user rels
[ "Returns", "a", "range", "of", "all", "the", "commerce", "account", "user", "rels", "where", "commerceAccountId", "=", "&#63", ";", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-account-service/src/main/java/com/liferay/commerce/account/service/persistence/impl/CommerceAccountUserRelPersistenceImpl.java#L142-L146
deeplearning4j/deeplearning4j
nd4j/nd4j-parameter-server-parent/nd4j-parameter-server-node/src/main/java/org/nd4j/parameterserver/distributed/v2/transport/impl/AeronUdpTransport.java
AeronUdpTransport.addInterceptor
public <T extends VoidMessage> void addInterceptor(@NonNull Class<T> cls, @NonNull MessageCallable<T> callable) { """ This method add interceptor for incoming messages. If interceptor is defined for given message class - runnable will be executed instead of processMessage() @param cls @param callable """ interceptors.put(cls.getCanonicalName(), callable); }
java
public <T extends VoidMessage> void addInterceptor(@NonNull Class<T> cls, @NonNull MessageCallable<T> callable) { interceptors.put(cls.getCanonicalName(), callable); }
[ "public", "<", "T", "extends", "VoidMessage", ">", "void", "addInterceptor", "(", "@", "NonNull", "Class", "<", "T", ">", "cls", ",", "@", "NonNull", "MessageCallable", "<", "T", ">", "callable", ")", "{", "interceptors", ".", "put", "(", "cls", ".", "getCanonicalName", "(", ")", ",", "callable", ")", ";", "}" ]
This method add interceptor for incoming messages. If interceptor is defined for given message class - runnable will be executed instead of processMessage() @param cls @param callable
[ "This", "method", "add", "interceptor", "for", "incoming", "messages", ".", "If", "interceptor", "is", "defined", "for", "given", "message", "class", "-", "runnable", "will", "be", "executed", "instead", "of", "processMessage", "()" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-parameter-server-parent/nd4j-parameter-server-node/src/main/java/org/nd4j/parameterserver/distributed/v2/transport/impl/AeronUdpTransport.java#L531-L533
alkacon/opencms-core
src/org/opencms/importexport/CmsImportExportManager.java
CmsImportExportManager.importData
public void importData(CmsObject cms, I_CmsReport report, CmsImportParameters parameters) throws CmsImportExportException, CmsXmlException, CmsRoleViolationException, CmsException { """ Checks if the current user has permissions to import data into the Cms, and if so, creates a new import handler instance that imports the data.<p> @param cms the current OpenCms context object @param report a Cms report to print log messages @param parameters the import parameters @throws CmsRoleViolationException if the current user is not allowed to import the OpenCms database @throws CmsImportExportException if operation was not successful @throws CmsXmlException if the manifest of the import could not be unmarshalled @throws CmsException in case of errors accessing the VFS @see I_CmsImportExportHandler @see #importData(CmsObject, String, String, I_CmsReport) """ // check the required role permissions OpenCms.getRoleManager().checkRole(cms, CmsRole.DATABASE_MANAGER); try { OpenCms.fireCmsEvent( new CmsEvent(I_CmsEventListener.EVENT_CLEAR_CACHES, Collections.<String, Object> emptyMap())); I_CmsImportExportHandler handler = getImportExportHandler(parameters); synchronized (handler) { handler.setImportParameters(parameters); handler.importData(cms, report); } } finally { OpenCms.fireCmsEvent( new CmsEvent(I_CmsEventListener.EVENT_CLEAR_CACHES, Collections.<String, Object> emptyMap())); } }
java
public void importData(CmsObject cms, I_CmsReport report, CmsImportParameters parameters) throws CmsImportExportException, CmsXmlException, CmsRoleViolationException, CmsException { // check the required role permissions OpenCms.getRoleManager().checkRole(cms, CmsRole.DATABASE_MANAGER); try { OpenCms.fireCmsEvent( new CmsEvent(I_CmsEventListener.EVENT_CLEAR_CACHES, Collections.<String, Object> emptyMap())); I_CmsImportExportHandler handler = getImportExportHandler(parameters); synchronized (handler) { handler.setImportParameters(parameters); handler.importData(cms, report); } } finally { OpenCms.fireCmsEvent( new CmsEvent(I_CmsEventListener.EVENT_CLEAR_CACHES, Collections.<String, Object> emptyMap())); } }
[ "public", "void", "importData", "(", "CmsObject", "cms", ",", "I_CmsReport", "report", ",", "CmsImportParameters", "parameters", ")", "throws", "CmsImportExportException", ",", "CmsXmlException", ",", "CmsRoleViolationException", ",", "CmsException", "{", "// check the required role permissions", "OpenCms", ".", "getRoleManager", "(", ")", ".", "checkRole", "(", "cms", ",", "CmsRole", ".", "DATABASE_MANAGER", ")", ";", "try", "{", "OpenCms", ".", "fireCmsEvent", "(", "new", "CmsEvent", "(", "I_CmsEventListener", ".", "EVENT_CLEAR_CACHES", ",", "Collections", ".", "<", "String", ",", "Object", ">", "emptyMap", "(", ")", ")", ")", ";", "I_CmsImportExportHandler", "handler", "=", "getImportExportHandler", "(", "parameters", ")", ";", "synchronized", "(", "handler", ")", "{", "handler", ".", "setImportParameters", "(", "parameters", ")", ";", "handler", ".", "importData", "(", "cms", ",", "report", ")", ";", "}", "}", "finally", "{", "OpenCms", ".", "fireCmsEvent", "(", "new", "CmsEvent", "(", "I_CmsEventListener", ".", "EVENT_CLEAR_CACHES", ",", "Collections", ".", "<", "String", ",", "Object", ">", "emptyMap", "(", ")", ")", ")", ";", "}", "}" ]
Checks if the current user has permissions to import data into the Cms, and if so, creates a new import handler instance that imports the data.<p> @param cms the current OpenCms context object @param report a Cms report to print log messages @param parameters the import parameters @throws CmsRoleViolationException if the current user is not allowed to import the OpenCms database @throws CmsImportExportException if operation was not successful @throws CmsXmlException if the manifest of the import could not be unmarshalled @throws CmsException in case of errors accessing the VFS @see I_CmsImportExportHandler @see #importData(CmsObject, String, String, I_CmsReport)
[ "Checks", "if", "the", "current", "user", "has", "permissions", "to", "import", "data", "into", "the", "Cms", "and", "if", "so", "creates", "a", "new", "import", "handler", "instance", "that", "imports", "the", "data", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/importexport/CmsImportExportManager.java#L891-L909
google/flogger
api/src/main/java/com/google/common/flogger/LogContext.java
LogContext.logImpl
@SuppressWarnings("ReferenceEquality") private void logImpl(String message, Object... args) { """ Make the backend logging call. This is the point at which we have paid the price of creating a varargs array and doing any necessary auto-boxing. """ this.args = args; // Evaluate any (rare) LazyArg instances early. This may throw exceptions from user code, but // it seems reasonable to propagate them in this case (they would have been thrown if the // argument was evaluated at the call site anyway). for (int n = 0; n < args.length; n++) { if (args[n] instanceof LazyArg) { args[n] = ((LazyArg<?>) args[n]).evaluate(); } } // Using "!=" is fast and sufficient here because the only real case this should be skipping // is when we called log(String) or log(), which should not result in a template being created. // DO NOT replace this with a string instance which can be interned, or use equals() here, // since that could mistakenly treat other calls to log(String, Object...) incorrectly. if (message != LITERAL_VALUE_MESSAGE) { this.templateContext = new TemplateContext(getMessageParser(), message); } getLogger().write(this); }
java
@SuppressWarnings("ReferenceEquality") private void logImpl(String message, Object... args) { this.args = args; // Evaluate any (rare) LazyArg instances early. This may throw exceptions from user code, but // it seems reasonable to propagate them in this case (they would have been thrown if the // argument was evaluated at the call site anyway). for (int n = 0; n < args.length; n++) { if (args[n] instanceof LazyArg) { args[n] = ((LazyArg<?>) args[n]).evaluate(); } } // Using "!=" is fast and sufficient here because the only real case this should be skipping // is when we called log(String) or log(), which should not result in a template being created. // DO NOT replace this with a string instance which can be interned, or use equals() here, // since that could mistakenly treat other calls to log(String, Object...) incorrectly. if (message != LITERAL_VALUE_MESSAGE) { this.templateContext = new TemplateContext(getMessageParser(), message); } getLogger().write(this); }
[ "@", "SuppressWarnings", "(", "\"ReferenceEquality\"", ")", "private", "void", "logImpl", "(", "String", "message", ",", "Object", "...", "args", ")", "{", "this", ".", "args", "=", "args", ";", "// Evaluate any (rare) LazyArg instances early. This may throw exceptions from user code, but", "// it seems reasonable to propagate them in this case (they would have been thrown if the", "// argument was evaluated at the call site anyway).", "for", "(", "int", "n", "=", "0", ";", "n", "<", "args", ".", "length", ";", "n", "++", ")", "{", "if", "(", "args", "[", "n", "]", "instanceof", "LazyArg", ")", "{", "args", "[", "n", "]", "=", "(", "(", "LazyArg", "<", "?", ">", ")", "args", "[", "n", "]", ")", ".", "evaluate", "(", ")", ";", "}", "}", "// Using \"!=\" is fast and sufficient here because the only real case this should be skipping", "// is when we called log(String) or log(), which should not result in a template being created.", "// DO NOT replace this with a string instance which can be interned, or use equals() here,", "// since that could mistakenly treat other calls to log(String, Object...) incorrectly.", "if", "(", "message", "!=", "LITERAL_VALUE_MESSAGE", ")", "{", "this", ".", "templateContext", "=", "new", "TemplateContext", "(", "getMessageParser", "(", ")", ",", "message", ")", ";", "}", "getLogger", "(", ")", ".", "write", "(", "this", ")", ";", "}" ]
Make the backend logging call. This is the point at which we have paid the price of creating a varargs array and doing any necessary auto-boxing.
[ "Make", "the", "backend", "logging", "call", ".", "This", "is", "the", "point", "at", "which", "we", "have", "paid", "the", "price", "of", "creating", "a", "varargs", "array", "and", "doing", "any", "necessary", "auto", "-", "boxing", "." ]
train
https://github.com/google/flogger/blob/a164967a93a9f4ce92f34319fc0cc7c91a57321c/api/src/main/java/com/google/common/flogger/LogContext.java#L548-L567
msteiger/jxmapviewer2
jxmapviewer2/src/main/java/org/jxmapviewer/viewer/LocalResponseCache.java
LocalResponseCache.installResponseCache
@Deprecated public static void installResponseCache(String baseURL, File cacheDir, boolean checkForUpdates) { """ Sets this cache as default response cache @param baseURL the URL, the caching should be restricted to or <code>null</code> for none @param cacheDir the cache directory @param checkForUpdates true if the URL is queried for newer versions of a file first @deprecated Use {@link TileFactory#setLocalCache(LocalCache)} instead """ ResponseCache.setDefault(new LocalResponseCache(baseURL, cacheDir, checkForUpdates)); }
java
@Deprecated public static void installResponseCache(String baseURL, File cacheDir, boolean checkForUpdates) { ResponseCache.setDefault(new LocalResponseCache(baseURL, cacheDir, checkForUpdates)); }
[ "@", "Deprecated", "public", "static", "void", "installResponseCache", "(", "String", "baseURL", ",", "File", "cacheDir", ",", "boolean", "checkForUpdates", ")", "{", "ResponseCache", ".", "setDefault", "(", "new", "LocalResponseCache", "(", "baseURL", ",", "cacheDir", ",", "checkForUpdates", ")", ")", ";", "}" ]
Sets this cache as default response cache @param baseURL the URL, the caching should be restricted to or <code>null</code> for none @param cacheDir the cache directory @param checkForUpdates true if the URL is queried for newer versions of a file first @deprecated Use {@link TileFactory#setLocalCache(LocalCache)} instead
[ "Sets", "this", "cache", "as", "default", "response", "cache" ]
train
https://github.com/msteiger/jxmapviewer2/blob/82639273b0aac983b6026fb90aa925c0cf596410/jxmapviewer2/src/main/java/org/jxmapviewer/viewer/LocalResponseCache.java#L55-L59
alkacon/opencms-core
src/org/opencms/jlan/CmsJlanDiskInterface.java
CmsJlanDiskInterface.getFileForPath
protected CmsJlanNetworkFile getFileForPath( CmsObjectWrapper cms, SrvSession session, TreeConnection connection, String path) throws CmsException { """ Helper method to get a network file object given a path.<p> @param cms the CMS context wrapper @param session the current session @param connection the current connection @param path the file path @return the network file object for the given path @throws CmsException if something goes wrong """ try { String cmsPath = getCmsPath(path); CmsResource resource = cms.readResource(cmsPath, STANDARD_FILTER); CmsJlanNetworkFile result = new CmsJlanNetworkFile(cms, resource, path); return result; } catch (CmsVfsResourceNotFoundException e) { return null; } }
java
protected CmsJlanNetworkFile getFileForPath( CmsObjectWrapper cms, SrvSession session, TreeConnection connection, String path) throws CmsException { try { String cmsPath = getCmsPath(path); CmsResource resource = cms.readResource(cmsPath, STANDARD_FILTER); CmsJlanNetworkFile result = new CmsJlanNetworkFile(cms, resource, path); return result; } catch (CmsVfsResourceNotFoundException e) { return null; } }
[ "protected", "CmsJlanNetworkFile", "getFileForPath", "(", "CmsObjectWrapper", "cms", ",", "SrvSession", "session", ",", "TreeConnection", "connection", ",", "String", "path", ")", "throws", "CmsException", "{", "try", "{", "String", "cmsPath", "=", "getCmsPath", "(", "path", ")", ";", "CmsResource", "resource", "=", "cms", ".", "readResource", "(", "cmsPath", ",", "STANDARD_FILTER", ")", ";", "CmsJlanNetworkFile", "result", "=", "new", "CmsJlanNetworkFile", "(", "cms", ",", "resource", ",", "path", ")", ";", "return", "result", ";", "}", "catch", "(", "CmsVfsResourceNotFoundException", "e", ")", "{", "return", "null", ";", "}", "}" ]
Helper method to get a network file object given a path.<p> @param cms the CMS context wrapper @param session the current session @param connection the current connection @param path the file path @return the network file object for the given path @throws CmsException if something goes wrong
[ "Helper", "method", "to", "get", "a", "network", "file", "object", "given", "a", "path", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/jlan/CmsJlanDiskInterface.java#L448-L462
aws/aws-sdk-java
aws-java-sdk-core/src/main/java/com/amazonaws/monitoring/ProfileCsmConfigurationProvider.java
ProfileCsmConfigurationProvider.getProfilesConfigFile
private ProfilesConfigFile getProfilesConfigFile() { """ ProfilesConfigFile immediately loads the profiles at construction time """ if (configFile == null) { synchronized (this) { if (configFile == null) { try { configFile = new ProfilesConfigFile(configFileLocationProvider.getLocation()); } catch (Exception e) { throw new SdkClientException("Unable to load config file", e); } } } } return configFile; }
java
private ProfilesConfigFile getProfilesConfigFile() { if (configFile == null) { synchronized (this) { if (configFile == null) { try { configFile = new ProfilesConfigFile(configFileLocationProvider.getLocation()); } catch (Exception e) { throw new SdkClientException("Unable to load config file", e); } } } } return configFile; }
[ "private", "ProfilesConfigFile", "getProfilesConfigFile", "(", ")", "{", "if", "(", "configFile", "==", "null", ")", "{", "synchronized", "(", "this", ")", "{", "if", "(", "configFile", "==", "null", ")", "{", "try", "{", "configFile", "=", "new", "ProfilesConfigFile", "(", "configFileLocationProvider", ".", "getLocation", "(", ")", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "SdkClientException", "(", "\"Unable to load config file\"", ",", "e", ")", ";", "}", "}", "}", "}", "return", "configFile", ";", "}" ]
ProfilesConfigFile immediately loads the profiles at construction time
[ "ProfilesConfigFile", "immediately", "loads", "the", "profiles", "at", "construction", "time" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-core/src/main/java/com/amazonaws/monitoring/ProfileCsmConfigurationProvider.java#L132-L145
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/utils/style/StyleUtilities.java
StyleUtilities.substituteExternalGraphics
public static void substituteExternalGraphics( Rule rule, URL externalGraphicsUrl ) { """ Change the external graphic in a rule. @param rule the rule of which the external graphic has to be changed. @param path the path of the image. """ String urlString = externalGraphicsUrl.toString(); String format = ""; if (urlString.toLowerCase().endsWith(".png")) { format = "image/png"; } else if (urlString.toLowerCase().endsWith(".jpg")) { format = "image/jpg"; } else if (urlString.toLowerCase().endsWith(".svg")) { format = "image/svg+xml"; } else { urlString = ""; try { externalGraphicsUrl = new URL("file:"); } catch (MalformedURLException e) { e.printStackTrace(); } } PointSymbolizer pointSymbolizer = StyleUtilities.pointSymbolizerFromRule(rule); Graphic graphic = SLD.graphic(pointSymbolizer); graphic.graphicalSymbols().clear(); ExternalGraphic exGraphic = sf.createExternalGraphic(externalGraphicsUrl, format); graphic.graphicalSymbols().add(exGraphic); }
java
public static void substituteExternalGraphics( Rule rule, URL externalGraphicsUrl ) { String urlString = externalGraphicsUrl.toString(); String format = ""; if (urlString.toLowerCase().endsWith(".png")) { format = "image/png"; } else if (urlString.toLowerCase().endsWith(".jpg")) { format = "image/jpg"; } else if (urlString.toLowerCase().endsWith(".svg")) { format = "image/svg+xml"; } else { urlString = ""; try { externalGraphicsUrl = new URL("file:"); } catch (MalformedURLException e) { e.printStackTrace(); } } PointSymbolizer pointSymbolizer = StyleUtilities.pointSymbolizerFromRule(rule); Graphic graphic = SLD.graphic(pointSymbolizer); graphic.graphicalSymbols().clear(); ExternalGraphic exGraphic = sf.createExternalGraphic(externalGraphicsUrl, format); graphic.graphicalSymbols().add(exGraphic); }
[ "public", "static", "void", "substituteExternalGraphics", "(", "Rule", "rule", ",", "URL", "externalGraphicsUrl", ")", "{", "String", "urlString", "=", "externalGraphicsUrl", ".", "toString", "(", ")", ";", "String", "format", "=", "\"\"", ";", "if", "(", "urlString", ".", "toLowerCase", "(", ")", ".", "endsWith", "(", "\".png\"", ")", ")", "{", "format", "=", "\"image/png\"", ";", "}", "else", "if", "(", "urlString", ".", "toLowerCase", "(", ")", ".", "endsWith", "(", "\".jpg\"", ")", ")", "{", "format", "=", "\"image/jpg\"", ";", "}", "else", "if", "(", "urlString", ".", "toLowerCase", "(", ")", ".", "endsWith", "(", "\".svg\"", ")", ")", "{", "format", "=", "\"image/svg+xml\"", ";", "}", "else", "{", "urlString", "=", "\"\"", ";", "try", "{", "externalGraphicsUrl", "=", "new", "URL", "(", "\"file:\"", ")", ";", "}", "catch", "(", "MalformedURLException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "}", "PointSymbolizer", "pointSymbolizer", "=", "StyleUtilities", ".", "pointSymbolizerFromRule", "(", "rule", ")", ";", "Graphic", "graphic", "=", "SLD", ".", "graphic", "(", "pointSymbolizer", ")", ";", "graphic", ".", "graphicalSymbols", "(", ")", ".", "clear", "(", ")", ";", "ExternalGraphic", "exGraphic", "=", "sf", ".", "createExternalGraphic", "(", "externalGraphicsUrl", ",", "format", ")", ";", "graphic", ".", "graphicalSymbols", "(", ")", ".", "add", "(", "exGraphic", ")", ";", "}" ]
Change the external graphic in a rule. @param rule the rule of which the external graphic has to be changed. @param path the path of the image.
[ "Change", "the", "external", "graphic", "in", "a", "rule", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/style/StyleUtilities.java#L597-L621
samskivert/samskivert
src/main/java/com/samskivert/text/MessageUtil.java
MessageUtil.tcompose
public static String tcompose (String key, Object... args) { """ A convenience method for calling {@link #compose(String,Object[])} with an array of arguments that will be automatically tainted (see {@link #taint}). """ int acount = args.length; String[] targs = new String[acount]; for (int ii = 0; ii < acount; ii++) { targs[ii] = taint(args[ii]); } return compose(key, (Object[]) targs); }
java
public static String tcompose (String key, Object... args) { int acount = args.length; String[] targs = new String[acount]; for (int ii = 0; ii < acount; ii++) { targs[ii] = taint(args[ii]); } return compose(key, (Object[]) targs); }
[ "public", "static", "String", "tcompose", "(", "String", "key", ",", "Object", "...", "args", ")", "{", "int", "acount", "=", "args", ".", "length", ";", "String", "[", "]", "targs", "=", "new", "String", "[", "acount", "]", ";", "for", "(", "int", "ii", "=", "0", ";", "ii", "<", "acount", ";", "ii", "++", ")", "{", "targs", "[", "ii", "]", "=", "taint", "(", "args", "[", "ii", "]", ")", ";", "}", "return", "compose", "(", "key", ",", "(", "Object", "[", "]", ")", "targs", ")", ";", "}" ]
A convenience method for calling {@link #compose(String,Object[])} with an array of arguments that will be automatically tainted (see {@link #taint}).
[ "A", "convenience", "method", "for", "calling", "{" ]
train
https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/text/MessageUtil.java#L129-L137
jparsec/jparsec
jparsec/src/main/java/org/jparsec/pattern/Patterns.java
Patterns.many
public static Pattern many(final CharPredicate predicate) { """ Returns a {@link Pattern} that matches 0 or more characters satisfying {@code predicate}. """ return new Pattern() { @Override public int match(CharSequence src, int begin, int end) { return matchMany(predicate, src, end, begin, 0); } @Override public String toString() { return predicate + "*"; } }; }
java
public static Pattern many(final CharPredicate predicate) { return new Pattern() { @Override public int match(CharSequence src, int begin, int end) { return matchMany(predicate, src, end, begin, 0); } @Override public String toString() { return predicate + "*"; } }; }
[ "public", "static", "Pattern", "many", "(", "final", "CharPredicate", "predicate", ")", "{", "return", "new", "Pattern", "(", ")", "{", "@", "Override", "public", "int", "match", "(", "CharSequence", "src", ",", "int", "begin", ",", "int", "end", ")", "{", "return", "matchMany", "(", "predicate", ",", "src", ",", "end", ",", "begin", ",", "0", ")", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "predicate", "+", "\"*\"", ";", "}", "}", ";", "}" ]
Returns a {@link Pattern} that matches 0 or more characters satisfying {@code predicate}.
[ "Returns", "a", "{" ]
train
https://github.com/jparsec/jparsec/blob/df1280259f5da9eb5ffc537437569dddba66cb94/jparsec/src/main/java/org/jparsec/pattern/Patterns.java#L384-L393
OpenLiberty/open-liberty
dev/com.ibm.ws.jaxws.clientcontainer/src/com/ibm/ws/jaxws/client/LibertyCustomizeBindingOutInterceptor.java
LibertyCustomizeBindingOutInterceptor.buildQName
public static QName buildQName(String namespace, String localName) { """ build the qname with the given, and make sure the namespace is ended with "/" if specified. @param portNameSpace @param portLocalName @return """ String namespaceURI = namespace; if (!isEmpty(namespace) && !namespace.trim().endsWith("/")) { namespaceURI += "/"; } return new QName(namespaceURI, localName); }
java
public static QName buildQName(String namespace, String localName) { String namespaceURI = namespace; if (!isEmpty(namespace) && !namespace.trim().endsWith("/")) { namespaceURI += "/"; } return new QName(namespaceURI, localName); }
[ "public", "static", "QName", "buildQName", "(", "String", "namespace", ",", "String", "localName", ")", "{", "String", "namespaceURI", "=", "namespace", ";", "if", "(", "!", "isEmpty", "(", "namespace", ")", "&&", "!", "namespace", ".", "trim", "(", ")", ".", "endsWith", "(", "\"/\"", ")", ")", "{", "namespaceURI", "+=", "\"/\"", ";", "}", "return", "new", "QName", "(", "namespaceURI", ",", "localName", ")", ";", "}" ]
build the qname with the given, and make sure the namespace is ended with "/" if specified. @param portNameSpace @param portLocalName @return
[ "build", "the", "qname", "with", "the", "given", "and", "make", "sure", "the", "namespace", "is", "ended", "with", "/", "if", "specified", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jaxws.clientcontainer/src/com/ibm/ws/jaxws/client/LibertyCustomizeBindingOutInterceptor.java#L124-L133
landawn/AbacusUtil
src/com/landawn/abacus/util/N.java
N.runUninterruptibly
public static void runUninterruptibly(final long timeoutInMillis, final Try.LongConsumer<InterruptedException> cmd) { """ Note: Copied from Google Guava under Apache License v2.0 <br /> <br /> If a thread is interrupted during such a call, the call continues to block until the result is available or the timeout elapses, and only then re-interrupts the thread. @param timeoutInMillis @param cmd """ N.checkArgNotNull(cmd); boolean interrupted = false; try { long remainingMillis = timeoutInMillis; final long sysMillis = System.currentTimeMillis(); final long end = remainingMillis >= Long.MAX_VALUE - sysMillis ? Long.MAX_VALUE : sysMillis + remainingMillis; while (true) { try { cmd.accept(remainingMillis); return; } catch (InterruptedException e) { interrupted = true; remainingMillis = end - System.currentTimeMillis(); } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } }
java
public static void runUninterruptibly(final long timeoutInMillis, final Try.LongConsumer<InterruptedException> cmd) { N.checkArgNotNull(cmd); boolean interrupted = false; try { long remainingMillis = timeoutInMillis; final long sysMillis = System.currentTimeMillis(); final long end = remainingMillis >= Long.MAX_VALUE - sysMillis ? Long.MAX_VALUE : sysMillis + remainingMillis; while (true) { try { cmd.accept(remainingMillis); return; } catch (InterruptedException e) { interrupted = true; remainingMillis = end - System.currentTimeMillis(); } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } }
[ "public", "static", "void", "runUninterruptibly", "(", "final", "long", "timeoutInMillis", ",", "final", "Try", ".", "LongConsumer", "<", "InterruptedException", ">", "cmd", ")", "{", "N", ".", "checkArgNotNull", "(", "cmd", ")", ";", "boolean", "interrupted", "=", "false", ";", "try", "{", "long", "remainingMillis", "=", "timeoutInMillis", ";", "final", "long", "sysMillis", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "final", "long", "end", "=", "remainingMillis", ">=", "Long", ".", "MAX_VALUE", "-", "sysMillis", "?", "Long", ".", "MAX_VALUE", ":", "sysMillis", "+", "remainingMillis", ";", "while", "(", "true", ")", "{", "try", "{", "cmd", ".", "accept", "(", "remainingMillis", ")", ";", "return", ";", "}", "catch", "(", "InterruptedException", "e", ")", "{", "interrupted", "=", "true", ";", "remainingMillis", "=", "end", "-", "System", ".", "currentTimeMillis", "(", ")", ";", "}", "}", "}", "finally", "{", "if", "(", "interrupted", ")", "{", "Thread", ".", "currentThread", "(", ")", ".", "interrupt", "(", ")", ";", "}", "}", "}" ]
Note: Copied from Google Guava under Apache License v2.0 <br /> <br /> If a thread is interrupted during such a call, the call continues to block until the result is available or the timeout elapses, and only then re-interrupts the thread. @param timeoutInMillis @param cmd
[ "Note", ":", "Copied", "from", "Google", "Guava", "under", "Apache", "License", "v2", ".", "0", "<br", "/", ">", "<br", "/", ">" ]
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/N.java#L27962-L27986
lievendoclo/Valkyrie-RCP
valkyrie-rcp-core/src/main/java/org/valkyriercp/rules/constraint/Constraints.java
Constraints.lte
public PropertyConstraint lte(String propertyName, Comparable propertyValue) { """ Apply a "less than equal to" constraint to a bean property. @param propertyName The first property @param propertyValue The constraint value @return The constraint """ return new ParameterizedPropertyConstraint(propertyName, lte(propertyValue)); }
java
public PropertyConstraint lte(String propertyName, Comparable propertyValue) { return new ParameterizedPropertyConstraint(propertyName, lte(propertyValue)); }
[ "public", "PropertyConstraint", "lte", "(", "String", "propertyName", ",", "Comparable", "propertyValue", ")", "{", "return", "new", "ParameterizedPropertyConstraint", "(", "propertyName", ",", "lte", "(", "propertyValue", ")", ")", ";", "}" ]
Apply a "less than equal to" constraint to a bean property. @param propertyName The first property @param propertyValue The constraint value @return The constraint
[ "Apply", "a", "less", "than", "equal", "to", "constraint", "to", "a", "bean", "property", "." ]
train
https://github.com/lievendoclo/Valkyrie-RCP/blob/6aad6e640b348cda8f3b0841f6e42025233f1eb8/valkyrie-rcp-core/src/main/java/org/valkyriercp/rules/constraint/Constraints.java#L724-L726
foundation-runtime/service-directory
2.0/sd-api/src/main/java/com/cisco/oss/foundation/directory/impl/DirectoryRegistrationService.java
DirectoryRegistrationService.setUserPermission
public void setUserPermission(String userName, Permission permission) { """ Set the user permission. @param userName the user name. @param permission the user permission. """ if(permission == null){ permission = Permission.NONE; } getServiceDirectoryClient().setACL(new ACL(AuthScheme.DIRECTORY, userName, permission.getId())); }
java
public void setUserPermission(String userName, Permission permission){ if(permission == null){ permission = Permission.NONE; } getServiceDirectoryClient().setACL(new ACL(AuthScheme.DIRECTORY, userName, permission.getId())); }
[ "public", "void", "setUserPermission", "(", "String", "userName", ",", "Permission", "permission", ")", "{", "if", "(", "permission", "==", "null", ")", "{", "permission", "=", "Permission", ".", "NONE", ";", "}", "getServiceDirectoryClient", "(", ")", ".", "setACL", "(", "new", "ACL", "(", "AuthScheme", ".", "DIRECTORY", ",", "userName", ",", "permission", ".", "getId", "(", ")", ")", ")", ";", "}" ]
Set the user permission. @param userName the user name. @param permission the user permission.
[ "Set", "the", "user", "permission", "." ]
train
https://github.com/foundation-runtime/service-directory/blob/a7bdefe173dc99e75eff4a24e07e6407e62f2ed4/2.0/sd-api/src/main/java/com/cisco/oss/foundation/directory/impl/DirectoryRegistrationService.java#L265-L270
haraldk/TwelveMonkeys
sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/DebugUtil.java
DebugUtil.printTimestamp
public static void printTimestamp(final Calendar pCalendar, final PrintStream pPrintStream) { """ Prints out the calendar time. <p> @param pCalendar the {@code java.util.Calendar} object from which to extract the date information. @param pPrintStream the {@code java.io.PrintStream} for flushing the results. @see <a href="http://java.sun.com/products/jdk/1.3/docs/api/java/util/Calendar.html">{@code java.util.Calendar}</a> """ if (pPrintStream == null) { System.err.println(PRINTSTREAM_IS_NULL_ERROR_MESSAGE); return; } pPrintStream.println(getTimestamp(pCalendar)); }
java
public static void printTimestamp(final Calendar pCalendar, final PrintStream pPrintStream) { if (pPrintStream == null) { System.err.println(PRINTSTREAM_IS_NULL_ERROR_MESSAGE); return; } pPrintStream.println(getTimestamp(pCalendar)); }
[ "public", "static", "void", "printTimestamp", "(", "final", "Calendar", "pCalendar", ",", "final", "PrintStream", "pPrintStream", ")", "{", "if", "(", "pPrintStream", "==", "null", ")", "{", "System", ".", "err", ".", "println", "(", "PRINTSTREAM_IS_NULL_ERROR_MESSAGE", ")", ";", "return", ";", "}", "pPrintStream", ".", "println", "(", "getTimestamp", "(", "pCalendar", ")", ")", ";", "}" ]
Prints out the calendar time. <p> @param pCalendar the {@code java.util.Calendar} object from which to extract the date information. @param pPrintStream the {@code java.io.PrintStream} for flushing the results. @see <a href="http://java.sun.com/products/jdk/1.3/docs/api/java/util/Calendar.html">{@code java.util.Calendar}</a>
[ "Prints", "out", "the", "calendar", "time", ".", "<p", ">" ]
train
https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/DebugUtil.java#L737-L744
OpenLiberty/open-liberty
dev/com.ibm.ws.webcontainer/src/com/ibm/ws/webcontainer/srt/SRTServletResponse.java
SRTServletResponse.getOutputStream
public ServletOutputStream getOutputStream() { """ Returns an output stream for writing binary response data. @see reinitStreamState """ final boolean isTraceOn = com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled(); if (isTraceOn&&logger.isLoggable (Level.FINE)) //306998.15 logger.entering(CLASS_NAME,"getOutputStream","gotWriter="+String.valueOf(_gotWriter)+" ["+this+"]"); if (!_ignoreStateErrors && _gotWriter) { if (isTraceOn&&logger.isLoggable (Level.FINE)) //306998.15 logger.exiting(CLASS_NAME,"getOutputStream","throw IllegalStateException"); throw new IllegalStateException(nls.getString("Writer.already.obtained", "Writer already obtained")); } //PK89810 Start if(!(WCCustomProperties.FINISH_RESPONSE_ON_CLOSE) || ! _gotOutputStream) { _gotOutputStream = true; // LIBERTY _bufferedOut.init(_rawOut, getBufferSize()); // LIBERTY _bufferedOut.setLimit(_contentLength); // LIBERTY _bufferedOut.setResponse(_response); // LIBERTY _responseBuffer = _bufferedOut; } //PK89810 End this.fireOutputStreamRetrievedEvent(_bufferedOut); if (isTraceOn&&logger.isLoggable (Level.FINE)) //306998.15 logger.exiting(CLASS_NAME,"getOutputStream"); return _bufferedOut; }
java
public ServletOutputStream getOutputStream() { final boolean isTraceOn = com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled(); if (isTraceOn&&logger.isLoggable (Level.FINE)) //306998.15 logger.entering(CLASS_NAME,"getOutputStream","gotWriter="+String.valueOf(_gotWriter)+" ["+this+"]"); if (!_ignoreStateErrors && _gotWriter) { if (isTraceOn&&logger.isLoggable (Level.FINE)) //306998.15 logger.exiting(CLASS_NAME,"getOutputStream","throw IllegalStateException"); throw new IllegalStateException(nls.getString("Writer.already.obtained", "Writer already obtained")); } //PK89810 Start if(!(WCCustomProperties.FINISH_RESPONSE_ON_CLOSE) || ! _gotOutputStream) { _gotOutputStream = true; // LIBERTY _bufferedOut.init(_rawOut, getBufferSize()); // LIBERTY _bufferedOut.setLimit(_contentLength); // LIBERTY _bufferedOut.setResponse(_response); // LIBERTY _responseBuffer = _bufferedOut; } //PK89810 End this.fireOutputStreamRetrievedEvent(_bufferedOut); if (isTraceOn&&logger.isLoggable (Level.FINE)) //306998.15 logger.exiting(CLASS_NAME,"getOutputStream"); return _bufferedOut; }
[ "public", "ServletOutputStream", "getOutputStream", "(", ")", "{", "final", "boolean", "isTraceOn", "=", "com", ".", "ibm", ".", "ejs", ".", "ras", ".", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", ";", "if", "(", "isTraceOn", "&&", "logger", ".", "isLoggable", "(", "Level", ".", "FINE", ")", ")", "//306998.15", "logger", ".", "entering", "(", "CLASS_NAME", ",", "\"getOutputStream\"", ",", "\"gotWriter=\"", "+", "String", ".", "valueOf", "(", "_gotWriter", ")", "+", "\" [\"", "+", "this", "+", "\"]\"", ")", ";", "if", "(", "!", "_ignoreStateErrors", "&&", "_gotWriter", ")", "{", "if", "(", "isTraceOn", "&&", "logger", ".", "isLoggable", "(", "Level", ".", "FINE", ")", ")", "//306998.15", "logger", ".", "exiting", "(", "CLASS_NAME", ",", "\"getOutputStream\"", ",", "\"throw IllegalStateException\"", ")", ";", "throw", "new", "IllegalStateException", "(", "nls", ".", "getString", "(", "\"Writer.already.obtained\"", ",", "\"Writer already obtained\"", ")", ")", ";", "}", "//PK89810 Start", "if", "(", "!", "(", "WCCustomProperties", ".", "FINISH_RESPONSE_ON_CLOSE", ")", "||", "!", "_gotOutputStream", ")", "{", "_gotOutputStream", "=", "true", ";", "// LIBERTY _bufferedOut.init(_rawOut, getBufferSize());", "// LIBERTY _bufferedOut.setLimit(_contentLength);", "// LIBERTY _bufferedOut.setResponse(_response);", "// LIBERTY _responseBuffer = _bufferedOut;", "}", "//PK89810 End", "this", ".", "fireOutputStreamRetrievedEvent", "(", "_bufferedOut", ")", ";", "if", "(", "isTraceOn", "&&", "logger", ".", "isLoggable", "(", "Level", ".", "FINE", ")", ")", "//306998.15", "logger", ".", "exiting", "(", "CLASS_NAME", ",", "\"getOutputStream\"", ")", ";", "return", "_bufferedOut", ";", "}" ]
Returns an output stream for writing binary response data. @see reinitStreamState
[ "Returns", "an", "output", "stream", "for", "writing", "binary", "response", "data", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.webcontainer/src/com/ibm/ws/webcontainer/srt/SRTServletResponse.java#L761-L790
alibaba/jstorm
jstorm-core/src/main/java/backtype/storm/topology/CheckpointTupleForwarder.java
CheckpointTupleForwarder.shouldProcessTransaction
private boolean shouldProcessTransaction(Action action, long txid) { """ Checks if check points have been received from all tasks across all input streams to this component """ TransactionRequest request = new TransactionRequest(action, txid); Integer count; if ((count = transactionRequestCount.get(request)) == null) { transactionRequestCount.put(request, 1); count = 1; } else { transactionRequestCount.put(request, ++count); } if (count == checkPointInputTaskCount) { transactionRequestCount.remove(request); return true; } return false; }
java
private boolean shouldProcessTransaction(Action action, long txid) { TransactionRequest request = new TransactionRequest(action, txid); Integer count; if ((count = transactionRequestCount.get(request)) == null) { transactionRequestCount.put(request, 1); count = 1; } else { transactionRequestCount.put(request, ++count); } if (count == checkPointInputTaskCount) { transactionRequestCount.remove(request); return true; } return false; }
[ "private", "boolean", "shouldProcessTransaction", "(", "Action", "action", ",", "long", "txid", ")", "{", "TransactionRequest", "request", "=", "new", "TransactionRequest", "(", "action", ",", "txid", ")", ";", "Integer", "count", ";", "if", "(", "(", "count", "=", "transactionRequestCount", ".", "get", "(", "request", ")", ")", "==", "null", ")", "{", "transactionRequestCount", ".", "put", "(", "request", ",", "1", ")", ";", "count", "=", "1", ";", "}", "else", "{", "transactionRequestCount", ".", "put", "(", "request", ",", "++", "count", ")", ";", "}", "if", "(", "count", "==", "checkPointInputTaskCount", ")", "{", "transactionRequestCount", ".", "remove", "(", "request", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Checks if check points have been received from all tasks across all input streams to this component
[ "Checks", "if", "check", "points", "have", "been", "received", "from", "all", "tasks", "across", "all", "input", "streams", "to", "this", "component" ]
train
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/topology/CheckpointTupleForwarder.java#L173-L187
couchbase/couchbase-jvm-core
src/main/java/com/couchbase/client/core/endpoint/kv/KeyValueHandler.java
KeyValueHandler.handleStoreRequest
private static BinaryMemcacheRequest handleStoreRequest(final ChannelHandlerContext ctx, final BinaryStoreRequest msg) { """ Encodes a {@link BinaryStoreRequest} into its lower level representation. There are three types of store operations that need to be considered: insert, upsert and replace, which directly translate to the add, set and replace binary memcached opcodes. By convention, only the replace command supports setting a CAS value, even if the others theoretically would do as well (but do not provide benefit in such cases). Currently, the content is loaded and sent down in one batch, streaming for requests is not supported. @return a ready {@link BinaryMemcacheRequest}. """ ByteBuf extras = ctx.alloc().buffer(8); extras.writeInt(msg.flags()); extras.writeInt(msg.expiration()); byte[] key = msg.keyBytes(); short keyLength = (short) key.length; byte extrasLength = (byte) extras.readableBytes(); FullBinaryMemcacheRequest request = new DefaultFullBinaryMemcacheRequest(key, extras, msg.content()); if (msg instanceof InsertRequest) { request.setOpcode(OP_INSERT); } else if (msg instanceof UpsertRequest) { request.setOpcode(OP_UPSERT); } else if (msg instanceof ReplaceRequest) { request.setOpcode(OP_REPLACE); request.setCAS(((ReplaceRequest) msg).cas()); } else { throw new IllegalArgumentException("Unknown incoming BinaryStoreRequest type " + msg.getClass()); } request.setKeyLength(keyLength); request.setTotalBodyLength(keyLength + msg.content().readableBytes() + extrasLength); request.setExtrasLength(extrasLength); return request; }
java
private static BinaryMemcacheRequest handleStoreRequest(final ChannelHandlerContext ctx, final BinaryStoreRequest msg) { ByteBuf extras = ctx.alloc().buffer(8); extras.writeInt(msg.flags()); extras.writeInt(msg.expiration()); byte[] key = msg.keyBytes(); short keyLength = (short) key.length; byte extrasLength = (byte) extras.readableBytes(); FullBinaryMemcacheRequest request = new DefaultFullBinaryMemcacheRequest(key, extras, msg.content()); if (msg instanceof InsertRequest) { request.setOpcode(OP_INSERT); } else if (msg instanceof UpsertRequest) { request.setOpcode(OP_UPSERT); } else if (msg instanceof ReplaceRequest) { request.setOpcode(OP_REPLACE); request.setCAS(((ReplaceRequest) msg).cas()); } else { throw new IllegalArgumentException("Unknown incoming BinaryStoreRequest type " + msg.getClass()); } request.setKeyLength(keyLength); request.setTotalBodyLength(keyLength + msg.content().readableBytes() + extrasLength); request.setExtrasLength(extrasLength); return request; }
[ "private", "static", "BinaryMemcacheRequest", "handleStoreRequest", "(", "final", "ChannelHandlerContext", "ctx", ",", "final", "BinaryStoreRequest", "msg", ")", "{", "ByteBuf", "extras", "=", "ctx", ".", "alloc", "(", ")", ".", "buffer", "(", "8", ")", ";", "extras", ".", "writeInt", "(", "msg", ".", "flags", "(", ")", ")", ";", "extras", ".", "writeInt", "(", "msg", ".", "expiration", "(", ")", ")", ";", "byte", "[", "]", "key", "=", "msg", ".", "keyBytes", "(", ")", ";", "short", "keyLength", "=", "(", "short", ")", "key", ".", "length", ";", "byte", "extrasLength", "=", "(", "byte", ")", "extras", ".", "readableBytes", "(", ")", ";", "FullBinaryMemcacheRequest", "request", "=", "new", "DefaultFullBinaryMemcacheRequest", "(", "key", ",", "extras", ",", "msg", ".", "content", "(", ")", ")", ";", "if", "(", "msg", "instanceof", "InsertRequest", ")", "{", "request", ".", "setOpcode", "(", "OP_INSERT", ")", ";", "}", "else", "if", "(", "msg", "instanceof", "UpsertRequest", ")", "{", "request", ".", "setOpcode", "(", "OP_UPSERT", ")", ";", "}", "else", "if", "(", "msg", "instanceof", "ReplaceRequest", ")", "{", "request", ".", "setOpcode", "(", "OP_REPLACE", ")", ";", "request", ".", "setCAS", "(", "(", "(", "ReplaceRequest", ")", "msg", ")", ".", "cas", "(", ")", ")", ";", "}", "else", "{", "throw", "new", "IllegalArgumentException", "(", "\"Unknown incoming BinaryStoreRequest type \"", "+", "msg", ".", "getClass", "(", ")", ")", ";", "}", "request", ".", "setKeyLength", "(", "keyLength", ")", ";", "request", ".", "setTotalBodyLength", "(", "keyLength", "+", "msg", ".", "content", "(", ")", ".", "readableBytes", "(", ")", "+", "extrasLength", ")", ";", "request", ".", "setExtrasLength", "(", "extrasLength", ")", ";", "return", "request", ";", "}" ]
Encodes a {@link BinaryStoreRequest} into its lower level representation. There are three types of store operations that need to be considered: insert, upsert and replace, which directly translate to the add, set and replace binary memcached opcodes. By convention, only the replace command supports setting a CAS value, even if the others theoretically would do as well (but do not provide benefit in such cases). Currently, the content is loaded and sent down in one batch, streaming for requests is not supported. @return a ready {@link BinaryMemcacheRequest}.
[ "Encodes", "a", "{", "@link", "BinaryStoreRequest", "}", "into", "its", "lower", "level", "representation", "." ]
train
https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/endpoint/kv/KeyValueHandler.java#L554-L581
google/error-prone-javac
src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/ClassWriter.java
ClassWriter.putChar
void putChar(ByteBuffer buf, int op, int x) { """ Write a character into given byte buffer; byte buffer will not be grown. """ buf.elems[op ] = (byte)((x >> 8) & 0xFF); buf.elems[op+1] = (byte)((x ) & 0xFF); }
java
void putChar(ByteBuffer buf, int op, int x) { buf.elems[op ] = (byte)((x >> 8) & 0xFF); buf.elems[op+1] = (byte)((x ) & 0xFF); }
[ "void", "putChar", "(", "ByteBuffer", "buf", ",", "int", "op", ",", "int", "x", ")", "{", "buf", ".", "elems", "[", "op", "]", "=", "(", "byte", ")", "(", "(", "x", ">>", "8", ")", "&", "0xFF", ")", ";", "buf", ".", "elems", "[", "op", "+", "1", "]", "=", "(", "byte", ")", "(", "(", "x", ")", "&", "0xFF", ")", ";", "}" ]
Write a character into given byte buffer; byte buffer will not be grown.
[ "Write", "a", "character", "into", "given", "byte", "buffer", ";", "byte", "buffer", "will", "not", "be", "grown", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/ClassWriter.java#L248-L251
finmath/finmath-lib
src/main/java/net/finmath/time/ScheduleGenerator.java
ScheduleGenerator.createScheduleFromConventions
public static Schedule createScheduleFromConventions( LocalDate referenceDate, LocalDate tradeDate, int spotOffsetDays, String startOffsetString, String maturityString, String frequency, String daycountConvention, String shortPeriodConvention, String dateRollConvention, BusinessdayCalendar businessdayCalendar, int fixingOffsetDays, int paymentOffsetDays ) { """ Simple schedule generation where startDate and maturityDate are calculated based on tradeDate, spotOffsetDays, startOffsetString and maturityString. The schedule generation considers short periods. Date rolling is ignored. @param referenceDate The date which is used in the schedule to internally convert dates to doubles, i.e., the date where t=0. @param tradeDate Base date for the schedule generation (used to build spot date). @param spotOffsetDays Number of business days to be added to the trade date to obtain the spot date. @param startOffsetString The start date as an offset from the spotDate (build from tradeDate and spotOffsetDays) entered as a code like 1D, 1W, 1M, 2M, 3M, 1Y, etc. @param maturityString The end date of the last period entered as a code like 1D, 1W, 1M, 2M, 3M, 1Y, etc. @param frequency The frequency (as String). @param daycountConvention The daycount convention (as String). @param shortPeriodConvention If short period exists, have it first or last (as String). @param dateRollConvention Adjustment to be applied to the all dates (as String). @param businessdayCalendar Business day calendar (holiday calendar) to be used for date roll adjustment. @param fixingOffsetDays Number of business days to be added to period start to get the fixing date. @param paymentOffsetDays Number of business days to be added to period end to get the payment date. @return The corresponding schedule """ LocalDate spotDate = businessdayCalendar.getRolledDate(tradeDate, spotOffsetDays); LocalDate startDate = businessdayCalendar.getDateFromDateAndOffsetCode(spotDate, startOffsetString); LocalDate maturityDate = businessdayCalendar.getDateFromDateAndOffsetCode(startDate, maturityString); return createScheduleFromConventions(referenceDate, startDate, maturityDate, frequency, daycountConvention, shortPeriodConvention, dateRollConvention, businessdayCalendar, fixingOffsetDays, paymentOffsetDays); }
java
public static Schedule createScheduleFromConventions( LocalDate referenceDate, LocalDate tradeDate, int spotOffsetDays, String startOffsetString, String maturityString, String frequency, String daycountConvention, String shortPeriodConvention, String dateRollConvention, BusinessdayCalendar businessdayCalendar, int fixingOffsetDays, int paymentOffsetDays ) { LocalDate spotDate = businessdayCalendar.getRolledDate(tradeDate, spotOffsetDays); LocalDate startDate = businessdayCalendar.getDateFromDateAndOffsetCode(spotDate, startOffsetString); LocalDate maturityDate = businessdayCalendar.getDateFromDateAndOffsetCode(startDate, maturityString); return createScheduleFromConventions(referenceDate, startDate, maturityDate, frequency, daycountConvention, shortPeriodConvention, dateRollConvention, businessdayCalendar, fixingOffsetDays, paymentOffsetDays); }
[ "public", "static", "Schedule", "createScheduleFromConventions", "(", "LocalDate", "referenceDate", ",", "LocalDate", "tradeDate", ",", "int", "spotOffsetDays", ",", "String", "startOffsetString", ",", "String", "maturityString", ",", "String", "frequency", ",", "String", "daycountConvention", ",", "String", "shortPeriodConvention", ",", "String", "dateRollConvention", ",", "BusinessdayCalendar", "businessdayCalendar", ",", "int", "fixingOffsetDays", ",", "int", "paymentOffsetDays", ")", "{", "LocalDate", "spotDate", "=", "businessdayCalendar", ".", "getRolledDate", "(", "tradeDate", ",", "spotOffsetDays", ")", ";", "LocalDate", "startDate", "=", "businessdayCalendar", ".", "getDateFromDateAndOffsetCode", "(", "spotDate", ",", "startOffsetString", ")", ";", "LocalDate", "maturityDate", "=", "businessdayCalendar", ".", "getDateFromDateAndOffsetCode", "(", "startDate", ",", "maturityString", ")", ";", "return", "createScheduleFromConventions", "(", "referenceDate", ",", "startDate", ",", "maturityDate", ",", "frequency", ",", "daycountConvention", ",", "shortPeriodConvention", ",", "dateRollConvention", ",", "businessdayCalendar", ",", "fixingOffsetDays", ",", "paymentOffsetDays", ")", ";", "}" ]
Simple schedule generation where startDate and maturityDate are calculated based on tradeDate, spotOffsetDays, startOffsetString and maturityString. The schedule generation considers short periods. Date rolling is ignored. @param referenceDate The date which is used in the schedule to internally convert dates to doubles, i.e., the date where t=0. @param tradeDate Base date for the schedule generation (used to build spot date). @param spotOffsetDays Number of business days to be added to the trade date to obtain the spot date. @param startOffsetString The start date as an offset from the spotDate (build from tradeDate and spotOffsetDays) entered as a code like 1D, 1W, 1M, 2M, 3M, 1Y, etc. @param maturityString The end date of the last period entered as a code like 1D, 1W, 1M, 2M, 3M, 1Y, etc. @param frequency The frequency (as String). @param daycountConvention The daycount convention (as String). @param shortPeriodConvention If short period exists, have it first or last (as String). @param dateRollConvention Adjustment to be applied to the all dates (as String). @param businessdayCalendar Business day calendar (holiday calendar) to be used for date roll adjustment. @param fixingOffsetDays Number of business days to be added to period start to get the fixing date. @param paymentOffsetDays Number of business days to be added to period end to get the payment date. @return The corresponding schedule
[ "Simple", "schedule", "generation", "where", "startDate", "and", "maturityDate", "are", "calculated", "based", "on", "tradeDate", "spotOffsetDays", "startOffsetString", "and", "maturityString", "." ]
train
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/time/ScheduleGenerator.java#L520-L540
kiswanij/jk-util
src/main/java/com/jk/util/JKDateTimeUtil.java
JKDateTimeUtil.isCurrentTimeBetweenTowTimes
public static boolean isCurrentTimeBetweenTowTimes(Date fromDate, Date fromTime, Date toDate, Date timeTo) { """ Checks if is current time between tow times. @param fromDate the from date @param fromTime the from time @param toDate the to date @param timeTo the time to @return true, if is current time between tow times """ JKTimeObject currntTime = getCurrntTime(); JKTimeObject fromTimeObject = new JKTimeObject(); JKTimeObject toTimeObject = new JKTimeObject(); if (currntTime.after(fromTimeObject.toTimeObject(fromDate, fromTime)) && currntTime.before(toTimeObject.toTimeObject(toDate, timeTo))) { return true; } return false; }
java
public static boolean isCurrentTimeBetweenTowTimes(Date fromDate, Date fromTime, Date toDate, Date timeTo) { JKTimeObject currntTime = getCurrntTime(); JKTimeObject fromTimeObject = new JKTimeObject(); JKTimeObject toTimeObject = new JKTimeObject(); if (currntTime.after(fromTimeObject.toTimeObject(fromDate, fromTime)) && currntTime.before(toTimeObject.toTimeObject(toDate, timeTo))) { return true; } return false; }
[ "public", "static", "boolean", "isCurrentTimeBetweenTowTimes", "(", "Date", "fromDate", ",", "Date", "fromTime", ",", "Date", "toDate", ",", "Date", "timeTo", ")", "{", "JKTimeObject", "currntTime", "=", "getCurrntTime", "(", ")", ";", "JKTimeObject", "fromTimeObject", "=", "new", "JKTimeObject", "(", ")", ";", "JKTimeObject", "toTimeObject", "=", "new", "JKTimeObject", "(", ")", ";", "if", "(", "currntTime", ".", "after", "(", "fromTimeObject", ".", "toTimeObject", "(", "fromDate", ",", "fromTime", ")", ")", "&&", "currntTime", ".", "before", "(", "toTimeObject", ".", "toTimeObject", "(", "toDate", ",", "timeTo", ")", ")", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}" ]
Checks if is current time between tow times. @param fromDate the from date @param fromTime the from time @param toDate the to date @param timeTo the time to @return true, if is current time between tow times
[ "Checks", "if", "is", "current", "time", "between", "tow", "times", "." ]
train
https://github.com/kiswanij/jk-util/blob/8e0c85818423406f769444c76194a748e0a0fc0a/src/main/java/com/jk/util/JKDateTimeUtil.java#L394-L402
PeterisP/LVTagger
src/main/java/edu/stanford/nlp/math/SloppyMath.java
SloppyMath.main
public static void main(String[] args) { """ Tests the hypergeometric distribution code, or other functions provided in this module. @param args Either none, and the log add rountines are tested, or the following 4 arguments: k (cell), n (total), r (row), m (col) """ if (args.length == 0) { System.err.println("Usage: java edu.stanford.nlp.math.SloppyMath " + "[-logAdd|-fishers k n r m|-binomial r n p"); } else if (args[0].equals("-logAdd")) { System.out.println("Log adds of neg infinity numbers, etc."); System.out.println("(logs) -Inf + -Inf = " + logAdd(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY)); System.out.println("(logs) -Inf + -7 = " + logAdd(Double.NEGATIVE_INFINITY, -7.0)); System.out.println("(logs) -7 + -Inf = " + logAdd(-7.0, Double.NEGATIVE_INFINITY)); System.out.println("(logs) -50 + -7 = " + logAdd(-50.0, -7.0)); System.out.println("(logs) -11 + -7 = " + logAdd(-11.0, -7.0)); System.out.println("(logs) -7 + -11 = " + logAdd(-7.0, -11.0)); System.out.println("real 1/2 + 1/2 = " + logAdd(Math.log(0.5), Math.log(0.5))); } else if (args[0].equals("-fishers")) { int k = Integer.parseInt(args[1]); int n = Integer.parseInt(args[2]); int r = Integer.parseInt(args[3]); int m = Integer.parseInt(args[4]); double ans = SloppyMath.hypergeometric(k, n, r, m); System.out.println("hypg(" + k + "; " + n + ", " + r + ", " + m + ") = " + ans); ans = SloppyMath.oneTailedFishersExact(k, n, r, m); System.out.println("1-tailed Fisher's exact(" + k + "; " + n + ", " + r + ", " + m + ") = " + ans); double ansChi = SloppyMath.chiSquare2by2(k, n, r, m); System.out.println("chiSquare(" + k + "; " + n + ", " + r + ", " + m + ") = " + ansChi); System.out.println("Swapping arguments should give same hypg:"); ans = SloppyMath.hypergeometric(k, n, r, m); System.out.println("hypg(" + k + "; " + n + ", " + m + ", " + r + ") = " + ans); int othrow = n - m; int othcol = n - r; int cell12 = m - k; int cell21 = r - k; int cell22 = othrow - (r - k); ans = SloppyMath.hypergeometric(cell12, n, othcol, m); System.out.println("hypg(" + cell12 + "; " + n + ", " + othcol + ", " + m + ") = " + ans); ans = SloppyMath.hypergeometric(cell21, n, r, othrow); System.out.println("hypg(" + cell21 + "; " + n + ", " + r + ", " + othrow + ") = " + ans); ans = SloppyMath.hypergeometric(cell22, n, othcol, othrow); System.out.println("hypg(" + cell22 + "; " + n + ", " + othcol + ", " + othrow + ") = " + ans); } else if (args[0].equals("-binomial")) { int k = Integer.parseInt(args[1]); int n = Integer.parseInt(args[2]); double p = Double.parseDouble(args[3]); double ans = SloppyMath.exactBinomial(k, n, p); System.out.println("Binomial p(X >= " + k + "; " + n + ", " + p + ") = " + ans); } else { System.err.println("Unknown option: " + args[0]); } }
java
public static void main(String[] args) { if (args.length == 0) { System.err.println("Usage: java edu.stanford.nlp.math.SloppyMath " + "[-logAdd|-fishers k n r m|-binomial r n p"); } else if (args[0].equals("-logAdd")) { System.out.println("Log adds of neg infinity numbers, etc."); System.out.println("(logs) -Inf + -Inf = " + logAdd(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY)); System.out.println("(logs) -Inf + -7 = " + logAdd(Double.NEGATIVE_INFINITY, -7.0)); System.out.println("(logs) -7 + -Inf = " + logAdd(-7.0, Double.NEGATIVE_INFINITY)); System.out.println("(logs) -50 + -7 = " + logAdd(-50.0, -7.0)); System.out.println("(logs) -11 + -7 = " + logAdd(-11.0, -7.0)); System.out.println("(logs) -7 + -11 = " + logAdd(-7.0, -11.0)); System.out.println("real 1/2 + 1/2 = " + logAdd(Math.log(0.5), Math.log(0.5))); } else if (args[0].equals("-fishers")) { int k = Integer.parseInt(args[1]); int n = Integer.parseInt(args[2]); int r = Integer.parseInt(args[3]); int m = Integer.parseInt(args[4]); double ans = SloppyMath.hypergeometric(k, n, r, m); System.out.println("hypg(" + k + "; " + n + ", " + r + ", " + m + ") = " + ans); ans = SloppyMath.oneTailedFishersExact(k, n, r, m); System.out.println("1-tailed Fisher's exact(" + k + "; " + n + ", " + r + ", " + m + ") = " + ans); double ansChi = SloppyMath.chiSquare2by2(k, n, r, m); System.out.println("chiSquare(" + k + "; " + n + ", " + r + ", " + m + ") = " + ansChi); System.out.println("Swapping arguments should give same hypg:"); ans = SloppyMath.hypergeometric(k, n, r, m); System.out.println("hypg(" + k + "; " + n + ", " + m + ", " + r + ") = " + ans); int othrow = n - m; int othcol = n - r; int cell12 = m - k; int cell21 = r - k; int cell22 = othrow - (r - k); ans = SloppyMath.hypergeometric(cell12, n, othcol, m); System.out.println("hypg(" + cell12 + "; " + n + ", " + othcol + ", " + m + ") = " + ans); ans = SloppyMath.hypergeometric(cell21, n, r, othrow); System.out.println("hypg(" + cell21 + "; " + n + ", " + r + ", " + othrow + ") = " + ans); ans = SloppyMath.hypergeometric(cell22, n, othcol, othrow); System.out.println("hypg(" + cell22 + "; " + n + ", " + othcol + ", " + othrow + ") = " + ans); } else if (args[0].equals("-binomial")) { int k = Integer.parseInt(args[1]); int n = Integer.parseInt(args[2]); double p = Double.parseDouble(args[3]); double ans = SloppyMath.exactBinomial(k, n, p); System.out.println("Binomial p(X >= " + k + "; " + n + ", " + p + ") = " + ans); } else { System.err.println("Unknown option: " + args[0]); } }
[ "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "{", "if", "(", "args", ".", "length", "==", "0", ")", "{", "System", ".", "err", ".", "println", "(", "\"Usage: java edu.stanford.nlp.math.SloppyMath \"", "+", "\"[-logAdd|-fishers k n r m|-binomial r n p\"", ")", ";", "}", "else", "if", "(", "args", "[", "0", "]", ".", "equals", "(", "\"-logAdd\"", ")", ")", "{", "System", ".", "out", ".", "println", "(", "\"Log adds of neg infinity numbers, etc.\"", ")", ";", "System", ".", "out", ".", "println", "(", "\"(logs) -Inf + -Inf = \"", "+", "logAdd", "(", "Double", ".", "NEGATIVE_INFINITY", ",", "Double", ".", "NEGATIVE_INFINITY", ")", ")", ";", "System", ".", "out", ".", "println", "(", "\"(logs) -Inf + -7 = \"", "+", "logAdd", "(", "Double", ".", "NEGATIVE_INFINITY", ",", "-", "7.0", ")", ")", ";", "System", ".", "out", ".", "println", "(", "\"(logs) -7 + -Inf = \"", "+", "logAdd", "(", "-", "7.0", ",", "Double", ".", "NEGATIVE_INFINITY", ")", ")", ";", "System", ".", "out", ".", "println", "(", "\"(logs) -50 + -7 = \"", "+", "logAdd", "(", "-", "50.0", ",", "-", "7.0", ")", ")", ";", "System", ".", "out", ".", "println", "(", "\"(logs) -11 + -7 = \"", "+", "logAdd", "(", "-", "11.0", ",", "-", "7.0", ")", ")", ";", "System", ".", "out", ".", "println", "(", "\"(logs) -7 + -11 = \"", "+", "logAdd", "(", "-", "7.0", ",", "-", "11.0", ")", ")", ";", "System", ".", "out", ".", "println", "(", "\"real 1/2 + 1/2 = \"", "+", "logAdd", "(", "Math", ".", "log", "(", "0.5", ")", ",", "Math", ".", "log", "(", "0.5", ")", ")", ")", ";", "}", "else", "if", "(", "args", "[", "0", "]", ".", "equals", "(", "\"-fishers\"", ")", ")", "{", "int", "k", "=", "Integer", ".", "parseInt", "(", "args", "[", "1", "]", ")", ";", "int", "n", "=", "Integer", ".", "parseInt", "(", "args", "[", "2", "]", ")", ";", "int", "r", "=", "Integer", ".", "parseInt", "(", "args", "[", "3", "]", ")", ";", "int", "m", "=", "Integer", ".", "parseInt", "(", "args", "[", "4", "]", ")", ";", "double", "ans", "=", "SloppyMath", ".", "hypergeometric", "(", "k", ",", "n", ",", "r", ",", "m", ")", ";", "System", ".", "out", ".", "println", "(", "\"hypg(\"", "+", "k", "+", "\"; \"", "+", "n", "+", "\", \"", "+", "r", "+", "\", \"", "+", "m", "+", "\") = \"", "+", "ans", ")", ";", "ans", "=", "SloppyMath", ".", "oneTailedFishersExact", "(", "k", ",", "n", ",", "r", ",", "m", ")", ";", "System", ".", "out", ".", "println", "(", "\"1-tailed Fisher's exact(\"", "+", "k", "+", "\"; \"", "+", "n", "+", "\", \"", "+", "r", "+", "\", \"", "+", "m", "+", "\") = \"", "+", "ans", ")", ";", "double", "ansChi", "=", "SloppyMath", ".", "chiSquare2by2", "(", "k", ",", "n", ",", "r", ",", "m", ")", ";", "System", ".", "out", ".", "println", "(", "\"chiSquare(\"", "+", "k", "+", "\"; \"", "+", "n", "+", "\", \"", "+", "r", "+", "\", \"", "+", "m", "+", "\") = \"", "+", "ansChi", ")", ";", "System", ".", "out", ".", "println", "(", "\"Swapping arguments should give same hypg:\"", ")", ";", "ans", "=", "SloppyMath", ".", "hypergeometric", "(", "k", ",", "n", ",", "r", ",", "m", ")", ";", "System", ".", "out", ".", "println", "(", "\"hypg(\"", "+", "k", "+", "\"; \"", "+", "n", "+", "\", \"", "+", "m", "+", "\", \"", "+", "r", "+", "\") = \"", "+", "ans", ")", ";", "int", "othrow", "=", "n", "-", "m", ";", "int", "othcol", "=", "n", "-", "r", ";", "int", "cell12", "=", "m", "-", "k", ";", "int", "cell21", "=", "r", "-", "k", ";", "int", "cell22", "=", "othrow", "-", "(", "r", "-", "k", ")", ";", "ans", "=", "SloppyMath", ".", "hypergeometric", "(", "cell12", ",", "n", ",", "othcol", ",", "m", ")", ";", "System", ".", "out", ".", "println", "(", "\"hypg(\"", "+", "cell12", "+", "\"; \"", "+", "n", "+", "\", \"", "+", "othcol", "+", "\", \"", "+", "m", "+", "\") = \"", "+", "ans", ")", ";", "ans", "=", "SloppyMath", ".", "hypergeometric", "(", "cell21", ",", "n", ",", "r", ",", "othrow", ")", ";", "System", ".", "out", ".", "println", "(", "\"hypg(\"", "+", "cell21", "+", "\"; \"", "+", "n", "+", "\", \"", "+", "r", "+", "\", \"", "+", "othrow", "+", "\") = \"", "+", "ans", ")", ";", "ans", "=", "SloppyMath", ".", "hypergeometric", "(", "cell22", ",", "n", ",", "othcol", ",", "othrow", ")", ";", "System", ".", "out", ".", "println", "(", "\"hypg(\"", "+", "cell22", "+", "\"; \"", "+", "n", "+", "\", \"", "+", "othcol", "+", "\", \"", "+", "othrow", "+", "\") = \"", "+", "ans", ")", ";", "}", "else", "if", "(", "args", "[", "0", "]", ".", "equals", "(", "\"-binomial\"", ")", ")", "{", "int", "k", "=", "Integer", ".", "parseInt", "(", "args", "[", "1", "]", ")", ";", "int", "n", "=", "Integer", ".", "parseInt", "(", "args", "[", "2", "]", ")", ";", "double", "p", "=", "Double", ".", "parseDouble", "(", "args", "[", "3", "]", ")", ";", "double", "ans", "=", "SloppyMath", ".", "exactBinomial", "(", "k", ",", "n", ",", "p", ")", ";", "System", ".", "out", ".", "println", "(", "\"Binomial p(X >= \"", "+", "k", "+", "\"; \"", "+", "n", "+", "\", \"", "+", "p", "+", "\") = \"", "+", "ans", ")", ";", "}", "else", "{", "System", ".", "err", ".", "println", "(", "\"Unknown option: \"", "+", "args", "[", "0", "]", ")", ";", "}", "}" ]
Tests the hypergeometric distribution code, or other functions provided in this module. @param args Either none, and the log add rountines are tested, or the following 4 arguments: k (cell), n (total), r (row), m (col)
[ "Tests", "the", "hypergeometric", "distribution", "code", "or", "other", "functions", "provided", "in", "this", "module", "." ]
train
https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/math/SloppyMath.java#L651-L698
arxanchain/java-common
src/main/java/com/arxanfintech/common/util/ByteUtil.java
ByteUtil.xorAlignRight
public static byte[] xorAlignRight(byte[] b1, byte[] b2) { """ XORs byte arrays of different lengths by aligning length of the shortest via adding zeros at beginning @param b1 b1 @param b2 b2 @return xorAlignRight """ if (b1.length > b2.length) { byte[] b2_ = new byte[b1.length]; System.arraycopy(b2, 0, b2_, b1.length - b2.length, b2.length); b2 = b2_; } else if (b2.length > b1.length) { byte[] b1_ = new byte[b2.length]; System.arraycopy(b1, 0, b1_, b2.length - b1.length, b1.length); b1 = b1_; } return xor(b1, b2); }
java
public static byte[] xorAlignRight(byte[] b1, byte[] b2) { if (b1.length > b2.length) { byte[] b2_ = new byte[b1.length]; System.arraycopy(b2, 0, b2_, b1.length - b2.length, b2.length); b2 = b2_; } else if (b2.length > b1.length) { byte[] b1_ = new byte[b2.length]; System.arraycopy(b1, 0, b1_, b2.length - b1.length, b1.length); b1 = b1_; } return xor(b1, b2); }
[ "public", "static", "byte", "[", "]", "xorAlignRight", "(", "byte", "[", "]", "b1", ",", "byte", "[", "]", "b2", ")", "{", "if", "(", "b1", ".", "length", ">", "b2", ".", "length", ")", "{", "byte", "[", "]", "b2_", "=", "new", "byte", "[", "b1", ".", "length", "]", ";", "System", ".", "arraycopy", "(", "b2", ",", "0", ",", "b2_", ",", "b1", ".", "length", "-", "b2", ".", "length", ",", "b2", ".", "length", ")", ";", "b2", "=", "b2_", ";", "}", "else", "if", "(", "b2", ".", "length", ">", "b1", ".", "length", ")", "{", "byte", "[", "]", "b1_", "=", "new", "byte", "[", "b2", ".", "length", "]", ";", "System", ".", "arraycopy", "(", "b1", ",", "0", ",", "b1_", ",", "b2", ".", "length", "-", "b1", ".", "length", ",", "b1", ".", "length", ")", ";", "b1", "=", "b1_", ";", "}", "return", "xor", "(", "b1", ",", "b2", ")", ";", "}" ]
XORs byte arrays of different lengths by aligning length of the shortest via adding zeros at beginning @param b1 b1 @param b2 b2 @return xorAlignRight
[ "XORs", "byte", "arrays", "of", "different", "lengths", "by", "aligning", "length", "of", "the", "shortest", "via", "adding", "zeros", "at", "beginning" ]
train
https://github.com/arxanchain/java-common/blob/3ddfedfd948f5bab3fee0b74b85cdce4702ed84e/src/main/java/com/arxanfintech/common/util/ByteUtil.java#L510-L522
peholmst/vaadin4spring
addons/i18n/src/main/java/org/vaadin/spring/i18n/I18N.java
I18N.getWithLocale
@Deprecated public String getWithLocale(String code, Locale locale, Object... arguments) { """ Tries to resolve the specified message for the given locale. @param code the code to lookup up, such as 'calculator.noRateSet', never {@code null}. @param locale The Locale for which it is tried to look up the code. Must not be null @param arguments Array of arguments that will be filled in for params within the message (params look like "{0}", "{1,date}", "{2,time}"), or {@code null} if none. @throws IllegalArgumentException if the given Locale is null @return the resolved message, or the message code prepended with an exclamation mark if the lookup fails. @see org.springframework.context.ApplicationContext#getMessage(String, Object[], java.util.Locale) @see java.util.Locale @deprecated Use {@link #get(String, Locale, Object...)} instead. """ return get(code, locale, arguments); }
java
@Deprecated public String getWithLocale(String code, Locale locale, Object... arguments) { return get(code, locale, arguments); }
[ "@", "Deprecated", "public", "String", "getWithLocale", "(", "String", "code", ",", "Locale", "locale", ",", "Object", "...", "arguments", ")", "{", "return", "get", "(", "code", ",", "locale", ",", "arguments", ")", ";", "}" ]
Tries to resolve the specified message for the given locale. @param code the code to lookup up, such as 'calculator.noRateSet', never {@code null}. @param locale The Locale for which it is tried to look up the code. Must not be null @param arguments Array of arguments that will be filled in for params within the message (params look like "{0}", "{1,date}", "{2,time}"), or {@code null} if none. @throws IllegalArgumentException if the given Locale is null @return the resolved message, or the message code prepended with an exclamation mark if the lookup fails. @see org.springframework.context.ApplicationContext#getMessage(String, Object[], java.util.Locale) @see java.util.Locale @deprecated Use {@link #get(String, Locale, Object...)} instead.
[ "Tries", "to", "resolve", "the", "specified", "message", "for", "the", "given", "locale", "." ]
train
https://github.com/peholmst/vaadin4spring/blob/ea896012f15d6abea6e6391def9a0001113a1f7a/addons/i18n/src/main/java/org/vaadin/spring/i18n/I18N.java#L138-L141
kuali/ojb-1.0.4
src/java/org/apache/ojb/broker/util/ExceptionHelper.java
ExceptionHelper.generateException
public static PersistenceBrokerSQLException generateException(SQLException ex, String sql, ClassDescriptor cld, Logger logger, Object obj) { """ Method which support the conversion of {@link java.sql.SQLException} to OJB's runtime exception (with additional message details). @param ex The exception to convert (mandatory). @param sql The used sql-statement or <em>null</em>. @param cld The {@link org.apache.ojb.broker.metadata.ClassDescriptor} of the target object or <em>null</em>. @param logger The {@link org.apache.ojb.broker.util.logging.Logger} to log an detailed message to the specified {@link org.apache.ojb.broker.util.logging.Logger} or <em>null</em> to skip logging message. @param obj The target object or <em>null</em>. @return A new created {@link org.apache.ojb.broker.PersistenceBrokerSQLException} based on the specified arguments. """ return generateException(ex, sql, cld, null, logger, obj); }
java
public static PersistenceBrokerSQLException generateException(SQLException ex, String sql, ClassDescriptor cld, Logger logger, Object obj) { return generateException(ex, sql, cld, null, logger, obj); }
[ "public", "static", "PersistenceBrokerSQLException", "generateException", "(", "SQLException", "ex", ",", "String", "sql", ",", "ClassDescriptor", "cld", ",", "Logger", "logger", ",", "Object", "obj", ")", "{", "return", "generateException", "(", "ex", ",", "sql", ",", "cld", ",", "null", ",", "logger", ",", "obj", ")", ";", "}" ]
Method which support the conversion of {@link java.sql.SQLException} to OJB's runtime exception (with additional message details). @param ex The exception to convert (mandatory). @param sql The used sql-statement or <em>null</em>. @param cld The {@link org.apache.ojb.broker.metadata.ClassDescriptor} of the target object or <em>null</em>. @param logger The {@link org.apache.ojb.broker.util.logging.Logger} to log an detailed message to the specified {@link org.apache.ojb.broker.util.logging.Logger} or <em>null</em> to skip logging message. @param obj The target object or <em>null</em>. @return A new created {@link org.apache.ojb.broker.PersistenceBrokerSQLException} based on the specified arguments.
[ "Method", "which", "support", "the", "conversion", "of", "{", "@link", "java", ".", "sql", ".", "SQLException", "}", "to", "OJB", "s", "runtime", "exception", "(", "with", "additional", "message", "details", ")", "." ]
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/util/ExceptionHelper.java#L69-L72
googleapis/google-cloud-java
google-cloud-clients/google-cloud-kms/src/main/java/com/google/cloud/kms/v1/KeyManagementServiceClient.java
KeyManagementServiceClient.asymmetricDecrypt
public final AsymmetricDecryptResponse asymmetricDecrypt(String name, ByteString ciphertext) { """ Decrypts data that was encrypted with a public key retrieved from [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey] corresponding to a [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] ASYMMETRIC_DECRYPT. <p>Sample code: <pre><code> try (KeyManagementServiceClient keyManagementServiceClient = KeyManagementServiceClient.create()) { CryptoKeyVersionName name = CryptoKeyVersionName.of("[PROJECT]", "[LOCATION]", "[KEY_RING]", "[CRYPTO_KEY]", "[CRYPTO_KEY_VERSION]"); ByteString ciphertext = ByteString.copyFromUtf8(""); AsymmetricDecryptResponse response = keyManagementServiceClient.asymmetricDecrypt(name.toString(), ciphertext); } </code></pre> @param name Required. The resource name of the [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to use for decryption. @param ciphertext Required. The data encrypted with the named [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]'s public key using OAEP. @throws com.google.api.gax.rpc.ApiException if the remote call fails """ AsymmetricDecryptRequest request = AsymmetricDecryptRequest.newBuilder().setName(name).setCiphertext(ciphertext).build(); return asymmetricDecrypt(request); }
java
public final AsymmetricDecryptResponse asymmetricDecrypt(String name, ByteString ciphertext) { AsymmetricDecryptRequest request = AsymmetricDecryptRequest.newBuilder().setName(name).setCiphertext(ciphertext).build(); return asymmetricDecrypt(request); }
[ "public", "final", "AsymmetricDecryptResponse", "asymmetricDecrypt", "(", "String", "name", ",", "ByteString", "ciphertext", ")", "{", "AsymmetricDecryptRequest", "request", "=", "AsymmetricDecryptRequest", ".", "newBuilder", "(", ")", ".", "setName", "(", "name", ")", ".", "setCiphertext", "(", "ciphertext", ")", ".", "build", "(", ")", ";", "return", "asymmetricDecrypt", "(", "request", ")", ";", "}" ]
Decrypts data that was encrypted with a public key retrieved from [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey] corresponding to a [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] ASYMMETRIC_DECRYPT. <p>Sample code: <pre><code> try (KeyManagementServiceClient keyManagementServiceClient = KeyManagementServiceClient.create()) { CryptoKeyVersionName name = CryptoKeyVersionName.of("[PROJECT]", "[LOCATION]", "[KEY_RING]", "[CRYPTO_KEY]", "[CRYPTO_KEY_VERSION]"); ByteString ciphertext = ByteString.copyFromUtf8(""); AsymmetricDecryptResponse response = keyManagementServiceClient.asymmetricDecrypt(name.toString(), ciphertext); } </code></pre> @param name Required. The resource name of the [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to use for decryption. @param ciphertext Required. The data encrypted with the named [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]'s public key using OAEP. @throws com.google.api.gax.rpc.ApiException if the remote call fails
[ "Decrypts", "data", "that", "was", "encrypted", "with", "a", "public", "key", "retrieved", "from", "[", "GetPublicKey", "]", "[", "google", ".", "cloud", ".", "kms", ".", "v1", ".", "KeyManagementService", ".", "GetPublicKey", "]", "corresponding", "to", "a", "[", "CryptoKeyVersion", "]", "[", "google", ".", "cloud", ".", "kms", ".", "v1", ".", "CryptoKeyVersion", "]", "with", "[", "CryptoKey", ".", "purpose", "]", "[", "google", ".", "cloud", ".", "kms", ".", "v1", ".", "CryptoKey", ".", "purpose", "]", "ASYMMETRIC_DECRYPT", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-kms/src/main/java/com/google/cloud/kms/v1/KeyManagementServiceClient.java#L2292-L2297
Impetus/Kundera
src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/processor/TableProcessor.java
TableProcessor.onIdAttribute
private void onIdAttribute(final MetaModelBuilder builder, EntityMetadata entityMetadata, final Class clazz, Field f) { """ On id attribute. @param builder the builder @param entityMetadata the entity metadata @param clazz the clazz @param f the f """ EntityType entity = (EntityType) builder.getManagedTypes().get(clazz); Attribute attrib = entity.getAttribute(f.getName()); if (!attrib.isCollection() && ((SingularAttribute) attrib).isId()) { entityMetadata.setIdAttribute((SingularAttribute) attrib); populateIdAccessorMethods(entityMetadata, clazz, f); } }
java
private void onIdAttribute(final MetaModelBuilder builder, EntityMetadata entityMetadata, final Class clazz, Field f) { EntityType entity = (EntityType) builder.getManagedTypes().get(clazz); Attribute attrib = entity.getAttribute(f.getName()); if (!attrib.isCollection() && ((SingularAttribute) attrib).isId()) { entityMetadata.setIdAttribute((SingularAttribute) attrib); populateIdAccessorMethods(entityMetadata, clazz, f); } }
[ "private", "void", "onIdAttribute", "(", "final", "MetaModelBuilder", "builder", ",", "EntityMetadata", "entityMetadata", ",", "final", "Class", "clazz", ",", "Field", "f", ")", "{", "EntityType", "entity", "=", "(", "EntityType", ")", "builder", ".", "getManagedTypes", "(", ")", ".", "get", "(", "clazz", ")", ";", "Attribute", "attrib", "=", "entity", ".", "getAttribute", "(", "f", ".", "getName", "(", ")", ")", ";", "if", "(", "!", "attrib", ".", "isCollection", "(", ")", "&&", "(", "(", "SingularAttribute", ")", "attrib", ")", ".", "isId", "(", ")", ")", "{", "entityMetadata", ".", "setIdAttribute", "(", "(", "SingularAttribute", ")", "attrib", ")", ";", "populateIdAccessorMethods", "(", "entityMetadata", ",", "clazz", ",", "f", ")", ";", "}", "}" ]
On id attribute. @param builder the builder @param entityMetadata the entity metadata @param clazz the clazz @param f the f
[ "On", "id", "attribute", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/processor/TableProcessor.java#L310-L320
spring-cloud/spring-cloud-contract
spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/GitRepo.java
GitRepo.checkout
void checkout(File project, String branch) { """ Checks out a branch for a project. @param project - a Git project @param branch - branch to check out """ try { String currentBranch = currentBranch(project); if (currentBranch.equals(branch)) { log.info("Won't check out the same branch. Skipping"); return; } log.info("Checking out branch [" + branch + "]"); checkoutBranch(project, branch); log.info("Successfully checked out the branch [" + branch + "]"); } catch (Exception e) { throw new IllegalStateException(e); } }
java
void checkout(File project, String branch) { try { String currentBranch = currentBranch(project); if (currentBranch.equals(branch)) { log.info("Won't check out the same branch. Skipping"); return; } log.info("Checking out branch [" + branch + "]"); checkoutBranch(project, branch); log.info("Successfully checked out the branch [" + branch + "]"); } catch (Exception e) { throw new IllegalStateException(e); } }
[ "void", "checkout", "(", "File", "project", ",", "String", "branch", ")", "{", "try", "{", "String", "currentBranch", "=", "currentBranch", "(", "project", ")", ";", "if", "(", "currentBranch", ".", "equals", "(", "branch", ")", ")", "{", "log", ".", "info", "(", "\"Won't check out the same branch. Skipping\"", ")", ";", "return", ";", "}", "log", ".", "info", "(", "\"Checking out branch [\"", "+", "branch", "+", "\"]\"", ")", ";", "checkoutBranch", "(", "project", ",", "branch", ")", ";", "log", ".", "info", "(", "\"Successfully checked out the branch [\"", "+", "branch", "+", "\"]\"", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "IllegalStateException", "(", "e", ")", ";", "}", "}" ]
Checks out a branch for a project. @param project - a Git project @param branch - branch to check out
[ "Checks", "out", "a", "branch", "for", "a", "project", "." ]
train
https://github.com/spring-cloud/spring-cloud-contract/blob/857da51950a87b393286e3bb1b2208c420c01087/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/GitRepo.java#L125-L139
pf4j/pf4j-update
src/main/java/org/pf4j/update/UpdateManager.java
UpdateManager.findReleaseForPlugin
protected PluginRelease findReleaseForPlugin(String id, String version) throws PluginException { """ Resolves Release from id and version. @param id of plugin @param version of plugin or null to locate latest version @return PluginRelease for downloading @throws PluginException if id or version does not exist """ PluginInfo pluginInfo = getPluginsMap().get(id); if (pluginInfo == null) { log.info("Plugin with id {} does not exist in any repository", id); throw new PluginException("Plugin with id {} not found in any repository", id); } if (version == null) { return getLastPluginRelease(id); } for (PluginRelease release : pluginInfo.releases) { if (versionManager.compareVersions(version, release.version) == 0 && release.url != null) { return release; } } throw new PluginException("Plugin {} with version @{} does not exist in the repository", id, version); }
java
protected PluginRelease findReleaseForPlugin(String id, String version) throws PluginException { PluginInfo pluginInfo = getPluginsMap().get(id); if (pluginInfo == null) { log.info("Plugin with id {} does not exist in any repository", id); throw new PluginException("Plugin with id {} not found in any repository", id); } if (version == null) { return getLastPluginRelease(id); } for (PluginRelease release : pluginInfo.releases) { if (versionManager.compareVersions(version, release.version) == 0 && release.url != null) { return release; } } throw new PluginException("Plugin {} with version @{} does not exist in the repository", id, version); }
[ "protected", "PluginRelease", "findReleaseForPlugin", "(", "String", "id", ",", "String", "version", ")", "throws", "PluginException", "{", "PluginInfo", "pluginInfo", "=", "getPluginsMap", "(", ")", ".", "get", "(", "id", ")", ";", "if", "(", "pluginInfo", "==", "null", ")", "{", "log", ".", "info", "(", "\"Plugin with id {} does not exist in any repository\"", ",", "id", ")", ";", "throw", "new", "PluginException", "(", "\"Plugin with id {} not found in any repository\"", ",", "id", ")", ";", "}", "if", "(", "version", "==", "null", ")", "{", "return", "getLastPluginRelease", "(", "id", ")", ";", "}", "for", "(", "PluginRelease", "release", ":", "pluginInfo", ".", "releases", ")", "{", "if", "(", "versionManager", ".", "compareVersions", "(", "version", ",", "release", ".", "version", ")", "==", "0", "&&", "release", ".", "url", "!=", "null", ")", "{", "return", "release", ";", "}", "}", "throw", "new", "PluginException", "(", "\"Plugin {} with version @{} does not exist in the repository\"", ",", "id", ",", "version", ")", ";", "}" ]
Resolves Release from id and version. @param id of plugin @param version of plugin or null to locate latest version @return PluginRelease for downloading @throws PluginException if id or version does not exist
[ "Resolves", "Release", "from", "id", "and", "version", "." ]
train
https://github.com/pf4j/pf4j-update/blob/80cf04b8f2790808d0cf9dff3602dc5d730ac979/src/main/java/org/pf4j/update/UpdateManager.java#L311-L329
jhunters/jprotobuf
v3/src/main/java/com/baidu/bjf/remoting/protobuf/code/CodedConstant.java
CodedConstant.computeListSize
public static int computeListSize(int order, List<?> list, FieldType type, boolean debug, File path) { """ Compute list size. @param order field order @param list field value @param type field type of list obj @param debug the debug @param path the path @return full java expression """ return computeListSize(order, list, type, debug, path, false, false); }
java
public static int computeListSize(int order, List<?> list, FieldType type, boolean debug, File path) { return computeListSize(order, list, type, debug, path, false, false); }
[ "public", "static", "int", "computeListSize", "(", "int", "order", ",", "List", "<", "?", ">", "list", ",", "FieldType", "type", ",", "boolean", "debug", ",", "File", "path", ")", "{", "return", "computeListSize", "(", "order", ",", "list", ",", "type", ",", "debug", ",", "path", ",", "false", ",", "false", ")", ";", "}" ]
Compute list size. @param order field order @param list field value @param type field type of list obj @param debug the debug @param path the path @return full java expression
[ "Compute", "list", "size", "." ]
train
https://github.com/jhunters/jprotobuf/blob/55832c9b4792afb128e5b35139d8a3891561d8a3/v3/src/main/java/com/baidu/bjf/remoting/protobuf/code/CodedConstant.java#L357-L359
sonyxperiadev/gerrit-events
src/main/java/com/sonymobile/tools/gerrit/gerritevents/GerritHandler.java
GerritHandler.shutdown
public void shutdown(boolean join) { """ Closes the handler. @param join if the method should wait for the thread to finish before returning. """ ThreadPoolExecutor pool = executor; executor = null; pool.shutdown(); // Disable new tasks from being submitted if (join) { try { // Wait a while for existing tasks to terminate if (!pool.awaitTermination(WAIT_FOR_JOBS_SHUTDOWN_TIMEOUT, TimeUnit.SECONDS)) { pool.shutdownNow(); // Cancel currently executing tasks // Wait a while for tasks to respond to being cancelled if (!pool.awaitTermination(WAIT_FOR_JOBS_SHUTDOWN_TIMEOUT, TimeUnit.SECONDS)) { logger.error("Pool did not terminate"); } } } catch (InterruptedException ie) { // (Re-)Cancel if current thread also interrupted pool.shutdownNow(); // Preserve interrupt status Thread.currentThread().interrupt(); } } }
java
public void shutdown(boolean join) { ThreadPoolExecutor pool = executor; executor = null; pool.shutdown(); // Disable new tasks from being submitted if (join) { try { // Wait a while for existing tasks to terminate if (!pool.awaitTermination(WAIT_FOR_JOBS_SHUTDOWN_TIMEOUT, TimeUnit.SECONDS)) { pool.shutdownNow(); // Cancel currently executing tasks // Wait a while for tasks to respond to being cancelled if (!pool.awaitTermination(WAIT_FOR_JOBS_SHUTDOWN_TIMEOUT, TimeUnit.SECONDS)) { logger.error("Pool did not terminate"); } } } catch (InterruptedException ie) { // (Re-)Cancel if current thread also interrupted pool.shutdownNow(); // Preserve interrupt status Thread.currentThread().interrupt(); } } }
[ "public", "void", "shutdown", "(", "boolean", "join", ")", "{", "ThreadPoolExecutor", "pool", "=", "executor", ";", "executor", "=", "null", ";", "pool", ".", "shutdown", "(", ")", ";", "// Disable new tasks from being submitted", "if", "(", "join", ")", "{", "try", "{", "// Wait a while for existing tasks to terminate", "if", "(", "!", "pool", ".", "awaitTermination", "(", "WAIT_FOR_JOBS_SHUTDOWN_TIMEOUT", ",", "TimeUnit", ".", "SECONDS", ")", ")", "{", "pool", ".", "shutdownNow", "(", ")", ";", "// Cancel currently executing tasks", "// Wait a while for tasks to respond to being cancelled", "if", "(", "!", "pool", ".", "awaitTermination", "(", "WAIT_FOR_JOBS_SHUTDOWN_TIMEOUT", ",", "TimeUnit", ".", "SECONDS", ")", ")", "{", "logger", ".", "error", "(", "\"Pool did not terminate\"", ")", ";", "}", "}", "}", "catch", "(", "InterruptedException", "ie", ")", "{", "// (Re-)Cancel if current thread also interrupted", "pool", ".", "shutdownNow", "(", ")", ";", "// Preserve interrupt status", "Thread", ".", "currentThread", "(", ")", ".", "interrupt", "(", ")", ";", "}", "}", "}" ]
Closes the handler. @param join if the method should wait for the thread to finish before returning.
[ "Closes", "the", "handler", "." ]
train
https://github.com/sonyxperiadev/gerrit-events/blob/9a443d13dded85cc4709136ac33989f2bbb34fe2/src/main/java/com/sonymobile/tools/gerrit/gerritevents/GerritHandler.java#L547-L568
dhanji/sitebricks
sitebricks/src/main/java/com/google/sitebricks/compiler/HtmlParser.java
HtmlParser.addTextNodeToParent
private void addTextNodeToParent (String text, Element parent, AnnotationNode annotation) { """ Break the text up by the first line delimiter. We only want annotations applied to the first line of a block of text and not to a whole segment. @param text the text to turn into nodes @param parent the parent node @param annotation the current annotation to be applied to the first line of text """ String [] lines = new String[] {text}; if (annotation != null) lines = splitInTwo(text); for (int i = 0; i < lines.length; i++){ TextNode textNode = TextNode.createFromEncoded(lines[i], baseUri); lines(textNode, lines[i]); // apply the annotation and reset it to null if (annotation != null && i == 0) annotation.apply(textNode); // put the text node on the parent parent.appendChild(textNode); } }
java
private void addTextNodeToParent (String text, Element parent, AnnotationNode annotation) { String [] lines = new String[] {text}; if (annotation != null) lines = splitInTwo(text); for (int i = 0; i < lines.length; i++){ TextNode textNode = TextNode.createFromEncoded(lines[i], baseUri); lines(textNode, lines[i]); // apply the annotation and reset it to null if (annotation != null && i == 0) annotation.apply(textNode); // put the text node on the parent parent.appendChild(textNode); } }
[ "private", "void", "addTextNodeToParent", "(", "String", "text", ",", "Element", "parent", ",", "AnnotationNode", "annotation", ")", "{", "String", "[", "]", "lines", "=", "new", "String", "[", "]", "{", "text", "}", ";", "if", "(", "annotation", "!=", "null", ")", "lines", "=", "splitInTwo", "(", "text", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "lines", ".", "length", ";", "i", "++", ")", "{", "TextNode", "textNode", "=", "TextNode", ".", "createFromEncoded", "(", "lines", "[", "i", "]", ",", "baseUri", ")", ";", "lines", "(", "textNode", ",", "lines", "[", "i", "]", ")", ";", "// apply the annotation and reset it to null", "if", "(", "annotation", "!=", "null", "&&", "i", "==", "0", ")", "annotation", ".", "apply", "(", "textNode", ")", ";", "// put the text node on the parent", "parent", ".", "appendChild", "(", "textNode", ")", ";", "}", "}" ]
Break the text up by the first line delimiter. We only want annotations applied to the first line of a block of text and not to a whole segment. @param text the text to turn into nodes @param parent the parent node @param annotation the current annotation to be applied to the first line of text
[ "Break", "the", "text", "up", "by", "the", "first", "line", "delimiter", ".", "We", "only", "want", "annotations", "applied", "to", "the", "first", "line", "of", "a", "block", "of", "text", "and", "not", "to", "a", "whole", "segment", "." ]
train
https://github.com/dhanji/sitebricks/blob/8682029a78bd48fb8566173d970800499e9e5d97/sitebricks/src/main/java/com/google/sitebricks/compiler/HtmlParser.java#L330-L347
adyliu/jafka
src/main/java/io/jafka/utils/Utils.java
Utils.newThread
public static Thread newThread(String name, Runnable runnable, boolean daemon) { """ Create a new thread @param name The name of the thread @param runnable The work for the thread to do @param daemon Should the thread block JVM shutdown? @return The unstarted thread """ Thread thread = new Thread(runnable, name); thread.setDaemon(daemon); return thread; }
java
public static Thread newThread(String name, Runnable runnable, boolean daemon) { Thread thread = new Thread(runnable, name); thread.setDaemon(daemon); return thread; }
[ "public", "static", "Thread", "newThread", "(", "String", "name", ",", "Runnable", "runnable", ",", "boolean", "daemon", ")", "{", "Thread", "thread", "=", "new", "Thread", "(", "runnable", ",", "name", ")", ";", "thread", ".", "setDaemon", "(", "daemon", ")", ";", "return", "thread", ";", "}" ]
Create a new thread @param name The name of the thread @param runnable The work for the thread to do @param daemon Should the thread block JVM shutdown? @return The unstarted thread
[ "Create", "a", "new", "thread" ]
train
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/utils/Utils.java#L322-L326
gmessner/gitlab4j-api
src/main/java/org/gitlab4j/api/NotesApi.java
NotesApi.getMergeRequestNote
public Note getMergeRequestNote(Object projectIdOrPath, Integer mergeRequestIid, Integer noteId) throws GitLabApiException { """ Get the specified merge request's note. @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance @param mergeRequestIid the merge request IID to get the notes for @param noteId the ID of the Note to get @return a Note instance for the specified IDs @throws GitLabApiException if any exception occurs """ Response response = get(Response.Status.OK, getDefaultPerPageParam(), "projects", getProjectIdOrPath(projectIdOrPath), "merge_requests", mergeRequestIid, "notes", noteId); return (response.readEntity(Note.class)); }
java
public Note getMergeRequestNote(Object projectIdOrPath, Integer mergeRequestIid, Integer noteId) throws GitLabApiException { Response response = get(Response.Status.OK, getDefaultPerPageParam(), "projects", getProjectIdOrPath(projectIdOrPath), "merge_requests", mergeRequestIid, "notes", noteId); return (response.readEntity(Note.class)); }
[ "public", "Note", "getMergeRequestNote", "(", "Object", "projectIdOrPath", ",", "Integer", "mergeRequestIid", ",", "Integer", "noteId", ")", "throws", "GitLabApiException", "{", "Response", "response", "=", "get", "(", "Response", ".", "Status", ".", "OK", ",", "getDefaultPerPageParam", "(", ")", ",", "\"projects\"", ",", "getProjectIdOrPath", "(", "projectIdOrPath", ")", ",", "\"merge_requests\"", ",", "mergeRequestIid", ",", "\"notes\"", ",", "noteId", ")", ";", "return", "(", "response", ".", "readEntity", "(", "Note", ".", "class", ")", ")", ";", "}" ]
Get the specified merge request's note. @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance @param mergeRequestIid the merge request IID to get the notes for @param noteId the ID of the Note to get @return a Note instance for the specified IDs @throws GitLabApiException if any exception occurs
[ "Get", "the", "specified", "merge", "request", "s", "note", "." ]
train
https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/NotesApi.java#L371-L375
b3dgs/lionengine
lionengine-core/src/main/java/com/b3dgs/lionengine/XmlReader.java
XmlReader.getValue
private String getValue(String defaultValue, String attribute) { """ Get the attribute value. @param defaultValue The value returned if attribute does not exist (can be <code>null</code>). @param attribute The attribute name (must not be <code>null</code>). @return The attribute value. @throws LionEngineException If attribute is not valid or does not exist. """ Check.notNull(attribute); if (root.hasAttribute(attribute)) { return root.getAttribute(attribute); } return defaultValue; }
java
private String getValue(String defaultValue, String attribute) { Check.notNull(attribute); if (root.hasAttribute(attribute)) { return root.getAttribute(attribute); } return defaultValue; }
[ "private", "String", "getValue", "(", "String", "defaultValue", ",", "String", "attribute", ")", "{", "Check", ".", "notNull", "(", "attribute", ")", ";", "if", "(", "root", ".", "hasAttribute", "(", "attribute", ")", ")", "{", "return", "root", ".", "getAttribute", "(", "attribute", ")", ";", "}", "return", "defaultValue", ";", "}" ]
Get the attribute value. @param defaultValue The value returned if attribute does not exist (can be <code>null</code>). @param attribute The attribute name (must not be <code>null</code>). @return The attribute value. @throws LionEngineException If attribute is not valid or does not exist.
[ "Get", "the", "attribute", "value", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-core/src/main/java/com/b3dgs/lionengine/XmlReader.java#L434-L443
javamelody/javamelody
javamelody-core/src/main/java/net/bull/javamelody/internal/model/RrdNioBackendFactory.java
RrdNioBackendFactory.open
@Override protected RrdBackend open(String path, boolean readOnly) throws IOException { """ Creates RrdNioBackend object for the given file path. @param path File path @param readOnly True, if the file should be accessed in read/only mode. False otherwise. @return RrdNioBackend object which handles all I/O operations for the given file path @throws IOException Thrown in case of I/O error. """ return new RrdNioBackend(path, readOnly, syncPeriod); }
java
@Override protected RrdBackend open(String path, boolean readOnly) throws IOException { return new RrdNioBackend(path, readOnly, syncPeriod); }
[ "@", "Override", "protected", "RrdBackend", "open", "(", "String", "path", ",", "boolean", "readOnly", ")", "throws", "IOException", "{", "return", "new", "RrdNioBackend", "(", "path", ",", "readOnly", ",", "syncPeriod", ")", ";", "}" ]
Creates RrdNioBackend object for the given file path. @param path File path @param readOnly True, if the file should be accessed in read/only mode. False otherwise. @return RrdNioBackend object which handles all I/O operations for the given file path @throws IOException Thrown in case of I/O error.
[ "Creates", "RrdNioBackend", "object", "for", "the", "given", "file", "path", "." ]
train
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/internal/model/RrdNioBackendFactory.java#L82-L85
super-csv/super-csv
super-csv-joda/src/main/java/org/supercsv/cellprocessor/joda/AbstractJodaFormattingProcessor.java
AbstractJodaFormattingProcessor.execute
public Object execute(final Object value, final CsvContext context) { """ {@inheritDoc} @throws SuperCsvCellProcessorException if value is null, not the correct type, or can't be formatted """ validateInputNotNull(value, context); if (!(value.getClass().equals(jodaClass))) { throw new SuperCsvCellProcessorException(jodaClass, value, context, this); } final T jodaType = jodaClass.cast(value); try { if (formatter != null) { return format(jodaType, formatter); } else if (pattern != null) { return format(jodaType, pattern, locale); } else { return format(jodaType); } } catch (IllegalArgumentException e) { throw new SuperCsvCellProcessorException( String.format("Failed to format value as a %s", jodaClass.getSimpleName()), context, this, e); } }
java
public Object execute(final Object value, final CsvContext context) { validateInputNotNull(value, context); if (!(value.getClass().equals(jodaClass))) { throw new SuperCsvCellProcessorException(jodaClass, value, context, this); } final T jodaType = jodaClass.cast(value); try { if (formatter != null) { return format(jodaType, formatter); } else if (pattern != null) { return format(jodaType, pattern, locale); } else { return format(jodaType); } } catch (IllegalArgumentException e) { throw new SuperCsvCellProcessorException( String.format("Failed to format value as a %s", jodaClass.getSimpleName()), context, this, e); } }
[ "public", "Object", "execute", "(", "final", "Object", "value", ",", "final", "CsvContext", "context", ")", "{", "validateInputNotNull", "(", "value", ",", "context", ")", ";", "if", "(", "!", "(", "value", ".", "getClass", "(", ")", ".", "equals", "(", "jodaClass", ")", ")", ")", "{", "throw", "new", "SuperCsvCellProcessorException", "(", "jodaClass", ",", "value", ",", "context", ",", "this", ")", ";", "}", "final", "T", "jodaType", "=", "jodaClass", ".", "cast", "(", "value", ")", ";", "try", "{", "if", "(", "formatter", "!=", "null", ")", "{", "return", "format", "(", "jodaType", ",", "formatter", ")", ";", "}", "else", "if", "(", "pattern", "!=", "null", ")", "{", "return", "format", "(", "jodaType", ",", "pattern", ",", "locale", ")", ";", "}", "else", "{", "return", "format", "(", "jodaType", ")", ";", "}", "}", "catch", "(", "IllegalArgumentException", "e", ")", "{", "throw", "new", "SuperCsvCellProcessorException", "(", "String", ".", "format", "(", "\"Failed to format value as a %s\"", ",", "jodaClass", ".", "getSimpleName", "(", ")", ")", ",", "context", ",", "this", ",", "e", ")", ";", "}", "}" ]
{@inheritDoc} @throws SuperCsvCellProcessorException if value is null, not the correct type, or can't be formatted
[ "{", "@inheritDoc", "}" ]
train
https://github.com/super-csv/super-csv/blob/f18db724674dc1c4116e25142c1b5403ebf43e96/super-csv-joda/src/main/java/org/supercsv/cellprocessor/joda/AbstractJodaFormattingProcessor.java#L276-L296
VoltDB/voltdb
src/frontend/org/voltdb/TheHashinator.java
TheHashinator.getHashedPartitionForParameter
public int getHashedPartitionForParameter(int partitionValueType, Object partitionValue) { """ Given the type of the targeting partition parameter and an object, coerce the object to the correct type and hash it. NOTE NOTE NOTE NOTE! THIS SHOULD BE THE ONLY WAY THAT YOU FIGURE OUT THE PARTITIONING FOR A PARAMETER! THIS IS SHARED BY SERVER AND CLIENT CLIENT USES direct instance method as it initializes its own per connection Hashinator. @return The partition best set up to execute the procedure. @throws VoltTypeException """ final VoltType partitionParamType = VoltType.get((byte) partitionValueType); return getHashedPartitionForParameter(partitionParamType, partitionValue); }
java
public int getHashedPartitionForParameter(int partitionValueType, Object partitionValue) { final VoltType partitionParamType = VoltType.get((byte) partitionValueType); return getHashedPartitionForParameter(partitionParamType, partitionValue); }
[ "public", "int", "getHashedPartitionForParameter", "(", "int", "partitionValueType", ",", "Object", "partitionValue", ")", "{", "final", "VoltType", "partitionParamType", "=", "VoltType", ".", "get", "(", "(", "byte", ")", "partitionValueType", ")", ";", "return", "getHashedPartitionForParameter", "(", "partitionParamType", ",", "partitionValue", ")", ";", "}" ]
Given the type of the targeting partition parameter and an object, coerce the object to the correct type and hash it. NOTE NOTE NOTE NOTE! THIS SHOULD BE THE ONLY WAY THAT YOU FIGURE OUT THE PARTITIONING FOR A PARAMETER! THIS IS SHARED BY SERVER AND CLIENT CLIENT USES direct instance method as it initializes its own per connection Hashinator. @return The partition best set up to execute the procedure. @throws VoltTypeException
[ "Given", "the", "type", "of", "the", "targeting", "partition", "parameter", "and", "an", "object", "coerce", "the", "object", "to", "the", "correct", "type", "and", "hash", "it", ".", "NOTE", "NOTE", "NOTE", "NOTE!", "THIS", "SHOULD", "BE", "THE", "ONLY", "WAY", "THAT", "YOU", "FIGURE", "OUT", "THE", "PARTITIONING", "FOR", "A", "PARAMETER!", "THIS", "IS", "SHARED", "BY", "SERVER", "AND", "CLIENT", "CLIENT", "USES", "direct", "instance", "method", "as", "it", "initializes", "its", "own", "per", "connection", "Hashinator", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/TheHashinator.java#L268-L271
GenesysPureEngage/workspace-client-java
src/main/java/com/genesys/internal/workspace/api/TargetsApi.java
TargetsApi.getTargetsAsync
public com.squareup.okhttp.Call getTargetsAsync(String searchTerm, String filterName, String types, String excludeGroup, String restrictGroup, String excludeFromGroup, String restrictToGroup, String sort, BigDecimal limit, String matchType, final ApiCallback<TargetsResponse> callback) throws ApiException { """ Search for targets (asynchronously) Search for targets by the specified search term. @param searchTerm The text to search for in targets. (required) @param filterName Filter the search based on this field. (optional) @param types A comma-separated list of types to include in the search. Valid values are &#x60;acd-queue&#x60;, &#x60;agent-group&#x60;, &#x60;agent&#x60;, &#x60;queue&#x60;, &#x60;route-point&#x60;, &#x60;skill&#x60;, and &#x60;custom-contact&#x60;. (optional) @param excludeGroup A comma-separated list of agent group names. Workspace excludes those groups from the search. (optional) @param restrictGroup A comma-separated list of agent group names. Workspace returns only these groups from the search. (optional) @param excludeFromGroup A comma-separated list of agent group names. Workspace excludes agents from these groups in the search. (optional) @param restrictToGroup A comma-separated list of agent group names. Workspace only searches for targets who belong to the groups in this list. (optional) @param sort The sort order, either ascending or descending. The default is descending. (optional) @param limit The number of results to return. The default value is 50. (optional) @param matchType Specify whether the search should only return exact matches. (optional) @param callback The callback to be executed when the API call finishes @return The request call @throws ApiException If fail to process the API call, e.g. serializing the request body object """ ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = getTargetsValidateBeforeCall(searchTerm, filterName, types, excludeGroup, restrictGroup, excludeFromGroup, restrictToGroup, sort, limit, matchType, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<TargetsResponse>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; }
java
public com.squareup.okhttp.Call getTargetsAsync(String searchTerm, String filterName, String types, String excludeGroup, String restrictGroup, String excludeFromGroup, String restrictToGroup, String sort, BigDecimal limit, String matchType, final ApiCallback<TargetsResponse> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = getTargetsValidateBeforeCall(searchTerm, filterName, types, excludeGroup, restrictGroup, excludeFromGroup, restrictToGroup, sort, limit, matchType, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<TargetsResponse>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; }
[ "public", "com", ".", "squareup", ".", "okhttp", ".", "Call", "getTargetsAsync", "(", "String", "searchTerm", ",", "String", "filterName", ",", "String", "types", ",", "String", "excludeGroup", ",", "String", "restrictGroup", ",", "String", "excludeFromGroup", ",", "String", "restrictToGroup", ",", "String", "sort", ",", "BigDecimal", "limit", ",", "String", "matchType", ",", "final", "ApiCallback", "<", "TargetsResponse", ">", "callback", ")", "throws", "ApiException", "{", "ProgressResponseBody", ".", "ProgressListener", "progressListener", "=", "null", ";", "ProgressRequestBody", ".", "ProgressRequestListener", "progressRequestListener", "=", "null", ";", "if", "(", "callback", "!=", "null", ")", "{", "progressListener", "=", "new", "ProgressResponseBody", ".", "ProgressListener", "(", ")", "{", "@", "Override", "public", "void", "update", "(", "long", "bytesRead", ",", "long", "contentLength", ",", "boolean", "done", ")", "{", "callback", ".", "onDownloadProgress", "(", "bytesRead", ",", "contentLength", ",", "done", ")", ";", "}", "}", ";", "progressRequestListener", "=", "new", "ProgressRequestBody", ".", "ProgressRequestListener", "(", ")", "{", "@", "Override", "public", "void", "onRequestProgress", "(", "long", "bytesWritten", ",", "long", "contentLength", ",", "boolean", "done", ")", "{", "callback", ".", "onUploadProgress", "(", "bytesWritten", ",", "contentLength", ",", "done", ")", ";", "}", "}", ";", "}", "com", ".", "squareup", ".", "okhttp", ".", "Call", "call", "=", "getTargetsValidateBeforeCall", "(", "searchTerm", ",", "filterName", ",", "types", ",", "excludeGroup", ",", "restrictGroup", ",", "excludeFromGroup", ",", "restrictToGroup", ",", "sort", ",", "limit", ",", "matchType", ",", "progressListener", ",", "progressRequestListener", ")", ";", "Type", "localVarReturnType", "=", "new", "TypeToken", "<", "TargetsResponse", ">", "(", ")", "{", "}", ".", "getType", "(", ")", ";", "apiClient", ".", "executeAsync", "(", "call", ",", "localVarReturnType", ",", "callback", ")", ";", "return", "call", ";", "}" ]
Search for targets (asynchronously) Search for targets by the specified search term. @param searchTerm The text to search for in targets. (required) @param filterName Filter the search based on this field. (optional) @param types A comma-separated list of types to include in the search. Valid values are &#x60;acd-queue&#x60;, &#x60;agent-group&#x60;, &#x60;agent&#x60;, &#x60;queue&#x60;, &#x60;route-point&#x60;, &#x60;skill&#x60;, and &#x60;custom-contact&#x60;. (optional) @param excludeGroup A comma-separated list of agent group names. Workspace excludes those groups from the search. (optional) @param restrictGroup A comma-separated list of agent group names. Workspace returns only these groups from the search. (optional) @param excludeFromGroup A comma-separated list of agent group names. Workspace excludes agents from these groups in the search. (optional) @param restrictToGroup A comma-separated list of agent group names. Workspace only searches for targets who belong to the groups in this list. (optional) @param sort The sort order, either ascending or descending. The default is descending. (optional) @param limit The number of results to return. The default value is 50. (optional) @param matchType Specify whether the search should only return exact matches. (optional) @param callback The callback to be executed when the API call finishes @return The request call @throws ApiException If fail to process the API call, e.g. serializing the request body object
[ "Search", "for", "targets", "(", "asynchronously", ")", "Search", "for", "targets", "by", "the", "specified", "search", "term", "." ]
train
https://github.com/GenesysPureEngage/workspace-client-java/blob/509fdd9e89b9359d012f9a72be95037a3cef53e6/src/main/java/com/genesys/internal/workspace/api/TargetsApi.java#L953-L978
hawkular/hawkular-commons
hawkular-bus/hawkular-bus-rest-client/src/main/java/org/hawkular/bus/restclient/RestClient.java
RestClient.postQueueMessage
public HttpResponse postQueueMessage(String queueName, String jsonPayload, Map<String, String> headers) throws RestClientException { """ Sends a message to the REST endpoint in order to put a message on the given queue. @param queueName name of the queue @param jsonPayload the actual message (as a JSON string) to put on the bus @param headers any headers to send with the message (can be null or empty) @return the response @throws RestClientException if the response was not a 200 status code """ return postMessage(Type.QUEUE, queueName, jsonPayload, headers); }
java
public HttpResponse postQueueMessage(String queueName, String jsonPayload, Map<String, String> headers) throws RestClientException { return postMessage(Type.QUEUE, queueName, jsonPayload, headers); }
[ "public", "HttpResponse", "postQueueMessage", "(", "String", "queueName", ",", "String", "jsonPayload", ",", "Map", "<", "String", ",", "String", ">", "headers", ")", "throws", "RestClientException", "{", "return", "postMessage", "(", "Type", ".", "QUEUE", ",", "queueName", ",", "jsonPayload", ",", "headers", ")", ";", "}" ]
Sends a message to the REST endpoint in order to put a message on the given queue. @param queueName name of the queue @param jsonPayload the actual message (as a JSON string) to put on the bus @param headers any headers to send with the message (can be null or empty) @return the response @throws RestClientException if the response was not a 200 status code
[ "Sends", "a", "message", "to", "the", "REST", "endpoint", "in", "order", "to", "put", "a", "message", "on", "the", "given", "queue", "." ]
train
https://github.com/hawkular/hawkular-commons/blob/e4a832862b3446d7f4d629bb05790f2df578e035/hawkular-bus/hawkular-bus-rest-client/src/main/java/org/hawkular/bus/restclient/RestClient.java#L143-L146
DataSketches/sketches-core
src/main/java/com/yahoo/sketches/hash/MurmurHash3Adaptor.java
MurmurHash3Adaptor.hashToLongs
public static long[] hashToLongs(final double datum, final long seed) { """ Hash a double and long seed. @param datum the input double. @param seed A long valued seed. @return The 128-bit hash as a long[2]. """ final double d = (datum == 0.0) ? 0.0 : datum; //canonicalize -0.0, 0.0 final long[] data = { Double.doubleToLongBits(d) };//canonicalize all NaN forms return hash(data, seed); }
java
public static long[] hashToLongs(final double datum, final long seed) { final double d = (datum == 0.0) ? 0.0 : datum; //canonicalize -0.0, 0.0 final long[] data = { Double.doubleToLongBits(d) };//canonicalize all NaN forms return hash(data, seed); }
[ "public", "static", "long", "[", "]", "hashToLongs", "(", "final", "double", "datum", ",", "final", "long", "seed", ")", "{", "final", "double", "d", "=", "(", "datum", "==", "0.0", ")", "?", "0.0", ":", "datum", ";", "//canonicalize -0.0, 0.0", "final", "long", "[", "]", "data", "=", "{", "Double", ".", "doubleToLongBits", "(", "d", ")", "}", ";", "//canonicalize all NaN forms", "return", "hash", "(", "data", ",", "seed", ")", ";", "}" ]
Hash a double and long seed. @param datum the input double. @param seed A long valued seed. @return The 128-bit hash as a long[2].
[ "Hash", "a", "double", "and", "long", "seed", "." ]
train
https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/hash/MurmurHash3Adaptor.java#L208-L212
googleapis/google-cloud-java
google-cloud-clients/google-cloud-datastore/src/main/java/com/google/cloud/datastore/Key.java
Key.fromUrlSafe
public static Key fromUrlSafe(String urlSafe) { """ Create a {@code Key} given its URL safe encoded form. @throws IllegalArgumentException when decoding fails """ try { String utf8Str = URLDecoder.decode(urlSafe, UTF_8.name()); com.google.datastore.v1.Key.Builder builder = com.google.datastore.v1.Key.newBuilder(); TextFormat.merge(utf8Str, builder); return fromPb(builder.build()); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("Unexpected decoding exception", e); } catch (TextFormat.ParseException e) { throw new IllegalArgumentException("Could not parse key", e); } }
java
public static Key fromUrlSafe(String urlSafe) { try { String utf8Str = URLDecoder.decode(urlSafe, UTF_8.name()); com.google.datastore.v1.Key.Builder builder = com.google.datastore.v1.Key.newBuilder(); TextFormat.merge(utf8Str, builder); return fromPb(builder.build()); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("Unexpected decoding exception", e); } catch (TextFormat.ParseException e) { throw new IllegalArgumentException("Could not parse key", e); } }
[ "public", "static", "Key", "fromUrlSafe", "(", "String", "urlSafe", ")", "{", "try", "{", "String", "utf8Str", "=", "URLDecoder", ".", "decode", "(", "urlSafe", ",", "UTF_8", ".", "name", "(", ")", ")", ";", "com", ".", "google", ".", "datastore", ".", "v1", ".", "Key", ".", "Builder", "builder", "=", "com", ".", "google", ".", "datastore", ".", "v1", ".", "Key", ".", "newBuilder", "(", ")", ";", "TextFormat", ".", "merge", "(", "utf8Str", ",", "builder", ")", ";", "return", "fromPb", "(", "builder", ".", "build", "(", ")", ")", ";", "}", "catch", "(", "UnsupportedEncodingException", "e", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Unexpected decoding exception\"", ",", "e", ")", ";", "}", "catch", "(", "TextFormat", ".", "ParseException", "e", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Could not parse key\"", ",", "e", ")", ";", "}", "}" ]
Create a {@code Key} given its URL safe encoded form. @throws IllegalArgumentException when decoding fails
[ "Create", "a", "{", "@code", "Key", "}", "given", "its", "URL", "safe", "encoded", "form", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-datastore/src/main/java/com/google/cloud/datastore/Key.java#L142-L153
jeremybrooks/jinx
src/main/java/net/jeremybrooks/jinx/api/PhotosetsApi.java
PhotosetsApi.removePhotos
public Response removePhotos(String photosetId, List<String> photoIds) throws JinxException { """ Remove multiple photos from a photoset. <br> This method requires authentication with 'write' permission. <br> Note: This method requires an HTTP POST request. @param photosetId id of the photoset to remove a photo from. @param photoIds list of photo id's to remove from the photoset. @return an empty success response if it completes without error. @throws JinxException if any parameter is null or empty, or if there are other errors. @see <a href="https://www.flickr.com/services/api/flickr.photosets.removePhotos.html">flickr.photosets.removePhotos</a> """ JinxUtils.validateParams(photosetId, photoIds); Map<String, String> params = new TreeMap<>(); params.put("method", "flickr.photosets.removePhotos"); params.put("photoset_id", photosetId); params.put("photo_ids", JinxUtils.buildCommaDelimitedList(photoIds)); return jinx.flickrPost(params, Response.class); }
java
public Response removePhotos(String photosetId, List<String> photoIds) throws JinxException { JinxUtils.validateParams(photosetId, photoIds); Map<String, String> params = new TreeMap<>(); params.put("method", "flickr.photosets.removePhotos"); params.put("photoset_id", photosetId); params.put("photo_ids", JinxUtils.buildCommaDelimitedList(photoIds)); return jinx.flickrPost(params, Response.class); }
[ "public", "Response", "removePhotos", "(", "String", "photosetId", ",", "List", "<", "String", ">", "photoIds", ")", "throws", "JinxException", "{", "JinxUtils", ".", "validateParams", "(", "photosetId", ",", "photoIds", ")", ";", "Map", "<", "String", ",", "String", ">", "params", "=", "new", "TreeMap", "<>", "(", ")", ";", "params", ".", "put", "(", "\"method\"", ",", "\"flickr.photosets.removePhotos\"", ")", ";", "params", ".", "put", "(", "\"photoset_id\"", ",", "photosetId", ")", ";", "params", ".", "put", "(", "\"photo_ids\"", ",", "JinxUtils", ".", "buildCommaDelimitedList", "(", "photoIds", ")", ")", ";", "return", "jinx", ".", "flickrPost", "(", "params", ",", "Response", ".", "class", ")", ";", "}" ]
Remove multiple photos from a photoset. <br> This method requires authentication with 'write' permission. <br> Note: This method requires an HTTP POST request. @param photosetId id of the photoset to remove a photo from. @param photoIds list of photo id's to remove from the photoset. @return an empty success response if it completes without error. @throws JinxException if any parameter is null or empty, or if there are other errors. @see <a href="https://www.flickr.com/services/api/flickr.photosets.removePhotos.html">flickr.photosets.removePhotos</a>
[ "Remove", "multiple", "photos", "from", "a", "photoset", ".", "<br", ">", "This", "method", "requires", "authentication", "with", "write", "permission", ".", "<br", ">", "Note", ":", "This", "method", "requires", "an", "HTTP", "POST", "request", "." ]
train
https://github.com/jeremybrooks/jinx/blob/ab7a4b7462d08bcbfd9b98bd3f5029771c20f6c6/src/main/java/net/jeremybrooks/jinx/api/PhotosetsApi.java#L356-L363
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDValidation.java
SDValidation.validateNumerical
protected static void validateNumerical(String opName, SDVariable v1, SDVariable v2) { """ Validate that the operation is being applied on numerical SDVariables (not boolean or utf8). Some operations (such as sum, norm2, add(Number) etc don't make sense when applied to boolean/utf8 arrays @param opName Operation name to print in the exception @param v1 Variable to validate datatype for (input to operation) @param v2 Variable to validate datatype for (input to operation) """ if (v1.dataType() == DataType.BOOL || v1.dataType() == DataType.UTF8 || v2.dataType() == DataType.BOOL || v2.dataType() == DataType.UTF8) throw new IllegalStateException("Cannot perform operation \"" + opName + "\" on variables \"" + v1.getVarName() + "\" and \"" + v2.getVarName() + "\" if one or both variables are non-numerical: " + v1.dataType() + " and " + v2.dataType()); }
java
protected static void validateNumerical(String opName, SDVariable v1, SDVariable v2) { if (v1.dataType() == DataType.BOOL || v1.dataType() == DataType.UTF8 || v2.dataType() == DataType.BOOL || v2.dataType() == DataType.UTF8) throw new IllegalStateException("Cannot perform operation \"" + opName + "\" on variables \"" + v1.getVarName() + "\" and \"" + v2.getVarName() + "\" if one or both variables are non-numerical: " + v1.dataType() + " and " + v2.dataType()); }
[ "protected", "static", "void", "validateNumerical", "(", "String", "opName", ",", "SDVariable", "v1", ",", "SDVariable", "v2", ")", "{", "if", "(", "v1", ".", "dataType", "(", ")", "==", "DataType", ".", "BOOL", "||", "v1", ".", "dataType", "(", ")", "==", "DataType", ".", "UTF8", "||", "v2", ".", "dataType", "(", ")", "==", "DataType", ".", "BOOL", "||", "v2", ".", "dataType", "(", ")", "==", "DataType", ".", "UTF8", ")", "throw", "new", "IllegalStateException", "(", "\"Cannot perform operation \\\"\"", "+", "opName", "+", "\"\\\" on variables \\\"\"", "+", "v1", ".", "getVarName", "(", ")", "+", "\"\\\" and \\\"\"", "+", "v2", ".", "getVarName", "(", ")", "+", "\"\\\" if one or both variables are non-numerical: \"", "+", "v1", ".", "dataType", "(", ")", "+", "\" and \"", "+", "v2", ".", "dataType", "(", ")", ")", ";", "}" ]
Validate that the operation is being applied on numerical SDVariables (not boolean or utf8). Some operations (such as sum, norm2, add(Number) etc don't make sense when applied to boolean/utf8 arrays @param opName Operation name to print in the exception @param v1 Variable to validate datatype for (input to operation) @param v2 Variable to validate datatype for (input to operation)
[ "Validate", "that", "the", "operation", "is", "being", "applied", "on", "numerical", "SDVariables", "(", "not", "boolean", "or", "utf8", ")", ".", "Some", "operations", "(", "such", "as", "sum", "norm2", "add", "(", "Number", ")", "etc", "don", "t", "make", "sense", "when", "applied", "to", "boolean", "/", "utf8", "arrays" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDValidation.java#L50-L54
line/armeria
core/src/main/java/com/linecorp/armeria/server/throttling/ThrottlingHttpService.java
ThrottlingHttpService.onFailure
@Override protected HttpResponse onFailure(ServiceRequestContext ctx, HttpRequest req, @Nullable Throwable cause) throws Exception { """ Invoked when {@code req} is throttled. By default, this method responds with the {@link HttpStatus#SERVICE_UNAVAILABLE} status. """ return HttpResponse.of(HttpStatus.SERVICE_UNAVAILABLE); }
java
@Override protected HttpResponse onFailure(ServiceRequestContext ctx, HttpRequest req, @Nullable Throwable cause) throws Exception { return HttpResponse.of(HttpStatus.SERVICE_UNAVAILABLE); }
[ "@", "Override", "protected", "HttpResponse", "onFailure", "(", "ServiceRequestContext", "ctx", ",", "HttpRequest", "req", ",", "@", "Nullable", "Throwable", "cause", ")", "throws", "Exception", "{", "return", "HttpResponse", ".", "of", "(", "HttpStatus", ".", "SERVICE_UNAVAILABLE", ")", ";", "}" ]
Invoked when {@code req} is throttled. By default, this method responds with the {@link HttpStatus#SERVICE_UNAVAILABLE} status.
[ "Invoked", "when", "{" ]
train
https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/core/src/main/java/com/linecorp/armeria/server/throttling/ThrottlingHttpService.java#L57-L61
jmeetsma/Iglu-Common
src/main/java/org/ijsberg/iglu/configuration/classloading/ExtendedClassPathClassLoader.java
ExtendedClassPathClassLoader.findClass
public Class<?> findClass(String className) throws ClassNotFoundException { """ Tries to locate a class in the specific class path. @param className @return @throws ClassNotFoundException """ Object location = classResourceLocations.get(className); if (location == null && this.propertiesResourceLocations.containsKey(className)) { String fileName = (String) propertiesResourceLocations.get(className); if (fileName.endsWith(".properties")) { //notify invoker that file is present as properties file return ResourceBundle.class; } else { throw new ClassNotFoundException("resource '" + fileName + "' for class '" + className + "' has incompatible format"); } } if (className.startsWith("java.")) { return super.findClass(className); } if (location == null) { throw new ClassNotFoundException("class '" + className + "' not found in " + classpath); } String fileName = className.replace('.', '/') + ".class"; byte[] data; try { data = getData(fileName, location); } catch (IOException ioe) { throw new NoClassDefFoundError("class '" + className + "' could not be loaded from '" + location + "' with message: " + ioe); } return defineClass(className, data, 0, data.length); }
java
public Class<?> findClass(String className) throws ClassNotFoundException { Object location = classResourceLocations.get(className); if (location == null && this.propertiesResourceLocations.containsKey(className)) { String fileName = (String) propertiesResourceLocations.get(className); if (fileName.endsWith(".properties")) { //notify invoker that file is present as properties file return ResourceBundle.class; } else { throw new ClassNotFoundException("resource '" + fileName + "' for class '" + className + "' has incompatible format"); } } if (className.startsWith("java.")) { return super.findClass(className); } if (location == null) { throw new ClassNotFoundException("class '" + className + "' not found in " + classpath); } String fileName = className.replace('.', '/') + ".class"; byte[] data; try { data = getData(fileName, location); } catch (IOException ioe) { throw new NoClassDefFoundError("class '" + className + "' could not be loaded from '" + location + "' with message: " + ioe); } return defineClass(className, data, 0, data.length); }
[ "public", "Class", "<", "?", ">", "findClass", "(", "String", "className", ")", "throws", "ClassNotFoundException", "{", "Object", "location", "=", "classResourceLocations", ".", "get", "(", "className", ")", ";", "if", "(", "location", "==", "null", "&&", "this", ".", "propertiesResourceLocations", ".", "containsKey", "(", "className", ")", ")", "{", "String", "fileName", "=", "(", "String", ")", "propertiesResourceLocations", ".", "get", "(", "className", ")", ";", "if", "(", "fileName", ".", "endsWith", "(", "\".properties\"", ")", ")", "{", "//notify invoker that file is present as properties file", "return", "ResourceBundle", ".", "class", ";", "}", "else", "{", "throw", "new", "ClassNotFoundException", "(", "\"resource '\"", "+", "fileName", "+", "\"' for class '\"", "+", "className", "+", "\"' has incompatible format\"", ")", ";", "}", "}", "if", "(", "className", ".", "startsWith", "(", "\"java.\"", ")", ")", "{", "return", "super", ".", "findClass", "(", "className", ")", ";", "}", "if", "(", "location", "==", "null", ")", "{", "throw", "new", "ClassNotFoundException", "(", "\"class '\"", "+", "className", "+", "\"' not found in \"", "+", "classpath", ")", ";", "}", "String", "fileName", "=", "className", ".", "replace", "(", "'", "'", ",", "'", "'", ")", "+", "\".class\"", ";", "byte", "[", "]", "data", ";", "try", "{", "data", "=", "getData", "(", "fileName", ",", "location", ")", ";", "}", "catch", "(", "IOException", "ioe", ")", "{", "throw", "new", "NoClassDefFoundError", "(", "\"class '\"", "+", "className", "+", "\"' could not be loaded from '\"", "+", "location", "+", "\"' with message: \"", "+", "ioe", ")", ";", "}", "return", "defineClass", "(", "className", ",", "data", ",", "0", ",", "data", ".", "length", ")", ";", "}" ]
Tries to locate a class in the specific class path. @param className @return @throws ClassNotFoundException
[ "Tries", "to", "locate", "a", "class", "in", "the", "specific", "class", "path", "." ]
train
https://github.com/jmeetsma/Iglu-Common/blob/0fb0885775b576209ff1b5a0f67e3c25a99a6420/src/main/java/org/ijsberg/iglu/configuration/classloading/ExtendedClassPathClassLoader.java#L317-L343
CenturyLinkCloud/mdw
mdw-common/src/com/centurylink/mdw/util/MDWMessageProducer.java
MDWMessageProducer.sendMessage
public void sendMessage(String requestMessage, String queueName, String correlationId, final Queue replyQueue, int delaySeconds, int deliveryMode) throws JMSException { """ Send a message to a queue with corrId, delay and potential replyQueue @param requestMessage @param queueName @param correlationId @param replyQueue @param delaySeconds @throws JMSException """ /** * If it's an internal message then always use jmsTemplate for ActiveMQ */ if (jmsTemplate != null) { jmsTemplate.setDeliveryMode(deliveryMode); if (!StringUtils.isEmpty(queueName)) { jmsTemplate.send(queueName, new MDWMessageCreator(requestMessage, correlationId, replyQueue, delaySeconds)); } else { jmsTemplate.send(new MDWMessageCreator(requestMessage, correlationId, replyQueue)); } } }
java
public void sendMessage(String requestMessage, String queueName, String correlationId, final Queue replyQueue, int delaySeconds, int deliveryMode) throws JMSException { /** * If it's an internal message then always use jmsTemplate for ActiveMQ */ if (jmsTemplate != null) { jmsTemplate.setDeliveryMode(deliveryMode); if (!StringUtils.isEmpty(queueName)) { jmsTemplate.send(queueName, new MDWMessageCreator(requestMessage, correlationId, replyQueue, delaySeconds)); } else { jmsTemplate.send(new MDWMessageCreator(requestMessage, correlationId, replyQueue)); } } }
[ "public", "void", "sendMessage", "(", "String", "requestMessage", ",", "String", "queueName", ",", "String", "correlationId", ",", "final", "Queue", "replyQueue", ",", "int", "delaySeconds", ",", "int", "deliveryMode", ")", "throws", "JMSException", "{", "/**\n * If it's an internal message then always use jmsTemplate for ActiveMQ\n */", "if", "(", "jmsTemplate", "!=", "null", ")", "{", "jmsTemplate", ".", "setDeliveryMode", "(", "deliveryMode", ")", ";", "if", "(", "!", "StringUtils", ".", "isEmpty", "(", "queueName", ")", ")", "{", "jmsTemplate", ".", "send", "(", "queueName", ",", "new", "MDWMessageCreator", "(", "requestMessage", ",", "correlationId", ",", "replyQueue", ",", "delaySeconds", ")", ")", ";", "}", "else", "{", "jmsTemplate", ".", "send", "(", "new", "MDWMessageCreator", "(", "requestMessage", ",", "correlationId", ",", "replyQueue", ")", ")", ";", "}", "}", "}" ]
Send a message to a queue with corrId, delay and potential replyQueue @param requestMessage @param queueName @param correlationId @param replyQueue @param delaySeconds @throws JMSException
[ "Send", "a", "message", "to", "a", "queue", "with", "corrId", "delay", "and", "potential", "replyQueue" ]
train
https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/util/MDWMessageProducer.java#L49-L66
apache/flink
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/operations/OperationExpressionsUtils.java
OperationExpressionsUtils.extractAggregationsAndProperties
public static CategorizedExpressions extractAggregationsAndProperties( List<Expression> expressions, Supplier<String> uniqueAttributeGenerator) { """ Extracts and deduplicates all aggregation and window property expressions (zero, one, or more) from the given expressions. @param expressions a list of expressions to extract @param uniqueAttributeGenerator a supplier that every time returns a unique attribute @return a Tuple2, the first field contains the extracted and deduplicated aggregations, and the second field contains the extracted and deduplicated window properties. """ AggregationAndPropertiesSplitter splitter = new AggregationAndPropertiesSplitter(uniqueAttributeGenerator); expressions.forEach(expr -> expr.accept(splitter)); List<Expression> projections = expressions.stream() .map(expr -> expr.accept(new AggregationAndPropertiesReplacer(splitter.aggregates, splitter.properties))) .collect(Collectors.toList()); List<Expression> aggregates = nameExpressions(splitter.aggregates); List<Expression> properties = nameExpressions(splitter.properties); return new CategorizedExpressions(projections, aggregates, properties); }
java
public static CategorizedExpressions extractAggregationsAndProperties( List<Expression> expressions, Supplier<String> uniqueAttributeGenerator) { AggregationAndPropertiesSplitter splitter = new AggregationAndPropertiesSplitter(uniqueAttributeGenerator); expressions.forEach(expr -> expr.accept(splitter)); List<Expression> projections = expressions.stream() .map(expr -> expr.accept(new AggregationAndPropertiesReplacer(splitter.aggregates, splitter.properties))) .collect(Collectors.toList()); List<Expression> aggregates = nameExpressions(splitter.aggregates); List<Expression> properties = nameExpressions(splitter.properties); return new CategorizedExpressions(projections, aggregates, properties); }
[ "public", "static", "CategorizedExpressions", "extractAggregationsAndProperties", "(", "List", "<", "Expression", ">", "expressions", ",", "Supplier", "<", "String", ">", "uniqueAttributeGenerator", ")", "{", "AggregationAndPropertiesSplitter", "splitter", "=", "new", "AggregationAndPropertiesSplitter", "(", "uniqueAttributeGenerator", ")", ";", "expressions", ".", "forEach", "(", "expr", "->", "expr", ".", "accept", "(", "splitter", ")", ")", ";", "List", "<", "Expression", ">", "projections", "=", "expressions", ".", "stream", "(", ")", ".", "map", "(", "expr", "->", "expr", ".", "accept", "(", "new", "AggregationAndPropertiesReplacer", "(", "splitter", ".", "aggregates", ",", "splitter", ".", "properties", ")", ")", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ";", "List", "<", "Expression", ">", "aggregates", "=", "nameExpressions", "(", "splitter", ".", "aggregates", ")", ";", "List", "<", "Expression", ">", "properties", "=", "nameExpressions", "(", "splitter", ".", "properties", ")", ";", "return", "new", "CategorizedExpressions", "(", "projections", ",", "aggregates", ",", "properties", ")", ";", "}" ]
Extracts and deduplicates all aggregation and window property expressions (zero, one, or more) from the given expressions. @param expressions a list of expressions to extract @param uniqueAttributeGenerator a supplier that every time returns a unique attribute @return a Tuple2, the first field contains the extracted and deduplicated aggregations, and the second field contains the extracted and deduplicated window properties.
[ "Extracts", "and", "deduplicates", "all", "aggregation", "and", "window", "property", "expressions", "(", "zero", "one", "or", "more", ")", "from", "the", "given", "expressions", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/operations/OperationExpressionsUtils.java#L95-L110
Impetus/Kundera
src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/schemamanager/CassandraSchemaManager.java
CassandraSchemaManager.onValidateColumn
private void onValidateColumn(TableInfo tableInfo, CfDef cfDef, ColumnInfo columnInfo) throws Exception { """ On validate column. @param tableInfo the table info @param cfDef the cf def @param columnInfo the column info @throws Exception the exception """ boolean columnfound = false; boolean isCounterColumnType = isCounterColumnType(tableInfo, null); for (ColumnDef columnDef : cfDef.getColumn_metadata()) { if (isMetadataSame(columnDef, columnInfo, isCql3Enabled(tableInfo), isCounterColumnType)) { columnfound = true; break; } } if (!columnfound) { throw new SchemaGenerationException("Column " + columnInfo.getColumnName() + " does not exist in column family " + tableInfo.getTableName() + "", "Cassandra", databaseName, tableInfo.getTableName()); } }
java
private void onValidateColumn(TableInfo tableInfo, CfDef cfDef, ColumnInfo columnInfo) throws Exception { boolean columnfound = false; boolean isCounterColumnType = isCounterColumnType(tableInfo, null); for (ColumnDef columnDef : cfDef.getColumn_metadata()) { if (isMetadataSame(columnDef, columnInfo, isCql3Enabled(tableInfo), isCounterColumnType)) { columnfound = true; break; } } if (!columnfound) { throw new SchemaGenerationException("Column " + columnInfo.getColumnName() + " does not exist in column family " + tableInfo.getTableName() + "", "Cassandra", databaseName, tableInfo.getTableName()); } }
[ "private", "void", "onValidateColumn", "(", "TableInfo", "tableInfo", ",", "CfDef", "cfDef", ",", "ColumnInfo", "columnInfo", ")", "throws", "Exception", "{", "boolean", "columnfound", "=", "false", ";", "boolean", "isCounterColumnType", "=", "isCounterColumnType", "(", "tableInfo", ",", "null", ")", ";", "for", "(", "ColumnDef", "columnDef", ":", "cfDef", ".", "getColumn_metadata", "(", ")", ")", "{", "if", "(", "isMetadataSame", "(", "columnDef", ",", "columnInfo", ",", "isCql3Enabled", "(", "tableInfo", ")", ",", "isCounterColumnType", ")", ")", "{", "columnfound", "=", "true", ";", "break", ";", "}", "}", "if", "(", "!", "columnfound", ")", "{", "throw", "new", "SchemaGenerationException", "(", "\"Column \"", "+", "columnInfo", ".", "getColumnName", "(", ")", "+", "\" does not exist in column family \"", "+", "tableInfo", ".", "getTableName", "(", ")", "+", "\"\"", ",", "\"Cassandra\"", ",", "databaseName", ",", "tableInfo", ".", "getTableName", "(", ")", ")", ";", "}", "}" ]
On validate column. @param tableInfo the table info @param cfDef the cf def @param columnInfo the column info @throws Exception the exception
[ "On", "validate", "column", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/schemamanager/CassandraSchemaManager.java#L1915-L1935
centic9/commons-dost
src/main/java/org/dstadler/commons/net/UrlUtils.java
UrlUtils.isAvailable
public static boolean isAvailable(String destinationUrl, boolean fireRequest, int timeout) throws IllegalArgumentException { """ Check if the HTTP resource specified by the destination URL is available. @param destinationUrl the destination URL to check for availability @param fireRequest if true a request will be sent to the given URL in addition to opening the connection @param timeout Timeout in milliseconds after which the call fails because of timeout. @return <code>true</code> if a connection could be set up and the response was received @throws IllegalArgumentException if the destination URL is invalid """ return isAvailable(destinationUrl, fireRequest, false, timeout); }
java
public static boolean isAvailable(String destinationUrl, boolean fireRequest, int timeout) throws IllegalArgumentException { return isAvailable(destinationUrl, fireRequest, false, timeout); }
[ "public", "static", "boolean", "isAvailable", "(", "String", "destinationUrl", ",", "boolean", "fireRequest", ",", "int", "timeout", ")", "throws", "IllegalArgumentException", "{", "return", "isAvailable", "(", "destinationUrl", ",", "fireRequest", ",", "false", ",", "timeout", ")", ";", "}" ]
Check if the HTTP resource specified by the destination URL is available. @param destinationUrl the destination URL to check for availability @param fireRequest if true a request will be sent to the given URL in addition to opening the connection @param timeout Timeout in milliseconds after which the call fails because of timeout. @return <code>true</code> if a connection could be set up and the response was received @throws IllegalArgumentException if the destination URL is invalid
[ "Check", "if", "the", "HTTP", "resource", "specified", "by", "the", "destination", "URL", "is", "available", "." ]
train
https://github.com/centic9/commons-dost/blob/f6fa4e3e0b943ff103f918824319d8abf33d0e0f/src/main/java/org/dstadler/commons/net/UrlUtils.java#L324-L326
borball/weixin-sdk
weixin-mp/src/main/java/com/riversoft/weixin/mp/care/Sessions.java
Sessions.create
public void create(String care, String openId, String text) { """ 创建回话 @param care 客服账号 @param openId openid @param text 消息 """ String url = WxEndpoint.get("url.care.session.create"); Map<String, String> request = new HashMap<>(); request.put("kf_account", care); request.put("openid", openId); if(!(text == null || "".equals(text))) { request.put("text", text); } String json = JsonMapper.nonEmptyMapper().toJson(request); logger.debug("create session: {}", json); wxClient.post(url, json); }
java
public void create(String care, String openId, String text) { String url = WxEndpoint.get("url.care.session.create"); Map<String, String> request = new HashMap<>(); request.put("kf_account", care); request.put("openid", openId); if(!(text == null || "".equals(text))) { request.put("text", text); } String json = JsonMapper.nonEmptyMapper().toJson(request); logger.debug("create session: {}", json); wxClient.post(url, json); }
[ "public", "void", "create", "(", "String", "care", ",", "String", "openId", ",", "String", "text", ")", "{", "String", "url", "=", "WxEndpoint", ".", "get", "(", "\"url.care.session.create\"", ")", ";", "Map", "<", "String", ",", "String", ">", "request", "=", "new", "HashMap", "<>", "(", ")", ";", "request", ".", "put", "(", "\"kf_account\"", ",", "care", ")", ";", "request", ".", "put", "(", "\"openid\"", ",", "openId", ")", ";", "if", "(", "!", "(", "text", "==", "null", "||", "\"\"", ".", "equals", "(", "text", ")", ")", ")", "{", "request", ".", "put", "(", "\"text\"", ",", "text", ")", ";", "}", "String", "json", "=", "JsonMapper", ".", "nonEmptyMapper", "(", ")", ".", "toJson", "(", "request", ")", ";", "logger", ".", "debug", "(", "\"create session: {}\"", ",", "json", ")", ";", "wxClient", ".", "post", "(", "url", ",", "json", ")", ";", "}" ]
创建回话 @param care 客服账号 @param openId openid @param text 消息
[ "创建回话" ]
train
https://github.com/borball/weixin-sdk/blob/32bf5e45cdd8d0d28074e83954e1ec62dcf25cb7/weixin-mp/src/main/java/com/riversoft/weixin/mp/care/Sessions.java#L51-L63
linkedin/linkedin-zookeeper
org.linkedin.zookeeper-impl/src/main/java/org/linkedin/zookeeper/client/AbstractZKClient.java
AbstractZKClient.createParents
private void createParents(String path, List<ACL> acl) throws InterruptedException, KeeperException { """ Implementation note: the method adjusts the path and use getZk() directly because in the case where chroot is not null, the chroot path itself may not exist which is why we have to go all the way to the root. """ path = PathUtils.getParentPath(adjustPath(path)); path = PathUtils.removeTrailingSlash(path); List<String> paths = new ArrayList<String>(); while(!path.equals("") && getZk().exists(path, false) == null) { paths.add(path); path = PathUtils.getParentPath(path); path = PathUtils.removeTrailingSlash(path); } Collections.reverse(paths); for(String p : paths) { try { getZk().create(p, null, acl, CreateMode.PERSISTENT); } catch(KeeperException.NodeExistsException e) { // ok we continue... if(log.isDebugEnabled()) log.debug("parent already exists " + p); } } }
java
private void createParents(String path, List<ACL> acl) throws InterruptedException, KeeperException { path = PathUtils.getParentPath(adjustPath(path)); path = PathUtils.removeTrailingSlash(path); List<String> paths = new ArrayList<String>(); while(!path.equals("") && getZk().exists(path, false) == null) { paths.add(path); path = PathUtils.getParentPath(path); path = PathUtils.removeTrailingSlash(path); } Collections.reverse(paths); for(String p : paths) { try { getZk().create(p, null, acl, CreateMode.PERSISTENT); } catch(KeeperException.NodeExistsException e) { // ok we continue... if(log.isDebugEnabled()) log.debug("parent already exists " + p); } } }
[ "private", "void", "createParents", "(", "String", "path", ",", "List", "<", "ACL", ">", "acl", ")", "throws", "InterruptedException", ",", "KeeperException", "{", "path", "=", "PathUtils", ".", "getParentPath", "(", "adjustPath", "(", "path", ")", ")", ";", "path", "=", "PathUtils", ".", "removeTrailingSlash", "(", "path", ")", ";", "List", "<", "String", ">", "paths", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "while", "(", "!", "path", ".", "equals", "(", "\"\"", ")", "&&", "getZk", "(", ")", ".", "exists", "(", "path", ",", "false", ")", "==", "null", ")", "{", "paths", ".", "add", "(", "path", ")", ";", "path", "=", "PathUtils", ".", "getParentPath", "(", "path", ")", ";", "path", "=", "PathUtils", ".", "removeTrailingSlash", "(", "path", ")", ";", "}", "Collections", ".", "reverse", "(", "paths", ")", ";", "for", "(", "String", "p", ":", "paths", ")", "{", "try", "{", "getZk", "(", ")", ".", "create", "(", "p", ",", "null", ",", "acl", ",", "CreateMode", ".", "PERSISTENT", ")", ";", "}", "catch", "(", "KeeperException", ".", "NodeExistsException", "e", ")", "{", "// ok we continue...", "if", "(", "log", ".", "isDebugEnabled", "(", ")", ")", "log", ".", "debug", "(", "\"parent already exists \"", "+", "p", ")", ";", "}", "}", "}" ]
Implementation note: the method adjusts the path and use getZk() directly because in the case where chroot is not null, the chroot path itself may not exist which is why we have to go all the way to the root.
[ "Implementation", "note", ":", "the", "method", "adjusts", "the", "path", "and", "use", "getZk", "()", "directly", "because", "in", "the", "case", "where", "chroot", "is", "not", "null", "the", "chroot", "path", "itself", "may", "not", "exist", "which", "is", "why", "we", "have", "to", "go", "all", "the", "way", "to", "the", "root", "." ]
train
https://github.com/linkedin/linkedin-zookeeper/blob/600b1d01318594ed425ede566bbbdc94b026a53e/org.linkedin.zookeeper-impl/src/main/java/org/linkedin/zookeeper/client/AbstractZKClient.java#L280-L315
VoltDB/voltdb
examples/contentionmark/ContentionMark.java
ContentionMark.runBenchmark
public void runBenchmark() throws Exception { """ Core benchmark code. Connect. Initialize. Run the loop. Cleanup. Print Results. @throws Exception if anything unexpected happens. """ System.out.print(HORIZONTAL_RULE); System.out.println(" Setup & Initialization"); System.out.println(HORIZONTAL_RULE); // connect to one or more servers, loop until success connect(client, config.servers); for (long i = 0; i < config.tuples; i++) { ClientResponse response = client.callProcedure("Init", i, i); if (response.getStatus() != ClientResponse.SUCCESS) { System.exit(-1); } } System.out.print("\n\n" + HORIZONTAL_RULE); System.out.println(" Starting Benchmark"); System.out.println(HORIZONTAL_RULE); System.out.println("\nWarming up..."); final long warmupEndTime = System.currentTimeMillis() + (1000l * config.warmup); while (warmupEndTime > System.currentTimeMillis()) { increment(); } // reset counters before the real benchmark starts post-warmup incrementCount.set(0); lastPeriod.set(0); failureCount.set(0); lastStatsReportTS = System.currentTimeMillis(); // print periodic statistics to the console benchmarkStartTS = System.currentTimeMillis(); TimerTask statsPrinting = new TimerTask() { @Override public void run() { printStatistics(); } }; Timer timer = new Timer(); timer.scheduleAtFixedRate(statsPrinting, config.displayinterval * 1000, config.displayinterval * 1000); // Run the benchmark loop for the requested duration // The throughput may be throttled depending on client configuration System.out.println("\nRunning benchmark..."); final long benchmarkEndTime = System.currentTimeMillis() + (1000l * config.duration); while (benchmarkEndTime > System.currentTimeMillis()) { increment(); } // cancel periodic stats printing timer.cancel(); // block until all outstanding txns return client.drain(); // close down the client connections client.close(); }
java
public void runBenchmark() throws Exception { System.out.print(HORIZONTAL_RULE); System.out.println(" Setup & Initialization"); System.out.println(HORIZONTAL_RULE); // connect to one or more servers, loop until success connect(client, config.servers); for (long i = 0; i < config.tuples; i++) { ClientResponse response = client.callProcedure("Init", i, i); if (response.getStatus() != ClientResponse.SUCCESS) { System.exit(-1); } } System.out.print("\n\n" + HORIZONTAL_RULE); System.out.println(" Starting Benchmark"); System.out.println(HORIZONTAL_RULE); System.out.println("\nWarming up..."); final long warmupEndTime = System.currentTimeMillis() + (1000l * config.warmup); while (warmupEndTime > System.currentTimeMillis()) { increment(); } // reset counters before the real benchmark starts post-warmup incrementCount.set(0); lastPeriod.set(0); failureCount.set(0); lastStatsReportTS = System.currentTimeMillis(); // print periodic statistics to the console benchmarkStartTS = System.currentTimeMillis(); TimerTask statsPrinting = new TimerTask() { @Override public void run() { printStatistics(); } }; Timer timer = new Timer(); timer.scheduleAtFixedRate(statsPrinting, config.displayinterval * 1000, config.displayinterval * 1000); // Run the benchmark loop for the requested duration // The throughput may be throttled depending on client configuration System.out.println("\nRunning benchmark..."); final long benchmarkEndTime = System.currentTimeMillis() + (1000l * config.duration); while (benchmarkEndTime > System.currentTimeMillis()) { increment(); } // cancel periodic stats printing timer.cancel(); // block until all outstanding txns return client.drain(); // close down the client connections client.close(); }
[ "public", "void", "runBenchmark", "(", ")", "throws", "Exception", "{", "System", ".", "out", ".", "print", "(", "HORIZONTAL_RULE", ")", ";", "System", ".", "out", ".", "println", "(", "\" Setup & Initialization\"", ")", ";", "System", ".", "out", ".", "println", "(", "HORIZONTAL_RULE", ")", ";", "// connect to one or more servers, loop until success", "connect", "(", "client", ",", "config", ".", "servers", ")", ";", "for", "(", "long", "i", "=", "0", ";", "i", "<", "config", ".", "tuples", ";", "i", "++", ")", "{", "ClientResponse", "response", "=", "client", ".", "callProcedure", "(", "\"Init\"", ",", "i", ",", "i", ")", ";", "if", "(", "response", ".", "getStatus", "(", ")", "!=", "ClientResponse", ".", "SUCCESS", ")", "{", "System", ".", "exit", "(", "-", "1", ")", ";", "}", "}", "System", ".", "out", ".", "print", "(", "\"\\n\\n\"", "+", "HORIZONTAL_RULE", ")", ";", "System", ".", "out", ".", "println", "(", "\" Starting Benchmark\"", ")", ";", "System", ".", "out", ".", "println", "(", "HORIZONTAL_RULE", ")", ";", "System", ".", "out", ".", "println", "(", "\"\\nWarming up...\"", ")", ";", "final", "long", "warmupEndTime", "=", "System", ".", "currentTimeMillis", "(", ")", "+", "(", "1000l", "*", "config", ".", "warmup", ")", ";", "while", "(", "warmupEndTime", ">", "System", ".", "currentTimeMillis", "(", ")", ")", "{", "increment", "(", ")", ";", "}", "// reset counters before the real benchmark starts post-warmup", "incrementCount", ".", "set", "(", "0", ")", ";", "lastPeriod", ".", "set", "(", "0", ")", ";", "failureCount", ".", "set", "(", "0", ")", ";", "lastStatsReportTS", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "// print periodic statistics to the console", "benchmarkStartTS", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "TimerTask", "statsPrinting", "=", "new", "TimerTask", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "printStatistics", "(", ")", ";", "}", "}", ";", "Timer", "timer", "=", "new", "Timer", "(", ")", ";", "timer", ".", "scheduleAtFixedRate", "(", "statsPrinting", ",", "config", ".", "displayinterval", "*", "1000", ",", "config", ".", "displayinterval", "*", "1000", ")", ";", "// Run the benchmark loop for the requested duration", "// The throughput may be throttled depending on client configuration", "System", ".", "out", ".", "println", "(", "\"\\nRunning benchmark...\"", ")", ";", "final", "long", "benchmarkEndTime", "=", "System", ".", "currentTimeMillis", "(", ")", "+", "(", "1000l", "*", "config", ".", "duration", ")", ";", "while", "(", "benchmarkEndTime", ">", "System", ".", "currentTimeMillis", "(", ")", ")", "{", "increment", "(", ")", ";", "}", "// cancel periodic stats printing", "timer", ".", "cancel", "(", ")", ";", "// block until all outstanding txns return", "client", ".", "drain", "(", ")", ";", "// close down the client connections", "client", ".", "close", "(", ")", ";", "}" ]
Core benchmark code. Connect. Initialize. Run the loop. Cleanup. Print Results. @throws Exception if anything unexpected happens.
[ "Core", "benchmark", "code", ".", "Connect", ".", "Initialize", ".", "Run", "the", "loop", ".", "Cleanup", ".", "Print", "Results", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/examples/contentionmark/ContentionMark.java#L269-L325
classgraph/classgraph
src/main/java/io/github/classgraph/PackageInfo.java
PackageInfo.getChildren
public PackageInfoList getChildren() { """ The child packages of this package, or the empty list if none. @return the child packages, or the empty list if none. """ if (children == null) { return PackageInfoList.EMPTY_LIST; } final PackageInfoList childrenSorted = new PackageInfoList(children); // Ensure children are sorted CollectionUtils.sortIfNotEmpty(childrenSorted, new Comparator<PackageInfo>() { @Override public int compare(final PackageInfo o1, final PackageInfo o2) { return o1.name.compareTo(o2.name); } }); return childrenSorted; }
java
public PackageInfoList getChildren() { if (children == null) { return PackageInfoList.EMPTY_LIST; } final PackageInfoList childrenSorted = new PackageInfoList(children); // Ensure children are sorted CollectionUtils.sortIfNotEmpty(childrenSorted, new Comparator<PackageInfo>() { @Override public int compare(final PackageInfo o1, final PackageInfo o2) { return o1.name.compareTo(o2.name); } }); return childrenSorted; }
[ "public", "PackageInfoList", "getChildren", "(", ")", "{", "if", "(", "children", "==", "null", ")", "{", "return", "PackageInfoList", ".", "EMPTY_LIST", ";", "}", "final", "PackageInfoList", "childrenSorted", "=", "new", "PackageInfoList", "(", "children", ")", ";", "// Ensure children are sorted", "CollectionUtils", ".", "sortIfNotEmpty", "(", "childrenSorted", ",", "new", "Comparator", "<", "PackageInfo", ">", "(", ")", "{", "@", "Override", "public", "int", "compare", "(", "final", "PackageInfo", "o1", ",", "final", "PackageInfo", "o2", ")", "{", "return", "o1", ".", "name", ".", "compareTo", "(", "o2", ".", "name", ")", ";", "}", "}", ")", ";", "return", "childrenSorted", ";", "}" ]
The child packages of this package, or the empty list if none. @return the child packages, or the empty list if none.
[ "The", "child", "packages", "of", "this", "package", "or", "the", "empty", "list", "if", "none", "." ]
train
https://github.com/classgraph/classgraph/blob/c8c8b2ca1eb76339f69193fdac33d735c864215c/src/main/java/io/github/classgraph/PackageInfo.java#L166-L179
micronaut-projects/micronaut-core
inject/src/main/java/io/micronaut/context/AbstractBeanDefinition.java
AbstractBeanDefinition.injectAnother
@Internal @SuppressWarnings( { """ Inject another bean, for example one created via factory. @param resolutionContext The reslution context @param context The context @param bean The bean @return The bean """"WeakerAccess", "unused"}) @UsedByGeneratedCode protected Object injectAnother(BeanResolutionContext resolutionContext, BeanContext context, Object bean) { DefaultBeanContext defaultContext = (DefaultBeanContext) context; if (bean == null) { throw new BeanInstantiationException(resolutionContext, "Bean factory returned null"); } return defaultContext.inject(resolutionContext, this, bean); }
java
@Internal @SuppressWarnings({"WeakerAccess", "unused"}) @UsedByGeneratedCode protected Object injectAnother(BeanResolutionContext resolutionContext, BeanContext context, Object bean) { DefaultBeanContext defaultContext = (DefaultBeanContext) context; if (bean == null) { throw new BeanInstantiationException(resolutionContext, "Bean factory returned null"); } return defaultContext.inject(resolutionContext, this, bean); }
[ "@", "Internal", "@", "SuppressWarnings", "(", "{", "\"WeakerAccess\"", ",", "\"unused\"", "}", ")", "@", "UsedByGeneratedCode", "protected", "Object", "injectAnother", "(", "BeanResolutionContext", "resolutionContext", ",", "BeanContext", "context", ",", "Object", "bean", ")", "{", "DefaultBeanContext", "defaultContext", "=", "(", "DefaultBeanContext", ")", "context", ";", "if", "(", "bean", "==", "null", ")", "{", "throw", "new", "BeanInstantiationException", "(", "resolutionContext", ",", "\"Bean factory returned null\"", ")", ";", "}", "return", "defaultContext", ".", "inject", "(", "resolutionContext", ",", "this", ",", "bean", ")", ";", "}" ]
Inject another bean, for example one created via factory. @param resolutionContext The reslution context @param context The context @param bean The bean @return The bean
[ "Inject", "another", "bean", "for", "example", "one", "created", "via", "factory", "." ]
train
https://github.com/micronaut-projects/micronaut-core/blob/c31f5b03ce0eb88c2f6470710987db03b8967d5c/inject/src/main/java/io/micronaut/context/AbstractBeanDefinition.java#L597-L606
hypercube1024/firefly
firefly-common/src/main/java/com/firefly/utils/lang/AtomicBiInteger.java
AtomicBiInteger.encodeLo
public static long encodeLo(long encoded, int lo) { """ Sets the lo value into the given encoded value. @param encoded the encoded value @param lo the lo value @return the new encoded value """ long h = (encoded >> 32) & 0xFFFF_FFFFL; long l = ((long) lo) & 0xFFFF_FFFFL; return (h << 32) + l; }
java
public static long encodeLo(long encoded, int lo) { long h = (encoded >> 32) & 0xFFFF_FFFFL; long l = ((long) lo) & 0xFFFF_FFFFL; return (h << 32) + l; }
[ "public", "static", "long", "encodeLo", "(", "long", "encoded", ",", "int", "lo", ")", "{", "long", "h", "=", "(", "encoded", ">>", "32", ")", "&", "0xFFFF_FFFF", "", "L", ";", "long", "l", "=", "(", "(", "long", ")", "lo", ")", "&", "0xFFFF_FFFF", "", "L", ";", "return", "(", "h", "<<", "32", ")", "+", "l", ";", "}" ]
Sets the lo value into the given encoded value. @param encoded the encoded value @param lo the lo value @return the new encoded value
[ "Sets", "the", "lo", "value", "into", "the", "given", "encoded", "value", "." ]
train
https://github.com/hypercube1024/firefly/blob/ed3fc75b7c54a65b1e7d8141d01b49144bb423a3/firefly-common/src/main/java/com/firefly/utils/lang/AtomicBiInteger.java#L237-L241
wisdom-framework/wisdom
core/application-configuration/src/main/java/org/wisdom/configuration/ConfigurationImpl.java
ConfigurationImpl.getIntegerOrDie
@Override public Integer getIntegerOrDie(String key) { """ The "die" method forces this key to be set. Otherwise a runtime exception will be thrown. @param key the key @return the Integer or a IllegalArgumentException will be thrown. """ Integer value = getInteger(key); if (value == null) { throw new IllegalArgumentException(String.format(ERROR_KEYNOTFOUND, key)); } else { return value; } }
java
@Override public Integer getIntegerOrDie(String key) { Integer value = getInteger(key); if (value == null) { throw new IllegalArgumentException(String.format(ERROR_KEYNOTFOUND, key)); } else { return value; } }
[ "@", "Override", "public", "Integer", "getIntegerOrDie", "(", "String", "key", ")", "{", "Integer", "value", "=", "getInteger", "(", "key", ")", ";", "if", "(", "value", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "String", ".", "format", "(", "ERROR_KEYNOTFOUND", ",", "key", ")", ")", ";", "}", "else", "{", "return", "value", ";", "}", "}" ]
The "die" method forces this key to be set. Otherwise a runtime exception will be thrown. @param key the key @return the Integer or a IllegalArgumentException will be thrown.
[ "The", "die", "method", "forces", "this", "key", "to", "be", "set", ".", "Otherwise", "a", "runtime", "exception", "will", "be", "thrown", "." ]
train
https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/core/application-configuration/src/main/java/org/wisdom/configuration/ConfigurationImpl.java#L293-L301
GenesysPureEngage/authentication-client-java
src/main/java/com/genesys/authentication/AuthenticationApi.java
AuthenticationApi.signIn
public void signIn(Map<String, Object> formParams) throws AuthenticationApiException { """ Perform form-based authentication. Perform form-based authentication by submitting an agent&#39;s username and password. @param formParams The form parameters, can be created via static methods @throws AuthenticationApiException if the call is unsuccessful. """ Headers.Builder headerBuilder = new Headers.Builder(); headerBuilder.add("Accept", "*/*"); headerBuilder.add("Content-Type", "application/x-www-form-urlencoded"); Request request = new Request.Builder() .url(client.getBasePath() + "/sign-in") .headers(headerBuilder.build()) .post(client.buildRequestBodyFormEncoding(formParams)) .build(); try { this.client.getHttpClient().newCall(request).execute(); } catch (IOException e) { throw new AuthenticationApiException("Authorization error", e); } }
java
public void signIn(Map<String, Object> formParams) throws AuthenticationApiException { Headers.Builder headerBuilder = new Headers.Builder(); headerBuilder.add("Accept", "*/*"); headerBuilder.add("Content-Type", "application/x-www-form-urlencoded"); Request request = new Request.Builder() .url(client.getBasePath() + "/sign-in") .headers(headerBuilder.build()) .post(client.buildRequestBodyFormEncoding(formParams)) .build(); try { this.client.getHttpClient().newCall(request).execute(); } catch (IOException e) { throw new AuthenticationApiException("Authorization error", e); } }
[ "public", "void", "signIn", "(", "Map", "<", "String", ",", "Object", ">", "formParams", ")", "throws", "AuthenticationApiException", "{", "Headers", ".", "Builder", "headerBuilder", "=", "new", "Headers", ".", "Builder", "(", ")", ";", "headerBuilder", ".", "add", "(", "\"Accept\"", ",", "\"*/*\"", ")", ";", "headerBuilder", ".", "add", "(", "\"Content-Type\"", ",", "\"application/x-www-form-urlencoded\"", ")", ";", "Request", "request", "=", "new", "Request", ".", "Builder", "(", ")", ".", "url", "(", "client", ".", "getBasePath", "(", ")", "+", "\"/sign-in\"", ")", ".", "headers", "(", "headerBuilder", ".", "build", "(", ")", ")", ".", "post", "(", "client", ".", "buildRequestBodyFormEncoding", "(", "formParams", ")", ")", ".", "build", "(", ")", ";", "try", "{", "this", ".", "client", ".", "getHttpClient", "(", ")", ".", "newCall", "(", "request", ")", ".", "execute", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "AuthenticationApiException", "(", "\"Authorization error\"", ",", "e", ")", ";", "}", "}" ]
Perform form-based authentication. Perform form-based authentication by submitting an agent&#39;s username and password. @param formParams The form parameters, can be created via static methods @throws AuthenticationApiException if the call is unsuccessful.
[ "Perform", "form", "-", "based", "authentication", ".", "Perform", "form", "-", "based", "authentication", "by", "submitting", "an", "agent&#39", ";", "s", "username", "and", "password", "." ]
train
https://github.com/GenesysPureEngage/authentication-client-java/blob/eb0d58343ee42ebd3c037163c1137f611dfcbb3a/src/main/java/com/genesys/authentication/AuthenticationApi.java#L227-L242
apache/groovy
subprojects/groovy-nio/src/main/java/org/codehaus/groovy/runtime/NioGroovyMethods.java
NioGroovyMethods.withWriterAppend
public static <T> T withWriterAppend(Path self, @ClosureParams(value = SimpleType.class, options = "java.io.Writer") Closure<T> closure) throws IOException { """ Create a new BufferedWriter for this file in append mode. The writer is passed to the closure and is closed after the closure returns. The writer will not write a BOM. @param self a Path @param closure a closure @return the value returned by the closure @throws java.io.IOException if an IOException occurs. @since 2.3.0 """ return withWriterAppend(self, Charset.defaultCharset().name(), closure); }
java
public static <T> T withWriterAppend(Path self, @ClosureParams(value = SimpleType.class, options = "java.io.Writer") Closure<T> closure) throws IOException { return withWriterAppend(self, Charset.defaultCharset().name(), closure); }
[ "public", "static", "<", "T", ">", "T", "withWriterAppend", "(", "Path", "self", ",", "@", "ClosureParams", "(", "value", "=", "SimpleType", ".", "class", ",", "options", "=", "\"java.io.Writer\"", ")", "Closure", "<", "T", ">", "closure", ")", "throws", "IOException", "{", "return", "withWriterAppend", "(", "self", ",", "Charset", ".", "defaultCharset", "(", ")", ".", "name", "(", ")", ",", "closure", ")", ";", "}" ]
Create a new BufferedWriter for this file in append mode. The writer is passed to the closure and is closed after the closure returns. The writer will not write a BOM. @param self a Path @param closure a closure @return the value returned by the closure @throws java.io.IOException if an IOException occurs. @since 2.3.0
[ "Create", "a", "new", "BufferedWriter", "for", "this", "file", "in", "append", "mode", ".", "The", "writer", "is", "passed", "to", "the", "closure", "and", "is", "closed", "after", "the", "closure", "returns", ".", "The", "writer", "will", "not", "write", "a", "BOM", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-nio/src/main/java/org/codehaus/groovy/runtime/NioGroovyMethods.java#L1721-L1723