repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
18
201
func_name
stringlengths
4
126
whole_func_string
stringlengths
75
3.57k
language
stringclasses
1 value
func_code_string
stringlengths
75
3.57k
func_code_tokens
listlengths
21
599
func_documentation_string
stringlengths
61
1.95k
func_documentation_tokens
listlengths
1
478
split_name
stringclasses
1 value
func_code_url
stringlengths
111
308
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/util/AuthConfigFactory.java
AuthConfigFactory.parseOpenShiftConfig
private AuthConfig parseOpenShiftConfig() { Map kubeConfig = DockerFileUtil.readKubeConfig(); if (kubeConfig == null) { return null; } String currentContextName = (String) kubeConfig.get("current-context"); if (currentContextName == null) { return null; } for (Map contextMap : (List<Map>) kubeConfig.get("contexts")) { if (currentContextName.equals(contextMap.get("name"))) { return parseContext(kubeConfig, (Map) contextMap.get("context")); } } return null; }
java
private AuthConfig parseOpenShiftConfig() { Map kubeConfig = DockerFileUtil.readKubeConfig(); if (kubeConfig == null) { return null; } String currentContextName = (String) kubeConfig.get("current-context"); if (currentContextName == null) { return null; } for (Map contextMap : (List<Map>) kubeConfig.get("contexts")) { if (currentContextName.equals(contextMap.get("name"))) { return parseContext(kubeConfig, (Map) contextMap.get("context")); } } return null; }
[ "private", "AuthConfig", "parseOpenShiftConfig", "(", ")", "{", "Map", "kubeConfig", "=", "DockerFileUtil", ".", "readKubeConfig", "(", ")", ";", "if", "(", "kubeConfig", "==", "null", ")", "{", "return", "null", ";", "}", "String", "currentContextName", "=", ...
Parse OpenShift config to get credentials, but return null if not found
[ "Parse", "OpenShift", "config", "to", "get", "credentials", "but", "return", "null", "if", "not", "found" ]
train
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/util/AuthConfigFactory.java#L458-L476
Azure/azure-sdk-for-java
kusto/resource-manager/v2018_09_07_preview/src/main/java/com/microsoft/azure/management/kusto/v2018_09_07_preview/implementation/ClustersInner.java
ClustersInner.createOrUpdate
public ClusterInner createOrUpdate(String resourceGroupName, String clusterName, ClusterInner parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, clusterName, parameters).toBlocking().last().body(); }
java
public ClusterInner createOrUpdate(String resourceGroupName, String clusterName, ClusterInner parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, clusterName, parameters).toBlocking().last().body(); }
[ "public", "ClusterInner", "createOrUpdate", "(", "String", "resourceGroupName", ",", "String", "clusterName", ",", "ClusterInner", "parameters", ")", "{", "return", "createOrUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "clusterName", ",", "parameters", ...
Create or update a Kusto cluster. @param resourceGroupName The name of the resource group containing the Kusto cluster. @param clusterName The name of the Kusto cluster. @param parameters The Kusto cluster parameters supplied to the CreateOrUpdate operation. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the ClusterInner object if successful.
[ "Create", "or", "update", "a", "Kusto", "cluster", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/kusto/resource-manager/v2018_09_07_preview/src/main/java/com/microsoft/azure/management/kusto/v2018_09_07_preview/implementation/ClustersInner.java#L231-L233
alipay/sofa-rpc
core-impl/client/src/main/java/com/alipay/sofa/rpc/client/AllConnectConnectionHolder.java
AllConnectConnectionHolder.aliveToRetry
protected void aliveToRetry(ProviderInfo providerInfo, ClientTransport transport) { providerLock.lock(); try { if (aliveConnections.remove(providerInfo) != null) { retryConnections.put(providerInfo, transport); } } finally { providerLock.unlock(); } }
java
protected void aliveToRetry(ProviderInfo providerInfo, ClientTransport transport) { providerLock.lock(); try { if (aliveConnections.remove(providerInfo) != null) { retryConnections.put(providerInfo, transport); } } finally { providerLock.unlock(); } }
[ "protected", "void", "aliveToRetry", "(", "ProviderInfo", "providerInfo", ",", "ClientTransport", "transport", ")", "{", "providerLock", ".", "lock", "(", ")", ";", "try", "{", "if", "(", "aliveConnections", ".", "remove", "(", "providerInfo", ")", "!=", "null...
从存活丢到重试列表 @param providerInfo Provider @param transport 连接
[ "从存活丢到重试列表" ]
train
https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/core-impl/client/src/main/java/com/alipay/sofa/rpc/client/AllConnectConnectionHolder.java#L145-L154
GenesysPureEngage/provisioning-client-java
src/main/java/com/genesys/internal/provisioning/api/OperationsApi.java
OperationsApi.getUsersAsyncAsync
public com.squareup.okhttp.Call getUsersAsyncAsync(String aioId, Integer limit, Integer offset, String order, String sortBy, String filterName, String filterParameters, String roles, String skills, Boolean userEnabled, String userValid, final ApiCallback<ApiAsyncSuccessResponse> 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 = getUsersAsyncValidateBeforeCall(aioId, limit, offset, order, sortBy, filterName, filterParameters, roles, skills, userEnabled, userValid, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<ApiAsyncSuccessResponse>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; }
java
public com.squareup.okhttp.Call getUsersAsyncAsync(String aioId, Integer limit, Integer offset, String order, String sortBy, String filterName, String filterParameters, String roles, String skills, Boolean userEnabled, String userValid, final ApiCallback<ApiAsyncSuccessResponse> 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 = getUsersAsyncValidateBeforeCall(aioId, limit, offset, order, sortBy, filterName, filterParameters, roles, skills, userEnabled, userValid, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<ApiAsyncSuccessResponse>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; }
[ "public", "com", ".", "squareup", ".", "okhttp", ".", "Call", "getUsersAsyncAsync", "(", "String", "aioId", ",", "Integer", "limit", ",", "Integer", "offset", ",", "String", "order", ",", "String", "sortBy", ",", "String", "filterName", ",", "String", "filte...
Get users. (asynchronously) Get [CfgPerson](https://docs.genesys.com/Documentation/PSDK/latest/ConfigLayerRef/CfgPerson) objects based on the specified filters. @param aioId A unique ID generated on the client (browser) when sending an API request that returns an asynchronous response. (required) @param limit Limit the number of users the Provisioning API should return. (optional) @param offset The number of matches the Provisioning API should skip in the returned users. (optional) @param order The sort order. (optional) @param sortBy A comma-separated list of fields to sort on. Possible values are firstName, lastName, and userName. (optional) @param filterName The name of a filter to use on the results. (optional) @param filterParameters A part of the users first or last name, if you use the FirstNameOrLastNameMatches filter. (optional) @param roles Return only return users who have these Workspace Web Edition roles. The roles can be specified in a comma-separated list. Possible values are ROLE_AGENT and ROLE_ADMIN,ROLE_SUPERVISOR. (optional) @param skills Return only users who have these skills. The skills can be specified in a comma-separated list. (optional) @param userEnabled Return only enabled or disabled users. (optional) @param userValid Return only valid or invalid users. (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
[ "Get", "users", ".", "(", "asynchronously", ")", "Get", "[", "CfgPerson", "]", "(", "https", ":", "//", "docs", ".", "genesys", ".", "com", "/", "Documentation", "/", "PSDK", "/", "latest", "/", "ConfigLayerRef", "/", "CfgPerson", ")", "objects", "based"...
train
https://github.com/GenesysPureEngage/provisioning-client-java/blob/1ad594c3767cec83052168e350994f922a26f75e/src/main/java/com/genesys/internal/provisioning/api/OperationsApi.java#L697-L722
spring-cloud/spring-cloud-contract
spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/assertion/CollectionAssert.java
CollectionAssert.hasSizeBetween
public CollectionAssert hasSizeBetween(int lowerBound, int higherBound) { isNotNull(); int size = size(this.actual); if (!(size >= lowerBound && size <= higherBound)) { failWithMessage("The size <%s> is not between <%s> and <%s>", size, lowerBound, higherBound); } return this; }
java
public CollectionAssert hasSizeBetween(int lowerBound, int higherBound) { isNotNull(); int size = size(this.actual); if (!(size >= lowerBound && size <= higherBound)) { failWithMessage("The size <%s> is not between <%s> and <%s>", size, lowerBound, higherBound); } return this; }
[ "public", "CollectionAssert", "hasSizeBetween", "(", "int", "lowerBound", ",", "int", "higherBound", ")", "{", "isNotNull", "(", ")", ";", "int", "size", "=", "size", "(", "this", ".", "actual", ")", ";", "if", "(", "!", "(", "size", ">=", "lowerBound", ...
Checks whether size is between the provided value. @param lowerBound - the collection should have size greater than or equal to this value @param higherBound - the collection should have size less than or equal to this value @return this
[ "Checks", "whether", "size", "is", "between", "the", "provided", "value", "." ]
train
https://github.com/spring-cloud/spring-cloud-contract/blob/857da51950a87b393286e3bb1b2208c420c01087/spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/assertion/CollectionAssert.java#L163-L171
biojava/biojava
biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/LocIterator.java
LocIterator.hasNext
public boolean hasNext( int windowSize, int increment ) { if( windowSize <= 0 ) { throw new IllegalArgumentException( "Window size must be positive." ); } try { if( increment > 0 ) { return windowSize == mBounds.suffix( mPosition ).prefix( windowSize ).length(); } else { if( mPosition == 0 ) { return windowSize == mBounds.suffix( - windowSize ).length(); } else { return windowSize == mBounds.prefix( mPosition ).suffix( - windowSize ).length(); } } } catch( Exception e ) { return false; } }
java
public boolean hasNext( int windowSize, int increment ) { if( windowSize <= 0 ) { throw new IllegalArgumentException( "Window size must be positive." ); } try { if( increment > 0 ) { return windowSize == mBounds.suffix( mPosition ).prefix( windowSize ).length(); } else { if( mPosition == 0 ) { return windowSize == mBounds.suffix( - windowSize ).length(); } else { return windowSize == mBounds.prefix( mPosition ).suffix( - windowSize ).length(); } } } catch( Exception e ) { return false; } }
[ "public", "boolean", "hasNext", "(", "int", "windowSize", ",", "int", "increment", ")", "{", "if", "(", "windowSize", "<=", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Window size must be positive.\"", ")", ";", "}", "try", "{", "if", ...
Check if next window of specified size is available. @param windowSize Size of window. May be smaller or larger than default window size. @param increment The increment by which to move the window at each iteration. Note that this method does not actually change the position. However, it checks the sign of the increment parameter to determine the direction of the iteration. @return True if window of specified size is available. @throws IllegalArgumentException Window size parameter was not positive.
[ "Check", "if", "next", "window", "of", "specified", "size", "is", "available", "." ]
train
https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/LocIterator.java#L91-L120
apache/flink
flink-streaming-java/src/main/java/org/apache/flink/streaming/api/graph/StreamGraphGenerator.java
StreamGraphGenerator.determineSlotSharingGroup
private String determineSlotSharingGroup(String specifiedGroup, Collection<Integer> inputIds) { if (specifiedGroup != null) { return specifiedGroup; } else { String inputGroup = null; for (int id: inputIds) { String inputGroupCandidate = streamGraph.getSlotSharingGroup(id); if (inputGroup == null) { inputGroup = inputGroupCandidate; } else if (!inputGroup.equals(inputGroupCandidate)) { return "default"; } } return inputGroup == null ? "default" : inputGroup; } }
java
private String determineSlotSharingGroup(String specifiedGroup, Collection<Integer> inputIds) { if (specifiedGroup != null) { return specifiedGroup; } else { String inputGroup = null; for (int id: inputIds) { String inputGroupCandidate = streamGraph.getSlotSharingGroup(id); if (inputGroup == null) { inputGroup = inputGroupCandidate; } else if (!inputGroup.equals(inputGroupCandidate)) { return "default"; } } return inputGroup == null ? "default" : inputGroup; } }
[ "private", "String", "determineSlotSharingGroup", "(", "String", "specifiedGroup", ",", "Collection", "<", "Integer", ">", "inputIds", ")", "{", "if", "(", "specifiedGroup", "!=", "null", ")", "{", "return", "specifiedGroup", ";", "}", "else", "{", "String", "...
Determines the slot sharing group for an operation based on the slot sharing group set by the user and the slot sharing groups of the inputs. <p>If the user specifies a group name, this is taken as is. If nothing is specified and the input operations all have the same group name then this name is taken. Otherwise the default group is chosen. @param specifiedGroup The group specified by the user. @param inputIds The IDs of the input operations.
[ "Determines", "the", "slot", "sharing", "group", "for", "an", "operation", "based", "on", "the", "slot", "sharing", "group", "set", "by", "the", "user", "and", "the", "slot", "sharing", "groups", "of", "the", "inputs", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/graph/StreamGraphGenerator.java#L639-L654
cdk/cdk
app/depict/src/main/java/org/openscience/cdk/depict/DepictionGenerator.java
DepictionGenerator.generateTitle
private Bounds generateTitle(IChemObject chemObj, double scale) { String title = chemObj.getProperty(CDKConstants.TITLE); if (title == null || title.isEmpty()) return new Bounds(); scale = 1 / scale * getParameterValue(RendererModel.TitleFontScale.class); return new Bounds(MarkedElement.markup(StandardGenerator.embedText(font, title, getParameterValue(RendererModel.TitleColor.class), scale), "title")); }
java
private Bounds generateTitle(IChemObject chemObj, double scale) { String title = chemObj.getProperty(CDKConstants.TITLE); if (title == null || title.isEmpty()) return new Bounds(); scale = 1 / scale * getParameterValue(RendererModel.TitleFontScale.class); return new Bounds(MarkedElement.markup(StandardGenerator.embedText(font, title, getParameterValue(RendererModel.TitleColor.class), scale), "title")); }
[ "private", "Bounds", "generateTitle", "(", "IChemObject", "chemObj", ",", "double", "scale", ")", "{", "String", "title", "=", "chemObj", ".", "getProperty", "(", "CDKConstants", ".", "TITLE", ")", ";", "if", "(", "title", "==", "null", "||", "title", ".",...
Generate a bound element that is the title of the provided molecule. If title is not specified an empty bounds is returned. @param chemObj molecule or reaction @return bound element
[ "Generate", "a", "bound", "element", "that", "is", "the", "title", "of", "the", "provided", "molecule", ".", "If", "title", "is", "not", "specified", "an", "empty", "bounds", "is", "returned", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/app/depict/src/main/java/org/openscience/cdk/depict/DepictionGenerator.java#L643-L650
DataSketches/sketches-core
src/main/java/com/yahoo/sketches/theta/UpdateSketch.java
UpdateSketch.heapify
public static UpdateSketch heapify(final Memory srcMem, final long seed) { final Family family = Family.idToFamily(srcMem.getByte(FAMILY_BYTE)); if (family.equals(Family.ALPHA)) { return HeapAlphaSketch.heapifyInstance(srcMem, seed); } return HeapQuickSelectSketch.heapifyInstance(srcMem, seed); }
java
public static UpdateSketch heapify(final Memory srcMem, final long seed) { final Family family = Family.idToFamily(srcMem.getByte(FAMILY_BYTE)); if (family.equals(Family.ALPHA)) { return HeapAlphaSketch.heapifyInstance(srcMem, seed); } return HeapQuickSelectSketch.heapifyInstance(srcMem, seed); }
[ "public", "static", "UpdateSketch", "heapify", "(", "final", "Memory", "srcMem", ",", "final", "long", "seed", ")", "{", "final", "Family", "family", "=", "Family", ".", "idToFamily", "(", "srcMem", ".", "getByte", "(", "FAMILY_BYTE", ")", ")", ";", "if", ...
Instantiates an on-heap UpdateSketch from Memory. @param srcMem <a href="{@docRoot}/resources/dictionary.html#mem">See Memory</a> @param seed <a href="{@docRoot}/resources/dictionary.html#seed">See Update Hash Seed</a>. @return an UpdateSketch
[ "Instantiates", "an", "on", "-", "heap", "UpdateSketch", "from", "Memory", "." ]
train
https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/theta/UpdateSketch.java#L107-L113
orbisgis/h2gis
h2gis-functions/src/main/java/org/h2gis/functions/io/tsv/TSVDriverFunction.java
TSVDriverFunction.exportTable
@Override public void exportTable(Connection connection, String tableReference, File fileName, ProgressVisitor progress, String encoding) throws SQLException, IOException { String regex = ".*(?i)\\b(select|from)\\b.*"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(tableReference); if (matcher.find()) { if (tableReference.startsWith("(") && tableReference.endsWith(")")) { if (FileUtil.isExtensionWellFormated(fileName, "tsv")) { try (Statement st = connection.createStatement()) { JDBCUtilities.attachCancelResultSet(st, progress); exportFromResultSet(connection, st.executeQuery(tableReference), fileName, new EmptyProgressVisitor(), encoding); } } else { throw new SQLException("Only .tsv extension is supported"); } } else { throw new SQLException("The select query must be enclosed in parenthesis: '(SELECT * FROM ORDERS)'."); } } else { if (FileUtil.isExtensionWellFormated(fileName, "tsv")) { final boolean isH2 = JDBCUtilities.isH2DataBase(connection.getMetaData()); TableLocation location = TableLocation.parse(tableReference, isH2); try (Statement st = connection.createStatement()) { JDBCUtilities.attachCancelResultSet(st, progress); exportFromResultSet(connection, st.executeQuery("SELECT * FROM " + location.toString()), fileName,new EmptyProgressVisitor(),encoding); } } else { throw new SQLException("Only .tsv extension is supported"); } } }
java
@Override public void exportTable(Connection connection, String tableReference, File fileName, ProgressVisitor progress, String encoding) throws SQLException, IOException { String regex = ".*(?i)\\b(select|from)\\b.*"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(tableReference); if (matcher.find()) { if (tableReference.startsWith("(") && tableReference.endsWith(")")) { if (FileUtil.isExtensionWellFormated(fileName, "tsv")) { try (Statement st = connection.createStatement()) { JDBCUtilities.attachCancelResultSet(st, progress); exportFromResultSet(connection, st.executeQuery(tableReference), fileName, new EmptyProgressVisitor(), encoding); } } else { throw new SQLException("Only .tsv extension is supported"); } } else { throw new SQLException("The select query must be enclosed in parenthesis: '(SELECT * FROM ORDERS)'."); } } else { if (FileUtil.isExtensionWellFormated(fileName, "tsv")) { final boolean isH2 = JDBCUtilities.isH2DataBase(connection.getMetaData()); TableLocation location = TableLocation.parse(tableReference, isH2); try (Statement st = connection.createStatement()) { JDBCUtilities.attachCancelResultSet(st, progress); exportFromResultSet(connection, st.executeQuery("SELECT * FROM " + location.toString()), fileName,new EmptyProgressVisitor(),encoding); } } else { throw new SQLException("Only .tsv extension is supported"); } } }
[ "@", "Override", "public", "void", "exportTable", "(", "Connection", "connection", ",", "String", "tableReference", ",", "File", "fileName", ",", "ProgressVisitor", "progress", ",", "String", "encoding", ")", "throws", "SQLException", ",", "IOException", "{", "Str...
Export a table or a query to as TSV file @param connection Active connection, do not close this connection. @param tableReference [[catalog.]schema.]table reference @param fileName File path to read @param progress @param encoding @throws SQLException @throws IOException
[ "Export", "a", "table", "or", "a", "query", "to", "as", "TSV", "file" ]
train
https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/io/tsv/TSVDriverFunction.java#L109-L140
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/utilities/ImageIOGreyScale.java
ImageIOGreyScale.getImageWritersByFormatName
public static Iterator<ImageWriter> getImageWritersByFormatName(String formatName) { if (formatName == null) { throw new IllegalArgumentException("formatName == null!"); } Iterator iter; // Ensure category is present try { iter = theRegistry.getServiceProviders(ImageWriterSpi.class, new ContainsFilter(writerFormatNamesMethod, formatName), true); } catch (IllegalArgumentException e) { return new HashSet().iterator(); } return new ImageWriterIterator(iter); }
java
public static Iterator<ImageWriter> getImageWritersByFormatName(String formatName) { if (formatName == null) { throw new IllegalArgumentException("formatName == null!"); } Iterator iter; // Ensure category is present try { iter = theRegistry.getServiceProviders(ImageWriterSpi.class, new ContainsFilter(writerFormatNamesMethod, formatName), true); } catch (IllegalArgumentException e) { return new HashSet().iterator(); } return new ImageWriterIterator(iter); }
[ "public", "static", "Iterator", "<", "ImageWriter", ">", "getImageWritersByFormatName", "(", "String", "formatName", ")", "{", "if", "(", "formatName", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"formatName == null!\"", ")", ";", "}...
Returns an <code>Iterator</code> containing all currently registered <code>ImageWriter</code>s that claim to be able to encode the named format. @param formatName a <code>String</code> containing the informal name of a format (<i>e.g.</i>, "jpeg" or "tiff". @return an <code>Iterator</code> containing <code>ImageWriter</code>s. @exception IllegalArgumentException if <code>formatName</code> is <code>null</code>. @see javax.imageio.spi.ImageWriterSpi#getFormatNames
[ "Returns", "an", "<code", ">", "Iterator<", "/", "code", ">", "containing", "all", "currently", "registered", "<code", ">", "ImageWriter<", "/", "code", ">", "s", "that", "claim", "to", "be", "able", "to", "encode", "the", "named", "format", "." ]
train
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/utilities/ImageIOGreyScale.java#L781-L793
cdk/cdk
tool/formula/src/main/java/org/openscience/cdk/tools/manipulator/MolecularFormulaManipulator.java
MolecularFormulaManipulator.getMajorIsotopeMolecularFormula
public static IMolecularFormula getMajorIsotopeMolecularFormula(String stringMF, IChemObjectBuilder builder) { return getMolecularFormula(stringMF, true, builder); }
java
public static IMolecularFormula getMajorIsotopeMolecularFormula(String stringMF, IChemObjectBuilder builder) { return getMolecularFormula(stringMF, true, builder); }
[ "public", "static", "IMolecularFormula", "getMajorIsotopeMolecularFormula", "(", "String", "stringMF", ",", "IChemObjectBuilder", "builder", ")", "{", "return", "getMolecularFormula", "(", "stringMF", ",", "true", ",", "builder", ")", ";", "}" ]
Construct an instance of IMolecularFormula, initialized with a molecular formula string. The string is immediately analyzed and a set of Nodes is built based on this analysis. The hydrogens must be implicit. Major isotopes are being used. @param stringMF The molecularFormula string @param builder a IChemObjectBuilder which is used to construct atoms @return The filled IMolecularFormula @see #getMolecularFormula(String,IMolecularFormula)
[ "Construct", "an", "instance", "of", "IMolecularFormula", "initialized", "with", "a", "molecular", "formula", "string", ".", "The", "string", "is", "immediately", "analyzed", "and", "a", "set", "of", "Nodes", "is", "built", "based", "on", "this", "analysis", "...
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/tool/formula/src/main/java/org/openscience/cdk/tools/manipulator/MolecularFormulaManipulator.java#L591-L593
offbynull/coroutines
instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/generators/GenericGenerators.java
GenericGenerators.jumpTo
public static InsnList jumpTo(LabelNode labelNode) { Validate.notNull(labelNode); InsnList ret = new InsnList(); ret.add(new JumpInsnNode(Opcodes.GOTO, labelNode)); return ret; }
java
public static InsnList jumpTo(LabelNode labelNode) { Validate.notNull(labelNode); InsnList ret = new InsnList(); ret.add(new JumpInsnNode(Opcodes.GOTO, labelNode)); return ret; }
[ "public", "static", "InsnList", "jumpTo", "(", "LabelNode", "labelNode", ")", "{", "Validate", ".", "notNull", "(", "labelNode", ")", ";", "InsnList", "ret", "=", "new", "InsnList", "(", ")", ";", "ret", ".", "add", "(", "new", "JumpInsnNode", "(", "Opco...
Generates instructions for an unconditional jump to a label. @param labelNode label to jump to @throws NullPointerException if any argument is {@code null} @return instructions for an unconditional jump to {@code labelNode}
[ "Generates", "instructions", "for", "an", "unconditional", "jump", "to", "a", "label", "." ]
train
https://github.com/offbynull/coroutines/blob/b1b83c293945f53a2f63fca8f15a53e88b796bf5/instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/generators/GenericGenerators.java#L254-L261
hellosign/hellosign-java-sdk
src/main/java/com/hellosign/sdk/resource/SignatureRequest.java
SignatureRequest.getSignature
public Signature getSignature(String email, String name) throws HelloSignException { if (email == null || "".equals(email)) { throw new HelloSignException("Email address cannot be empty"); } if (name == null || "".equals(name)) { throw new HelloSignException("Name cannot be empty"); } for (Signature s : getSignatures()) { if (email.equalsIgnoreCase(s.getEmail()) && name.equalsIgnoreCase(s.getName())) { return s; } } return null; }
java
public Signature getSignature(String email, String name) throws HelloSignException { if (email == null || "".equals(email)) { throw new HelloSignException("Email address cannot be empty"); } if (name == null || "".equals(name)) { throw new HelloSignException("Name cannot be empty"); } for (Signature s : getSignatures()) { if (email.equalsIgnoreCase(s.getEmail()) && name.equalsIgnoreCase(s.getName())) { return s; } } return null; }
[ "public", "Signature", "getSignature", "(", "String", "email", ",", "String", "name", ")", "throws", "HelloSignException", "{", "if", "(", "email", "==", "null", "||", "\"\"", ".", "equals", "(", "email", ")", ")", "{", "throw", "new", "HelloSignException", ...
Returns the signature for the given email/name combination, or null if not found on this request. @param email String email address @param name String name @return Signature or null if not found @throws HelloSignException if the email or name are empty
[ "Returns", "the", "signature", "for", "the", "given", "email", "/", "name", "combination", "or", "null", "if", "not", "found", "on", "this", "request", "." ]
train
https://github.com/hellosign/hellosign-java-sdk/blob/08fa7aeb3b0c68ddb6c7ea797d114d55d36d36b1/src/main/java/com/hellosign/sdk/resource/SignatureRequest.java#L142-L155
apache/groovy
src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java
StaticTypeCheckingVisitor.checkGroovyStyleConstructor
protected MethodNode checkGroovyStyleConstructor(final ClassNode node, final ClassNode[] arguments, final ASTNode source) { if (node.equals(ClassHelper.OBJECT_TYPE) || node.equals(ClassHelper.DYNAMIC_TYPE)) { // in that case, we are facing a list constructor assigned to a def or object return null; } List<ConstructorNode> constructors = node.getDeclaredConstructors(); if (constructors.isEmpty() && arguments.length == 0) { return null; } List<MethodNode> constructorList = findMethod(node, "<init>", arguments); if (constructorList.isEmpty()) { if (isBeingCompiled(node) && arguments.length == 1 && LINKEDHASHMAP_CLASSNODE.equals(arguments[0])) { // there will be a default hash map constructor added later ConstructorNode cn = new ConstructorNode(Opcodes.ACC_PUBLIC, new Parameter[]{ new Parameter(LINKEDHASHMAP_CLASSNODE, "args") }, ClassNode.EMPTY_ARRAY, EmptyStatement.INSTANCE); return cn; } else { addStaticTypeError("No matching constructor found: " + node + toMethodParametersString("<init>", arguments), source); return null; } } else if (constructorList.size() > 1) { addStaticTypeError("Ambiguous constructor call " + node + toMethodParametersString("<init>", arguments), source); return null; } return constructorList.get(0); }
java
protected MethodNode checkGroovyStyleConstructor(final ClassNode node, final ClassNode[] arguments, final ASTNode source) { if (node.equals(ClassHelper.OBJECT_TYPE) || node.equals(ClassHelper.DYNAMIC_TYPE)) { // in that case, we are facing a list constructor assigned to a def or object return null; } List<ConstructorNode> constructors = node.getDeclaredConstructors(); if (constructors.isEmpty() && arguments.length == 0) { return null; } List<MethodNode> constructorList = findMethod(node, "<init>", arguments); if (constructorList.isEmpty()) { if (isBeingCompiled(node) && arguments.length == 1 && LINKEDHASHMAP_CLASSNODE.equals(arguments[0])) { // there will be a default hash map constructor added later ConstructorNode cn = new ConstructorNode(Opcodes.ACC_PUBLIC, new Parameter[]{ new Parameter(LINKEDHASHMAP_CLASSNODE, "args") }, ClassNode.EMPTY_ARRAY, EmptyStatement.INSTANCE); return cn; } else { addStaticTypeError("No matching constructor found: " + node + toMethodParametersString("<init>", arguments), source); return null; } } else if (constructorList.size() > 1) { addStaticTypeError("Ambiguous constructor call " + node + toMethodParametersString("<init>", arguments), source); return null; } return constructorList.get(0); }
[ "protected", "MethodNode", "checkGroovyStyleConstructor", "(", "final", "ClassNode", "node", ",", "final", "ClassNode", "[", "]", "arguments", ",", "final", "ASTNode", "source", ")", "{", "if", "(", "node", ".", "equals", "(", "ClassHelper", ".", "OBJECT_TYPE", ...
Checks that a constructor style expression is valid regarding the number of arguments and the argument types. @param node the class node for which we will try to find a matching constructor @param arguments the constructor arguments
[ "Checks", "that", "a", "constructor", "style", "expression", "is", "valid", "regarding", "the", "number", "of", "arguments", "and", "the", "argument", "types", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java#L1457-L1483
sksamuel/scrimage
scrimage-filters/src/main/java/thirdparty/marvin/image/MarvinImage.java
MarvinImage.setIntColor
public void setIntColor(int x, int y, int alpha, int c0, int c1, int c2) { arrIntColor[((y * image.getWidth() + x))] = (alpha << 24) + (c0 << 16) + (c1 << 8) + c2; }
java
public void setIntColor(int x, int y, int alpha, int c0, int c1, int c2) { arrIntColor[((y * image.getWidth() + x))] = (alpha << 24) + (c0 << 16) + (c1 << 8) + c2; }
[ "public", "void", "setIntColor", "(", "int", "x", ",", "int", "y", ",", "int", "alpha", ",", "int", "c0", ",", "int", "c1", ",", "int", "c2", ")", "{", "arrIntColor", "[", "(", "(", "y", "*", "image", ".", "getWidth", "(", ")", "+", "x", ")", ...
Sets the integer color in X an Y position @param x position @param y position @param c0 component 0 @param c1 component 1 @param c2 component 2
[ "Sets", "the", "integer", "color", "in", "X", "an", "Y", "position" ]
train
https://github.com/sksamuel/scrimage/blob/52dab448136e6657a71951b0e6b7d5e64dc979ac/scrimage-filters/src/main/java/thirdparty/marvin/image/MarvinImage.java#L341-L346
ironjacamar/ironjacamar
deployers/src/main/java/org/ironjacamar/deployers/common/AbstractResourceAdapterDeployer.java
AbstractResourceAdapterDeployer.getTransactionSupport
private TransactionSupportEnum getTransactionSupport(Connector connector, Activation activation) { if (activation.getTransactionSupport() != null) return activation.getTransactionSupport(); if (connector.getResourceadapter().getOutboundResourceadapter() != null) return connector.getResourceadapter().getOutboundResourceadapter().getTransactionSupport(); // We have to assume XA for pure inbound, overrides is done with activation return TransactionSupportEnum.XATransaction; }
java
private TransactionSupportEnum getTransactionSupport(Connector connector, Activation activation) { if (activation.getTransactionSupport() != null) return activation.getTransactionSupport(); if (connector.getResourceadapter().getOutboundResourceadapter() != null) return connector.getResourceadapter().getOutboundResourceadapter().getTransactionSupport(); // We have to assume XA for pure inbound, overrides is done with activation return TransactionSupportEnum.XATransaction; }
[ "private", "TransactionSupportEnum", "getTransactionSupport", "(", "Connector", "connector", ",", "Activation", "activation", ")", "{", "if", "(", "activation", ".", "getTransactionSupport", "(", ")", "!=", "null", ")", "return", "activation", ".", "getTransactionSupp...
Get the transaction support level @param connector The spec metadata @param activation The activation @return True if XA, otherwise false
[ "Get", "the", "transaction", "support", "level" ]
train
https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/deployers/src/main/java/org/ironjacamar/deployers/common/AbstractResourceAdapterDeployer.java#L923-L933
joniles/mpxj
src/main/java/net/sf/mpxj/fasttrack/FastTrackData.java
FastTrackData.readBlock
private void readBlock(int blockIndex, int startIndex, int blockLength) throws Exception { logBlock(blockIndex, startIndex, blockLength); if (blockLength < 128) { readTableBlock(startIndex, blockLength); } else { readColumnBlock(startIndex, blockLength); } }
java
private void readBlock(int blockIndex, int startIndex, int blockLength) throws Exception { logBlock(blockIndex, startIndex, blockLength); if (blockLength < 128) { readTableBlock(startIndex, blockLength); } else { readColumnBlock(startIndex, blockLength); } }
[ "private", "void", "readBlock", "(", "int", "blockIndex", ",", "int", "startIndex", ",", "int", "blockLength", ")", "throws", "Exception", "{", "logBlock", "(", "blockIndex", ",", "startIndex", ",", "blockLength", ")", ";", "if", "(", "blockLength", "<", "12...
Read a block of data from the FastTrack file and determine if it contains a table definition, or columns. @param blockIndex index of the current block @param startIndex start index of the block in the file @param blockLength block length
[ "Read", "a", "block", "of", "data", "from", "the", "FastTrack", "file", "and", "determine", "if", "it", "contains", "a", "table", "definition", "or", "columns", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/fasttrack/FastTrackData.java#L141-L153
googleapis/google-cloud-java
google-cloud-clients/google-cloud-contrib/google-cloud-nio/src/main/java/com/google/cloud/storage/contrib/nio/UnixPath.java
UnixPath.getName
public UnixPath getName(int index) { if (path.isEmpty()) { return this; } try { return new UnixPath(permitEmptyComponents, getParts().get(index)); } catch (IndexOutOfBoundsException e) { throw new IllegalArgumentException(); } }
java
public UnixPath getName(int index) { if (path.isEmpty()) { return this; } try { return new UnixPath(permitEmptyComponents, getParts().get(index)); } catch (IndexOutOfBoundsException e) { throw new IllegalArgumentException(); } }
[ "public", "UnixPath", "getName", "(", "int", "index", ")", "{", "if", "(", "path", ".", "isEmpty", "(", ")", ")", "{", "return", "this", ";", "}", "try", "{", "return", "new", "UnixPath", "(", "permitEmptyComponents", ",", "getParts", "(", ")", ".", ...
Returns component in {@code path} at {@code index}. @see java.nio.file.Path#getName(int)
[ "Returns", "component", "in", "{", "@code", "path", "}", "at", "{", "@code", "index", "}", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-contrib/google-cloud-nio/src/main/java/com/google/cloud/storage/contrib/nio/UnixPath.java#L242-L251
OpenLiberty/open-liberty
dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/impl/ExceptionDestinationHandlerImpl.java
ExceptionDestinationHandlerImpl.handleUndeliverableMessage
public UndeliverableReturnCode handleUndeliverableMessage( SIMPMessage message, TransactionCommon tran, int exceptionReason, String[] exceptionStrings) { // F001333-14610 // Delegate down onto the new method passing a null // subscription ID. return handleUndeliverableMessage(message, tran, exceptionReason, exceptionStrings, null); }
java
public UndeliverableReturnCode handleUndeliverableMessage( SIMPMessage message, TransactionCommon tran, int exceptionReason, String[] exceptionStrings) { // F001333-14610 // Delegate down onto the new method passing a null // subscription ID. return handleUndeliverableMessage(message, tran, exceptionReason, exceptionStrings, null); }
[ "public", "UndeliverableReturnCode", "handleUndeliverableMessage", "(", "SIMPMessage", "message", ",", "TransactionCommon", "tran", ",", "int", "exceptionReason", ",", "String", "[", "]", "exceptionStrings", ")", "{", "// F001333-14610", "// Delegate down onto the new method ...
This method contains the routine used to handle an undeliverable message. The method examines the attributes of a message to determine what to do with it. It is possible for a message to be discarded, blocked, or sent to an exception destination. @param msg - The undeliverable message @param tran - The transaction that the message was delivered under @param exceptionReason - The reason why the message could not be delivered @param exceptionStrings - A list of inserts to place into an error message @return A code indicating what we did with the message
[ "This", "method", "contains", "the", "routine", "used", "to", "handle", "an", "undeliverable", "message", ".", "The", "method", "examines", "the", "attributes", "of", "a", "message", "to", "determine", "what", "to", "do", "with", "it", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/impl/ExceptionDestinationHandlerImpl.java#L371-L381
mapbox/mapbox-navigation-android
libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/utils/DistanceFormatter.java
DistanceFormatter.roundToDecimalPlace
private String roundToDecimalPlace(double distance, int decimalPlace) { numberFormat.setMaximumFractionDigits(decimalPlace); return numberFormat.format(distance); }
java
private String roundToDecimalPlace(double distance, int decimalPlace) { numberFormat.setMaximumFractionDigits(decimalPlace); return numberFormat.format(distance); }
[ "private", "String", "roundToDecimalPlace", "(", "double", "distance", ",", "int", "decimalPlace", ")", "{", "numberFormat", ".", "setMaximumFractionDigits", "(", "decimalPlace", ")", ";", "return", "numberFormat", ".", "format", "(", "distance", ")", ";", "}" ]
Rounds given number to the given decimal place @param distance to round @param decimalPlace number of decimal places to round @return distance rounded to given decimal places
[ "Rounds", "given", "number", "to", "the", "given", "decimal", "place" ]
train
https://github.com/mapbox/mapbox-navigation-android/blob/375a89c017d360b9defc2c90d0c03468165162ec/libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/utils/DistanceFormatter.java#L141-L145
jbundle/osgi
core/src/main/java/org/jbundle/util/osgi/finder/BaseClassFinderService.java
BaseClassFinderService.startBaseBundle
public boolean startBaseBundle(BundleContext context, String interfaceClassName, String dependentServiceClassName, String versionRange, Dictionary<String,String> filter, int secsToWait) { ServiceReference ServiceReference = getClassServiceReference((bundleContext != null) ? bundleContext : context, interfaceClassName, versionRange, filter); if ((ServiceReference != null) && ((ServiceReference.getBundle().getState() & Bundle.ACTIVE) != 0)) return true; // Already up! // If the repository is not up, but the bundle is deployed, this will find it return (ClassFinderActivator.waitForServiceStartup(context, interfaceClassName, dependentServiceClassName, versionRange, null, secsToWait) != null); }
java
public boolean startBaseBundle(BundleContext context, String interfaceClassName, String dependentServiceClassName, String versionRange, Dictionary<String,String> filter, int secsToWait) { ServiceReference ServiceReference = getClassServiceReference((bundleContext != null) ? bundleContext : context, interfaceClassName, versionRange, filter); if ((ServiceReference != null) && ((ServiceReference.getBundle().getState() & Bundle.ACTIVE) != 0)) return true; // Already up! // If the repository is not up, but the bundle is deployed, this will find it return (ClassFinderActivator.waitForServiceStartup(context, interfaceClassName, dependentServiceClassName, versionRange, null, secsToWait) != null); }
[ "public", "boolean", "startBaseBundle", "(", "BundleContext", "context", ",", "String", "interfaceClassName", ",", "String", "dependentServiceClassName", ",", "String", "versionRange", ",", "Dictionary", "<", "String", ",", "String", ">", "filter", ",", "int", "secs...
Start up a basebundle service. Note: You will probably want to call this from a thread and attach a service listener since this may take some time. @param versionRange version @param secsToWait Time to wait for startup 0=0, -1=default @param className @return true If I'm up already @return false If I had a problem.
[ "Start", "up", "a", "basebundle", "service", ".", "Note", ":", "You", "will", "probably", "want", "to", "call", "this", "from", "a", "thread", "and", "attach", "a", "service", "listener", "since", "this", "may", "take", "some", "time", "." ]
train
https://github.com/jbundle/osgi/blob/beb02aef78736a4f799aaac001c8f0327bf0536c/core/src/main/java/org/jbundle/util/osgi/finder/BaseClassFinderService.java#L531-L540
lessthanoptimal/BoofCV
main/boofcv-ip/src/main/java/boofcv/alg/color/ColorLab.java
ColorLab.rgbToLab
public static <T extends ImageGray<T>> void rgbToLab(Planar<T> rgb , Planar<GrayF32> lab ) { lab.reshape(rgb.width,rgb.height,3); if( rgb.getBandType() == GrayU8.class ) { if (BoofConcurrency.USE_CONCURRENT) { ImplColorLab_MT.rgbToLab_U8((Planar<GrayU8>) rgb, lab); } else { ImplColorLab.rgbToLab_U8((Planar<GrayU8>) rgb, lab); } } else if( rgb.getBandType() == GrayF32.class ) { if(BoofConcurrency.USE_CONCURRENT ) { ImplColorLab_MT.rgbToLab_F32((Planar<GrayF32>)rgb,lab); } else { ImplColorLab.rgbToLab_F32((Planar<GrayF32>)rgb,lab); } } else { throw new IllegalArgumentException("Unsupported band type "+rgb.getBandType().getSimpleName()); } }
java
public static <T extends ImageGray<T>> void rgbToLab(Planar<T> rgb , Planar<GrayF32> lab ) { lab.reshape(rgb.width,rgb.height,3); if( rgb.getBandType() == GrayU8.class ) { if (BoofConcurrency.USE_CONCURRENT) { ImplColorLab_MT.rgbToLab_U8((Planar<GrayU8>) rgb, lab); } else { ImplColorLab.rgbToLab_U8((Planar<GrayU8>) rgb, lab); } } else if( rgb.getBandType() == GrayF32.class ) { if(BoofConcurrency.USE_CONCURRENT ) { ImplColorLab_MT.rgbToLab_F32((Planar<GrayF32>)rgb,lab); } else { ImplColorLab.rgbToLab_F32((Planar<GrayF32>)rgb,lab); } } else { throw new IllegalArgumentException("Unsupported band type "+rgb.getBandType().getSimpleName()); } }
[ "public", "static", "<", "T", "extends", "ImageGray", "<", "T", ">", ">", "void", "rgbToLab", "(", "Planar", "<", "T", ">", "rgb", ",", "Planar", "<", "GrayF32", ">", "lab", ")", "{", "lab", ".", "reshape", "(", "rgb", ".", "width", ",", "rgb", "...
Convert a 3-channel {@link Planar} image from RGB into LAB. RGB is assumed to have a range from 0:255 NOTE: Input and output image can be the same instance. @param rgb (Input) RGB encoded image @param lab (Output) LAB encoded image. L = channel 0, A = channel 1, B = channel 2
[ "Convert", "a", "3", "-", "channel", "{", "@link", "Planar", "}", "image", "from", "RGB", "into", "LAB", ".", "RGB", "is", "assumed", "to", "have", "a", "range", "from", "0", ":", "255" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/alg/color/ColorLab.java#L126-L145
aicer/hibiscus-http-client
src/main/java/org/aicer/hibiscus/util/HashGenerator.java
HashGenerator.getMD5Hash
public static String getMD5Hash(final String input) throws HibiscusException { String hashValue = null; try { final MessageDigest messageDigest = MessageDigest.getInstance(MESSAGE_DIGEST_ALGORITHM_MD5); byte[] md5Hash = new byte[BYTE_LENGTH_MD5]; messageDigest.update(input.getBytes(ENCODING_CHARSET_NAME), MESSAGE_DIGEST_UPDATE_OFFSET, input.length()); md5Hash = messageDigest.digest(); hashValue = convertToHex(md5Hash); } catch (NoSuchAlgorithmException e) { throw new HibiscusException("Unsupported Message Digest Algorithm " + MESSAGE_DIGEST_ALGORITHM_MD5, e); } catch (UnsupportedEncodingException e) { throw new HibiscusException("Unsupported Encoding " + ENCODING_CHARSET_NAME , e); } return hashValue; }
java
public static String getMD5Hash(final String input) throws HibiscusException { String hashValue = null; try { final MessageDigest messageDigest = MessageDigest.getInstance(MESSAGE_DIGEST_ALGORITHM_MD5); byte[] md5Hash = new byte[BYTE_LENGTH_MD5]; messageDigest.update(input.getBytes(ENCODING_CHARSET_NAME), MESSAGE_DIGEST_UPDATE_OFFSET, input.length()); md5Hash = messageDigest.digest(); hashValue = convertToHex(md5Hash); } catch (NoSuchAlgorithmException e) { throw new HibiscusException("Unsupported Message Digest Algorithm " + MESSAGE_DIGEST_ALGORITHM_MD5, e); } catch (UnsupportedEncodingException e) { throw new HibiscusException("Unsupported Encoding " + ENCODING_CHARSET_NAME , e); } return hashValue; }
[ "public", "static", "String", "getMD5Hash", "(", "final", "String", "input", ")", "throws", "HibiscusException", "{", "String", "hashValue", "=", "null", ";", "try", "{", "final", "MessageDigest", "messageDigest", "=", "MessageDigest", ".", "getInstance", "(", "...
Returns the MD5 hash of the input string @param input Input string @return String The md5 hash of the input string @throws HibiscusException
[ "Returns", "the", "MD5", "hash", "of", "the", "input", "string" ]
train
https://github.com/aicer/hibiscus-http-client/blob/a037e3cf8d4bb862d38a55a090778736a48d67cc/src/main/java/org/aicer/hibiscus/util/HashGenerator.java#L117-L138
grpc/grpc-java
api/src/main/java/io/grpc/InternalLogId.java
InternalLogId.allocate
public static InternalLogId allocate(String typeName, @Nullable String details) { return new InternalLogId(typeName, details, getNextId()); }
java
public static InternalLogId allocate(String typeName, @Nullable String details) { return new InternalLogId(typeName, details, getNextId()); }
[ "public", "static", "InternalLogId", "allocate", "(", "String", "typeName", ",", "@", "Nullable", "String", "details", ")", "{", "return", "new", "InternalLogId", "(", "typeName", ",", "details", ",", "getNextId", "(", ")", ")", ";", "}" ]
Creates a log id. @param typeName the "Type" to be used when logging this id. @param details a short, human readable string that describes the object the id is attached to. Typically this will be an address or target.
[ "Creates", "a", "log", "id", "." ]
train
https://github.com/grpc/grpc-java/blob/973885457f9609de232d2553b82c67f6c3ff57bf/api/src/main/java/io/grpc/InternalLogId.java#L54-L56
shrinkwrap/resolver
maven/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/bootstrap/MavenManagerBuilder.java
MavenManagerBuilder.dependencyGraphTransformer
public DependencyGraphTransformer dependencyGraphTransformer() { DependencyGraphTransformer transformer = new ConflictResolver(new NearestVersionSelector(), new JavaScopeSelector(), new SimpleOptionalitySelector(), new JavaScopeDeriver()); return new ChainedDependencyGraphTransformer(transformer, new JavaDependencyContextRefiner()); }
java
public DependencyGraphTransformer dependencyGraphTransformer() { DependencyGraphTransformer transformer = new ConflictResolver(new NearestVersionSelector(), new JavaScopeSelector(), new SimpleOptionalitySelector(), new JavaScopeDeriver()); return new ChainedDependencyGraphTransformer(transformer, new JavaDependencyContextRefiner()); }
[ "public", "DependencyGraphTransformer", "dependencyGraphTransformer", "(", ")", "{", "DependencyGraphTransformer", "transformer", "=", "new", "ConflictResolver", "(", "new", "NearestVersionSelector", "(", ")", ",", "new", "JavaScopeSelector", "(", ")", ",", "new", "Simp...
Gets a dependency graph transformer. This one handles scope changes @return
[ "Gets", "a", "dependency", "graph", "transformer", ".", "This", "one", "handles", "scope", "changes" ]
train
https://github.com/shrinkwrap/resolver/blob/e881a84b8cff5b0a014f2a5ebf612be3eb9db01f/maven/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/bootstrap/MavenManagerBuilder.java#L254-L260
voldemort/voldemort
src/java/voldemort/store/stats/StoreStats.java
StoreStats.recordPutTimeAndSize
public void recordPutTimeAndSize(long timeNS, long valueSize, long keySize) { recordTime(Tracked.PUT, timeNS, 0, valueSize, keySize, 0); }
java
public void recordPutTimeAndSize(long timeNS, long valueSize, long keySize) { recordTime(Tracked.PUT, timeNS, 0, valueSize, keySize, 0); }
[ "public", "void", "recordPutTimeAndSize", "(", "long", "timeNS", ",", "long", "valueSize", ",", "long", "keySize", ")", "{", "recordTime", "(", "Tracked", ".", "PUT", ",", "timeNS", ",", "0", ",", "valueSize", ",", "keySize", ",", "0", ")", ";", "}" ]
Record the duration of a put operation, along with the size of the values returned.
[ "Record", "the", "duration", "of", "a", "put", "operation", "along", "with", "the", "size", "of", "the", "values", "returned", "." ]
train
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/stats/StoreStats.java#L104-L106
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/internal/config/ConfigValidator.java
ConfigValidator.checkAndLogPropertyDeprecated
public static boolean checkAndLogPropertyDeprecated(HazelcastProperties properties, HazelcastProperty hazelcastProperty) { if (properties.containsKey(hazelcastProperty)) { LOGGER.warning( "Property " + hazelcastProperty.getName() + " is deprecated. Use configuration object/element instead."); return properties.getBoolean(hazelcastProperty); } return false; }
java
public static boolean checkAndLogPropertyDeprecated(HazelcastProperties properties, HazelcastProperty hazelcastProperty) { if (properties.containsKey(hazelcastProperty)) { LOGGER.warning( "Property " + hazelcastProperty.getName() + " is deprecated. Use configuration object/element instead."); return properties.getBoolean(hazelcastProperty); } return false; }
[ "public", "static", "boolean", "checkAndLogPropertyDeprecated", "(", "HazelcastProperties", "properties", ",", "HazelcastProperty", "hazelcastProperty", ")", "{", "if", "(", "properties", ".", "containsKey", "(", "hazelcastProperty", ")", ")", "{", "LOGGER", ".", "war...
Checks if given group property is defined within given Hazelcast properties. Logs a warning when the property is defied. @return {@code true} when the property is defined
[ "Checks", "if", "given", "group", "property", "is", "defined", "within", "given", "Hazelcast", "properties", ".", "Logs", "a", "warning", "when", "the", "property", "is", "defied", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/internal/config/ConfigValidator.java#L511-L518
baratine/baratine
kraken/src/main/java/com/caucho/v5/kelp/segment/SegmentServiceImpl.java
SegmentServiceImpl.writeMetaContinuation
private void writeMetaContinuation() { TempBuffer tBuf = TempBuffer.create(); byte []buffer = tBuf.buffer(); int metaLength = _segmentMeta[0].size(); SegmentExtent extent = new SegmentExtent(0, _addressTail, metaLength); _metaExtents.add(extent); _addressTail += metaLength; int offset = 0; buffer[offset++] = CODE_META_SEGMENT; long address = extent.address(); int length = extent.length(); long value = (address & ~0xffff) | (length >> 16); offset += BitsUtil.writeLong(buffer, offset, value); int crc = _nonce; crc = Crc32Caucho.generate(crc, buffer, 0, offset); offset += BitsUtil.writeInt(buffer, offset, crc); try (OutStore sOut = openWrite(_metaOffset, offset)) { sOut.write(_metaOffset, buffer, 0, offset); } tBuf.free(); _metaAddress = address; _metaOffset = address; _metaTail = address + length; }
java
private void writeMetaContinuation() { TempBuffer tBuf = TempBuffer.create(); byte []buffer = tBuf.buffer(); int metaLength = _segmentMeta[0].size(); SegmentExtent extent = new SegmentExtent(0, _addressTail, metaLength); _metaExtents.add(extent); _addressTail += metaLength; int offset = 0; buffer[offset++] = CODE_META_SEGMENT; long address = extent.address(); int length = extent.length(); long value = (address & ~0xffff) | (length >> 16); offset += BitsUtil.writeLong(buffer, offset, value); int crc = _nonce; crc = Crc32Caucho.generate(crc, buffer, 0, offset); offset += BitsUtil.writeInt(buffer, offset, crc); try (OutStore sOut = openWrite(_metaOffset, offset)) { sOut.write(_metaOffset, buffer, 0, offset); } tBuf.free(); _metaAddress = address; _metaOffset = address; _metaTail = address + length; }
[ "private", "void", "writeMetaContinuation", "(", ")", "{", "TempBuffer", "tBuf", "=", "TempBuffer", ".", "create", "(", ")", ";", "byte", "[", "]", "buffer", "=", "tBuf", ".", "buffer", "(", ")", ";", "int", "metaLength", "=", "_segmentMeta", "[", "0", ...
Writes a continuation entry, which points to a new meta-data segment.
[ "Writes", "a", "continuation", "entry", "which", "points", "to", "a", "new", "meta", "-", "data", "segment", "." ]
train
https://github.com/baratine/baratine/blob/db34b45c03c5a5e930d8142acc72319125569fcf/kraken/src/main/java/com/caucho/v5/kelp/segment/SegmentServiceImpl.java#L547-L584
litsec/swedish-eid-shibboleth-base
shibboleth-base/shibboleth-extensions/src/main/java/se/litsec/shibboleth/idp/authn/controller/AbstractExternalAuthenticationController.java
AbstractExternalAuthenticationController.initializeServices
protected void initializeServices(ProfileRequestContext<?, ?> profileRequestContext) throws ExternalAutenticationErrorCodeException { this.authnContextService.initializeContext(profileRequestContext); this.signSupportService.initializeContext(profileRequestContext); }
java
protected void initializeServices(ProfileRequestContext<?, ?> profileRequestContext) throws ExternalAutenticationErrorCodeException { this.authnContextService.initializeContext(profileRequestContext); this.signSupportService.initializeContext(profileRequestContext); }
[ "protected", "void", "initializeServices", "(", "ProfileRequestContext", "<", "?", ",", "?", ">", "profileRequestContext", ")", "throws", "ExternalAutenticationErrorCodeException", "{", "this", ".", "authnContextService", ".", "initializeContext", "(", "profileRequestContex...
Initializes the services for the controller. Subclasses should override this method to initialize their own services. @param profileRequestContext the request context @throws ExternalAutenticationErrorCodeException for errors during initialization
[ "Initializes", "the", "services", "for", "the", "controller", ".", "Subclasses", "should", "override", "this", "method", "to", "initialize", "their", "own", "services", "." ]
train
https://github.com/litsec/swedish-eid-shibboleth-base/blob/aaaa467ff61f07d7dfa31627fb36851a37da6804/shibboleth-base/shibboleth-extensions/src/main/java/se/litsec/shibboleth/idp/authn/controller/AbstractExternalAuthenticationController.java#L212-L215
sagiegurari/fax4j
src/main/java/org/fax4j/spi/http/TemplateFaxJob2HTTPRequestConverter.java
TemplateFaxJob2HTTPRequestConverter.createHTTPRequest
public HTTPRequest createHTTPRequest(HTTPFaxClientSpi faxClientSpi,FaxActionType faxActionType,FaxJob faxJob) { FaxJob2HTTPRequestConverterConfigurationConstants templateName=null; switch(faxActionType) { case SUBMIT_FAX_JOB: templateName=FaxJob2HTTPRequestConverterConfigurationConstants.SUBMIT_FAX_JOB_TEMPLATE_PROPERTY_KEY; break; case SUSPEND_FAX_JOB: templateName=FaxJob2HTTPRequestConverterConfigurationConstants.SUSPEND_FAX_JOB_TEMPLATE_PROPERTY_KEY; break; case RESUME_FAX_JOB: templateName=FaxJob2HTTPRequestConverterConfigurationConstants.RESUME_FAX_JOB_TEMPLATE_PROPERTY_KEY; break; case CANCEL_FAX_JOB: templateName=FaxJob2HTTPRequestConverterConfigurationConstants.CANCEL_FAX_JOB_TEMPLATE_PROPERTY_KEY; break; case GET_FAX_JOB_STATUS: templateName=FaxJob2HTTPRequestConverterConfigurationConstants.GET_FAX_JOB_STATUS_TEMPLATE_PROPERTY_KEY; break; default: throw new FaxException("Fax action type: "+faxActionType+" not supported."); } //create HTTP request HTTPRequest httpRequest=this.createHTTPRequest(faxClientSpi,faxActionType,templateName,faxJob); return httpRequest; }
java
public HTTPRequest createHTTPRequest(HTTPFaxClientSpi faxClientSpi,FaxActionType faxActionType,FaxJob faxJob) { FaxJob2HTTPRequestConverterConfigurationConstants templateName=null; switch(faxActionType) { case SUBMIT_FAX_JOB: templateName=FaxJob2HTTPRequestConverterConfigurationConstants.SUBMIT_FAX_JOB_TEMPLATE_PROPERTY_KEY; break; case SUSPEND_FAX_JOB: templateName=FaxJob2HTTPRequestConverterConfigurationConstants.SUSPEND_FAX_JOB_TEMPLATE_PROPERTY_KEY; break; case RESUME_FAX_JOB: templateName=FaxJob2HTTPRequestConverterConfigurationConstants.RESUME_FAX_JOB_TEMPLATE_PROPERTY_KEY; break; case CANCEL_FAX_JOB: templateName=FaxJob2HTTPRequestConverterConfigurationConstants.CANCEL_FAX_JOB_TEMPLATE_PROPERTY_KEY; break; case GET_FAX_JOB_STATUS: templateName=FaxJob2HTTPRequestConverterConfigurationConstants.GET_FAX_JOB_STATUS_TEMPLATE_PROPERTY_KEY; break; default: throw new FaxException("Fax action type: "+faxActionType+" not supported."); } //create HTTP request HTTPRequest httpRequest=this.createHTTPRequest(faxClientSpi,faxActionType,templateName,faxJob); return httpRequest; }
[ "public", "HTTPRequest", "createHTTPRequest", "(", "HTTPFaxClientSpi", "faxClientSpi", ",", "FaxActionType", "faxActionType", ",", "FaxJob", "faxJob", ")", "{", "FaxJob2HTTPRequestConverterConfigurationConstants", "templateName", "=", "null", ";", "switch", "(", "faxActionT...
Creates the HTTP request from the fax job data. @param faxClientSpi The HTTP fax client SPI @param faxActionType The fax action type @param faxJob The fax job object @return The HTTP request to send
[ "Creates", "the", "HTTP", "request", "from", "the", "fax", "job", "data", "." ]
train
https://github.com/sagiegurari/fax4j/blob/42fa51acabe7bf279e27ab3dd1cf76146b27955f/src/main/java/org/fax4j/spi/http/TemplateFaxJob2HTTPRequestConverter.java#L253-L281
broadinstitute/barclay
src/main/java/org/broadinstitute/barclay/utils/Utils.java
Utils.nonNull
public static <T> T nonNull(final T object, final Supplier<String> message) { if (object == null) { throw new IllegalArgumentException(message.get()); } return object; }
java
public static <T> T nonNull(final T object, final Supplier<String> message) { if (object == null) { throw new IllegalArgumentException(message.get()); } return object; }
[ "public", "static", "<", "T", ">", "T", "nonNull", "(", "final", "T", "object", ",", "final", "Supplier", "<", "String", ">", "message", ")", "{", "if", "(", "object", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "message", ...
Checks that an {@link Object} is not {@code null} and returns the same object or throws an {@link IllegalArgumentException} @param object any Object @param message the text message that would be passed to the exception thrown when {@code o == null}. @return the same object @throws IllegalArgumentException if a {@code o == null}
[ "Checks", "that", "an", "{" ]
train
https://github.com/broadinstitute/barclay/blob/7e56d725766b0da3baff23e79a31c3d01c3589c2/src/main/java/org/broadinstitute/barclay/utils/Utils.java#L56-L61
lessthanoptimal/BoofCV
main/boofcv-sfm/src/main/java/boofcv/alg/sfm/structure2/ProjectiveInitializeAllCommon.java
ProjectiveInitializeAllCommon.triangulateFeatures
private void triangulateFeatures(List<AssociatedTriple> inliers, DMatrixRMaj P1, DMatrixRMaj P2, DMatrixRMaj P3) { List<DMatrixRMaj> cameraMatrices = new ArrayList<>(); cameraMatrices.add(P1); cameraMatrices.add(P2); cameraMatrices.add(P3); // need elements to be non-empty so that it can use set(). probably over optimization List<Point2D_F64> triangObs = new ArrayList<>(); triangObs.add(null); triangObs.add(null); triangObs.add(null); Point4D_F64 X = new Point4D_F64(); for (int i = 0; i < inliers.size(); i++) { AssociatedTriple t = inliers.get(i); triangObs.set(0,t.p1); triangObs.set(1,t.p2); triangObs.set(2,t.p3); // triangulation can fail if all 3 views have the same pixel value. This has been observed in // simulated 3D scenes if( triangulator.triangulate(triangObs,cameraMatrices,X)) { structure.points[i].set(X.x,X.y,X.z,X.w); } else { throw new RuntimeException("Failed to triangulate a point in the inlier set?! Handle if this is common"); } } }
java
private void triangulateFeatures(List<AssociatedTriple> inliers, DMatrixRMaj P1, DMatrixRMaj P2, DMatrixRMaj P3) { List<DMatrixRMaj> cameraMatrices = new ArrayList<>(); cameraMatrices.add(P1); cameraMatrices.add(P2); cameraMatrices.add(P3); // need elements to be non-empty so that it can use set(). probably over optimization List<Point2D_F64> triangObs = new ArrayList<>(); triangObs.add(null); triangObs.add(null); triangObs.add(null); Point4D_F64 X = new Point4D_F64(); for (int i = 0; i < inliers.size(); i++) { AssociatedTriple t = inliers.get(i); triangObs.set(0,t.p1); triangObs.set(1,t.p2); triangObs.set(2,t.p3); // triangulation can fail if all 3 views have the same pixel value. This has been observed in // simulated 3D scenes if( triangulator.triangulate(triangObs,cameraMatrices,X)) { structure.points[i].set(X.x,X.y,X.z,X.w); } else { throw new RuntimeException("Failed to triangulate a point in the inlier set?! Handle if this is common"); } } }
[ "private", "void", "triangulateFeatures", "(", "List", "<", "AssociatedTriple", ">", "inliers", ",", "DMatrixRMaj", "P1", ",", "DMatrixRMaj", "P2", ",", "DMatrixRMaj", "P3", ")", "{", "List", "<", "DMatrixRMaj", ">", "cameraMatrices", "=", "new", "ArrayList", ...
Triangulates the location of each features in homogenous space
[ "Triangulates", "the", "location", "of", "each", "features", "in", "homogenous", "space" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-sfm/src/main/java/boofcv/alg/sfm/structure2/ProjectiveInitializeAllCommon.java#L275-L304
zeroturnaround/zt-zip
src/main/java/org/zeroturnaround/zip/ZipUtil.java
ZipUtil.packEntry
public static void packEntry(File fileToPack, File destZipFile, NameMapper mapper) { packEntries(new File[] { fileToPack }, destZipFile, mapper); }
java
public static void packEntry(File fileToPack, File destZipFile, NameMapper mapper) { packEntries(new File[] { fileToPack }, destZipFile, mapper); }
[ "public", "static", "void", "packEntry", "(", "File", "fileToPack", ",", "File", "destZipFile", ",", "NameMapper", "mapper", ")", "{", "packEntries", "(", "new", "File", "[", "]", "{", "fileToPack", "}", ",", "destZipFile", ",", "mapper", ")", ";", "}" ]
Compresses the given file into a ZIP file. <p> The ZIP file must not be a directory and its parent directory must exist. @param fileToPack file that needs to be zipped. @param destZipFile ZIP file that will be created or overwritten. @param mapper call-back for renaming the entries.
[ "Compresses", "the", "given", "file", "into", "a", "ZIP", "file", ".", "<p", ">", "The", "ZIP", "file", "must", "not", "be", "a", "directory", "and", "its", "parent", "directory", "must", "exist", "." ]
train
https://github.com/zeroturnaround/zt-zip/blob/abb4dc43583e4d19339c0c021035019798970a13/src/main/java/org/zeroturnaround/zip/ZipUtil.java#L1479-L1481
jmapper-framework/jmapper-core
JMapper Framework/src/main/java/com/googlecode/jmapper/JMapper.java
JMapper.getDestination
public D getDestination(final S source,final NullPointerControl nullPointerControl,final MappingType mtSource){ try{ switch(nullPointerControl){ case ALL: case DESTINATION: case SOURCE: switch(mtSource){ case ALL_FIELDS: return mapper.nullVSouAllAll(source); case ONLY_VALUED_FIELDS: return mapper.nullVSouAllValued(source); case ONLY_NULL_FIELDS: return mapper.get(source);} case NOT_ANY: switch(mtSource){ case ALL_FIELDS: return mapper.nullVNotAllAll(source); case ONLY_VALUED_FIELDS: return mapper.nullVNotAllValued(source); case ONLY_NULL_FIELDS: return mapper.get(source);}} }catch (Exception e) { JmapperLog.error(e); } return null; }
java
public D getDestination(final S source,final NullPointerControl nullPointerControl,final MappingType mtSource){ try{ switch(nullPointerControl){ case ALL: case DESTINATION: case SOURCE: switch(mtSource){ case ALL_FIELDS: return mapper.nullVSouAllAll(source); case ONLY_VALUED_FIELDS: return mapper.nullVSouAllValued(source); case ONLY_NULL_FIELDS: return mapper.get(source);} case NOT_ANY: switch(mtSource){ case ALL_FIELDS: return mapper.nullVNotAllAll(source); case ONLY_VALUED_FIELDS: return mapper.nullVNotAllValued(source); case ONLY_NULL_FIELDS: return mapper.get(source);}} }catch (Exception e) { JmapperLog.error(e); } return null; }
[ "public", "D", "getDestination", "(", "final", "S", "source", ",", "final", "NullPointerControl", "nullPointerControl", ",", "final", "MappingType", "mtSource", ")", "{", "try", "{", "switch", "(", "nullPointerControl", ")", "{", "case", "ALL", ":", "case", "D...
This method returns a new instance of Destination Class with this setting: <table summary = ""> <tr> <td><code>NullPointerControl</code></td><td>nullPointerControl</td> </tr><tr> <td><code>MappingType</code> of Destination</td><td><code>ALL_FIELDS</code></td> </tr><tr> <td><code>MappingType</code> of Source</td><td>mtSource</td> </tr> </table> @param source instance that contains the data @param nullPointerControl type of control @param mtSource type of mapping @return new instance of destination @see NullPointerControl @see MappingType
[ "This", "method", "returns", "a", "new", "instance", "of", "Destination", "Class", "with", "this", "setting", ":", "<table", "summary", "=", ">", "<tr", ">", "<td", ">", "<code", ">", "NullPointerControl<", "/", "code", ">", "<", "/", "td", ">", "<td", ...
train
https://github.com/jmapper-framework/jmapper-core/blob/b48fd3527f35055b8b4a30f53a51136f183acc90/JMapper Framework/src/main/java/com/googlecode/jmapper/JMapper.java#L223-L242
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/Validate.java
Validate.exclusiveBetween
public static <T> void exclusiveBetween(final T start, final T end, final Comparable<T> value) { // TODO when breaking BC, consider returning value if (value.compareTo(start) <= 0 || value.compareTo(end) >= 0) { throw new IllegalArgumentException(StringUtils.simpleFormat(DEFAULT_EXCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end)); } }
java
public static <T> void exclusiveBetween(final T start, final T end, final Comparable<T> value) { // TODO when breaking BC, consider returning value if (value.compareTo(start) <= 0 || value.compareTo(end) >= 0) { throw new IllegalArgumentException(StringUtils.simpleFormat(DEFAULT_EXCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end)); } }
[ "public", "static", "<", "T", ">", "void", "exclusiveBetween", "(", "final", "T", "start", ",", "final", "T", "end", ",", "final", "Comparable", "<", "T", ">", "value", ")", "{", "// TODO when breaking BC, consider returning value", "if", "(", "value", ".", ...
<p>Validate that the specified argument object fall between the two exclusive values specified; otherwise, throws an exception.</p> <pre>Validate.exclusiveBetween(0, 2, 1);</pre> @param <T> the type of the argument object @param start the exclusive start value, not null @param end the exclusive end value, not null @param value the object to validate, not null @throws IllegalArgumentException if the value falls outside the boundaries @see #exclusiveBetween(Object, Object, Comparable, String, Object...) @since 3.0
[ "<p", ">", "Validate", "that", "the", "specified", "argument", "object", "fall", "between", "the", "two", "exclusive", "values", "specified", ";", "otherwise", "throws", "an", "exception", ".", "<", "/", "p", ">" ]
train
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/Validate.java#L1127-L1132
vanilladb/vanillacore
src/main/java/org/vanilladb/core/storage/metadata/statistics/SampledHistogramBuilder.java
SampledHistogramBuilder.newMaxDiffHistogram
public Histogram newMaxDiffHistogram(int numBkts, int numPcts) { Map<String, BucketBuilder> initBbs = new HashMap<String, BucketBuilder>(); for (String fld : schema.fields()) { if (schema.type(fld).isNumeric()) { initBbs.put(fld, new MaxDiffAreaBucketBuilder(frequencies(fld), null)); } else initBbs.put(fld, new MaxDiffFreqBucketBuilder(frequencies(fld), numPcts)); } return newMaxDiffHistogram(numBkts, initBbs); }
java
public Histogram newMaxDiffHistogram(int numBkts, int numPcts) { Map<String, BucketBuilder> initBbs = new HashMap<String, BucketBuilder>(); for (String fld : schema.fields()) { if (schema.type(fld).isNumeric()) { initBbs.put(fld, new MaxDiffAreaBucketBuilder(frequencies(fld), null)); } else initBbs.put(fld, new MaxDiffFreqBucketBuilder(frequencies(fld), numPcts)); } return newMaxDiffHistogram(numBkts, initBbs); }
[ "public", "Histogram", "newMaxDiffHistogram", "(", "int", "numBkts", ",", "int", "numPcts", ")", "{", "Map", "<", "String", ",", "BucketBuilder", ">", "initBbs", "=", "new", "HashMap", "<", "String", ",", "BucketBuilder", ">", "(", ")", ";", "for", "(", ...
Constructs a histogram with the "MaxDiff(V, A)" buckets for numeric field values and "MaxDiff(V, F)" buckets for other types of field values respectively. @param numBkts the number of buckets to construct for each field @param numPcts the number of value percentiles in each bucket of the non-numeric fields @return a "MaxDiff(V, A/F)" histogram
[ "Constructs", "a", "histogram", "with", "the", "MaxDiff", "(", "V", "A", ")", "buckets", "for", "numeric", "field", "values", "and", "MaxDiff", "(", "V", "F", ")", "buckets", "for", "other", "types", "of", "field", "values", "respectively", "." ]
train
https://github.com/vanilladb/vanillacore/blob/d9a34e876b1b83226036d1fa982a614bbef59bd1/src/main/java/org/vanilladb/core/storage/metadata/statistics/SampledHistogramBuilder.java#L395-L406
mlhartme/mork
src/main/java/net/oneandone/mork/scanner/Minimizer.java
Minimizer.setDistinct
private void setDistinct(int leftSi, int rightSi) { IntArrayList tmp; int pair; int i, max; tmp = distinct[leftSi][rightSi]; if (tmp != YES) { distinct[leftSi][rightSi] = YES; if (tmp != UNKNOWN) { max = tmp.size(); for (i = 0; i < max; i++) { pair = tmp.get(i); setDistinct(left(pair), right(pair)); } } } }
java
private void setDistinct(int leftSi, int rightSi) { IntArrayList tmp; int pair; int i, max; tmp = distinct[leftSi][rightSi]; if (tmp != YES) { distinct[leftSi][rightSi] = YES; if (tmp != UNKNOWN) { max = tmp.size(); for (i = 0; i < max; i++) { pair = tmp.get(i); setDistinct(left(pair), right(pair)); } } } }
[ "private", "void", "setDistinct", "(", "int", "leftSi", ",", "int", "rightSi", ")", "{", "IntArrayList", "tmp", ";", "int", "pair", ";", "int", "i", ",", "max", ";", "tmp", "=", "distinct", "[", "leftSi", "]", "[", "rightSi", "]", ";", "if", "(", "...
Mark the pair to be distinct. Recursively marks depending pairs.
[ "Mark", "the", "pair", "to", "be", "distinct", ".", "Recursively", "marks", "depending", "pairs", "." ]
train
https://github.com/mlhartme/mork/blob/a069b087750c4133bfeebaf1f599c3bc96762113/src/main/java/net/oneandone/mork/scanner/Minimizer.java#L237-L253
grails/grails-core
grails-core/src/main/groovy/org/grails/compiler/injection/GrailsASTUtils.java
GrailsASTUtils.applyMethodTarget
public static MethodCallExpression applyMethodTarget(final MethodCallExpression methodCallExpression, final Class<?> targetClass, final Class<?>... targetParameterClassTypes) { return applyMethodTarget(methodCallExpression, ClassHelper.make(targetClass).getPlainNodeReference(), convertTargetParameterTypes(targetParameterClassTypes)); }
java
public static MethodCallExpression applyMethodTarget(final MethodCallExpression methodCallExpression, final Class<?> targetClass, final Class<?>... targetParameterClassTypes) { return applyMethodTarget(methodCallExpression, ClassHelper.make(targetClass).getPlainNodeReference(), convertTargetParameterTypes(targetParameterClassTypes)); }
[ "public", "static", "MethodCallExpression", "applyMethodTarget", "(", "final", "MethodCallExpression", "methodCallExpression", ",", "final", "Class", "<", "?", ">", "targetClass", ",", "final", "Class", "<", "?", ">", "...", "targetParameterClassTypes", ")", "{", "r...
Set the method target of a MethodCallExpression to the first matching method with same number and type of arguments. @param methodCallExpression @param targetClass @param targetParameterClassTypes @return The method call expression
[ "Set", "the", "method", "target", "of", "a", "MethodCallExpression", "to", "the", "first", "matching", "method", "with", "same", "number", "and", "type", "of", "arguments", "." ]
train
https://github.com/grails/grails-core/blob/c0b08aa995b0297143b75d05642abba8cb7b4122/grails-core/src/main/groovy/org/grails/compiler/injection/GrailsASTUtils.java#L1256-L1258
kite-sdk/kite
kite-data/kite-data-hbase/src/main/java/org/kitesdk/data/hbase/impl/EntitySerDe.java
EntitySerDe.deserializeColumn
private Object deserializeColumn(String fieldName, byte[] family, byte[] qualifier, Result result) { byte[] bytes = result.getValue(family, qualifier); if (bytes == null) { return getDefaultValue(fieldName); } else { return deserializeColumnValueFromBytes(fieldName, bytes); } }
java
private Object deserializeColumn(String fieldName, byte[] family, byte[] qualifier, Result result) { byte[] bytes = result.getValue(family, qualifier); if (bytes == null) { return getDefaultValue(fieldName); } else { return deserializeColumnValueFromBytes(fieldName, bytes); } }
[ "private", "Object", "deserializeColumn", "(", "String", "fieldName", ",", "byte", "[", "]", "family", ",", "byte", "[", "]", "qualifier", ",", "Result", "result", ")", "{", "byte", "[", "]", "bytes", "=", "result", ".", "getValue", "(", "family", ",", ...
Deserialize the entity field that has a column mapping. @param fieldName The name of the entity's field we are deserializing. @param family The column family this field is mapped to @param qualifier The column qualifier this field is mapped to @param result The HBase Result that represents a row in HBase. @return The deserialized field value
[ "Deserialize", "the", "entity", "field", "that", "has", "a", "column", "mapping", "." ]
train
https://github.com/kite-sdk/kite/blob/72bfb4b1a881af85808cd7f14bc3e15160a1e811/kite-data/kite-data-hbase/src/main/java/org/kitesdk/data/hbase/impl/EntitySerDe.java#L301-L309
OpenTSDB/opentsdb
src/core/HistogramAggregationIterator.java
HistogramAggregationIterator.putDataPoint
private void putDataPoint(final int i, final HistogramDataPoint dp) { timestamps[i] = dp.timestamp(); values[i] = dp.clone(); }
java
private void putDataPoint(final int i, final HistogramDataPoint dp) { timestamps[i] = dp.timestamp(); values[i] = dp.clone(); }
[ "private", "void", "putDataPoint", "(", "final", "int", "i", ",", "final", "HistogramDataPoint", "dp", ")", "{", "timestamps", "[", "i", "]", "=", "dp", ".", "timestamp", "(", ")", ";", "values", "[", "i", "]", "=", "dp", ".", "clone", "(", ")", ";...
Puts the next data point of an iterator in the internal buffer. @param i The index in {@link #iterators} of the iterator. @param dp The last data point returned by that iterator.
[ "Puts", "the", "next", "data", "point", "of", "an", "iterator", "in", "the", "internal", "buffer", "." ]
train
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/core/HistogramAggregationIterator.java#L178-L181
apache/flink
flink-core/src/main/java/org/apache/flink/api/common/typeutils/base/BigDecComparator.java
BigDecComparator.putNormalizedKey
@Override public void putNormalizedKey(BigDecimal record, MemorySegment target, int offset, int len) { final long signum = record.signum(); // order of magnitude // smallest: // scale = Integer.MAX, precision = 1 => SMALLEST_MAGNITUDE // largest: // scale = Integer.MIN, precision = Integer.MAX => LARGEST_MAGNITUDE final long mag = ((long) record.scale()) - ((long) record.precision()) + 1; // normalize value range: from 0 to (SMALLEST_MAGNITUDE + -1*LARGEST_MAGNITUDE) final long normMag = -1L * LARGEST_MAGNITUDE + mag; // normalize value range dependent on sign: // 0 to (SMALLEST_MAGNITUDE + -1*LARGEST_MAGNITUDE) // OR (SMALLEST_MAGNITUDE + -1*LARGEST_MAGNITUDE) to 0 // --> uses at most 33 bit (5 least-significant bytes) long signNormMag = signum < 0 ? normMag : (SMALLEST_MAGNITUDE + -1L * LARGEST_MAGNITUDE - normMag); // zero has no magnitude // set 34th bit to flag zero if (signum == 0) { signNormMag = 0L; signNormMag |= (1L << 34); } // set 35th bit to flag positive sign else if (signum > 0) { signNormMag |= (1L << 35); } // add 5 least-significant bytes that contain value to target for (int i = 0; i < 5 && len > 0; i++, len--) { final byte b = (byte) (signNormMag >>> (8 * (4 - i))); target.put(offset++, b); } }
java
@Override public void putNormalizedKey(BigDecimal record, MemorySegment target, int offset, int len) { final long signum = record.signum(); // order of magnitude // smallest: // scale = Integer.MAX, precision = 1 => SMALLEST_MAGNITUDE // largest: // scale = Integer.MIN, precision = Integer.MAX => LARGEST_MAGNITUDE final long mag = ((long) record.scale()) - ((long) record.precision()) + 1; // normalize value range: from 0 to (SMALLEST_MAGNITUDE + -1*LARGEST_MAGNITUDE) final long normMag = -1L * LARGEST_MAGNITUDE + mag; // normalize value range dependent on sign: // 0 to (SMALLEST_MAGNITUDE + -1*LARGEST_MAGNITUDE) // OR (SMALLEST_MAGNITUDE + -1*LARGEST_MAGNITUDE) to 0 // --> uses at most 33 bit (5 least-significant bytes) long signNormMag = signum < 0 ? normMag : (SMALLEST_MAGNITUDE + -1L * LARGEST_MAGNITUDE - normMag); // zero has no magnitude // set 34th bit to flag zero if (signum == 0) { signNormMag = 0L; signNormMag |= (1L << 34); } // set 35th bit to flag positive sign else if (signum > 0) { signNormMag |= (1L << 35); } // add 5 least-significant bytes that contain value to target for (int i = 0; i < 5 && len > 0; i++, len--) { final byte b = (byte) (signNormMag >>> (8 * (4 - i))); target.put(offset++, b); } }
[ "@", "Override", "public", "void", "putNormalizedKey", "(", "BigDecimal", "record", ",", "MemorySegment", "target", ",", "int", "offset", ",", "int", "len", ")", "{", "final", "long", "signum", "=", "record", ".", "signum", "(", ")", ";", "// order of magnit...
Adds a normalized key containing a normalized order of magnitude of the given record. 2 bits determine the sign (negative, zero, positive), 33 bits determine the magnitude. This method adds at most 5 bytes that contain information.
[ "Adds", "a", "normalized", "key", "containing", "a", "normalized", "order", "of", "magnitude", "of", "the", "given", "record", ".", "2", "bits", "determine", "the", "sign", "(", "negative", "zero", "positive", ")", "33", "bits", "determine", "the", "magnitud...
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/api/common/typeutils/base/BigDecComparator.java#L76-L112
MTDdk/jawn
jawn-core/src/main/java/net/javapla/jawn/core/routes/RouterImpl.java
RouterImpl.calculateRoute
private final Route calculateRoute(HttpMethod httpMethod, String requestUri/*, ActionInvoker invoker*//*,Injector injector*/) throws RouteException { if (routes == null) throw new IllegalStateException("Routes have not been compiled. Call #compileRoutes() first"); final Route route = matchCustom(httpMethod, requestUri); if (route != null) return route; // nothing is found - try to deduce a route from controllers //if (isDev) { try { return matchStandard(httpMethod, requestUri, invoker/*injector*/); } catch (ClassLoadException e) { // a route could not be deduced } //} throw new RouteException("Failed to map resource to URI: " + requestUri); }
java
private final Route calculateRoute(HttpMethod httpMethod, String requestUri/*, ActionInvoker invoker*//*,Injector injector*/) throws RouteException { if (routes == null) throw new IllegalStateException("Routes have not been compiled. Call #compileRoutes() first"); final Route route = matchCustom(httpMethod, requestUri); if (route != null) return route; // nothing is found - try to deduce a route from controllers //if (isDev) { try { return matchStandard(httpMethod, requestUri, invoker/*injector*/); } catch (ClassLoadException e) { // a route could not be deduced } //} throw new RouteException("Failed to map resource to URI: " + requestUri); }
[ "private", "final", "Route", "calculateRoute", "(", "HttpMethod", "httpMethod", ",", "String", "requestUri", "/*, ActionInvoker invoker*/", "/*,Injector injector*/", ")", "throws", "RouteException", "{", "if", "(", "routes", "==", "null", ")", "throw", "new", "Illegal...
It is not consistent that this particular injector handles implementations from both core and server
[ "It", "is", "not", "consistent", "that", "this", "particular", "injector", "handles", "implementations", "from", "both", "core", "and", "server" ]
train
https://github.com/MTDdk/jawn/blob/4ec2d09b97d413efdead7487e6075e5bfd13b925/jawn-core/src/main/java/net/javapla/jawn/core/routes/RouterImpl.java#L82-L98
m-m-m/util
collection/src/main/java/net/sf/mmm/util/collection/impl/CollectionFactoryManagerImpl.java
CollectionFactoryManagerImpl.registerMapFactory
protected <MAP extends Map> MapFactory registerMapFactory(MapFactory<? extends MAP> factory, Class<MAP> mapInterface) { return this.mapFactoryMap.put(mapInterface, factory); }
java
protected <MAP extends Map> MapFactory registerMapFactory(MapFactory<? extends MAP> factory, Class<MAP> mapInterface) { return this.mapFactoryMap.put(mapInterface, factory); }
[ "protected", "<", "MAP", "extends", "Map", ">", "MapFactory", "registerMapFactory", "(", "MapFactory", "<", "?", "extends", "MAP", ">", "factory", ",", "Class", "<", "MAP", ">", "mapInterface", ")", "{", "return", "this", ".", "mapFactoryMap", ".", "put", ...
This method registers the given {@code factory} for the given {@code mapInterface}. @param <MAP> is the generic type of the {@code mapInterface}. @param factory is the {@link MapFactory} to register. @param mapInterface is the interface of the associated {@link Map}. It has to be {@link Class#isAssignableFrom(Class) assignable from} the {@link MapFactory#getMapInterface() map-interface} of the given {@code factory}. @return the {@link MapFactory} that was registered for the given {@code mapInterface} before and has now been replaced with {@code factory} or {@code null} if none was replaced.
[ "This", "method", "registers", "the", "given", "{", "@code", "factory", "}", "for", "the", "given", "{", "@code", "mapInterface", "}", "." ]
train
https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/collection/src/main/java/net/sf/mmm/util/collection/impl/CollectionFactoryManagerImpl.java#L147-L150
xcesco/kripton
kripton-processor/src/main/java/com/abubusoft/kripton/processor/bind/transform/MapBindTransformation.java
MapBindTransformation.generateSerializeOnJackson
@Override public void generateSerializeOnJackson(BindTypeContext context, MethodSpec.Builder methodBuilder, String serializerName, TypeName beanClass, String beanName, BindProperty property) { this.generateSerializeOnJacksonInternal(context, methodBuilder, serializerName, beanClass, beanName, property, false); }
java
@Override public void generateSerializeOnJackson(BindTypeContext context, MethodSpec.Builder methodBuilder, String serializerName, TypeName beanClass, String beanName, BindProperty property) { this.generateSerializeOnJacksonInternal(context, methodBuilder, serializerName, beanClass, beanName, property, false); }
[ "@", "Override", "public", "void", "generateSerializeOnJackson", "(", "BindTypeContext", "context", ",", "MethodSpec", ".", "Builder", "methodBuilder", ",", "String", "serializerName", ",", "TypeName", "beanClass", ",", "String", "beanName", ",", "BindProperty", "prop...
/* (non-Javadoc) @see com.abubusoft.kripton.processor.bind.transform.BindTransform#generateSerializeOnJackson(com.abubusoft.kripton.processor.bind.BindTypeContext, com.squareup.javapoet.MethodSpec.Builder, java.lang.String, com.squareup.javapoet.TypeName, java.lang.String, com.abubusoft.kripton.processor.bind.model.BindProperty)
[ "/", "*", "(", "non", "-", "Javadoc", ")" ]
train
https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/bind/transform/MapBindTransformation.java#L241-L244
couchbase/couchbase-lite-java
src/main/java/com/couchbase/lite/AbstractQuery.java
AbstractQuery.addChangeListener
@NonNull @Override public ListenerToken addChangeListener(Executor executor, @NonNull QueryChangeListener listener) { if (listener == null) { throw new IllegalArgumentException("listener cannot be null."); } return liveQuery().addChangeListener(executor, listener); }
java
@NonNull @Override public ListenerToken addChangeListener(Executor executor, @NonNull QueryChangeListener listener) { if (listener == null) { throw new IllegalArgumentException("listener cannot be null."); } return liveQuery().addChangeListener(executor, listener); }
[ "@", "NonNull", "@", "Override", "public", "ListenerToken", "addChangeListener", "(", "Executor", "executor", ",", "@", "NonNull", "QueryChangeListener", "listener", ")", "{", "if", "(", "listener", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException...
Adds a query change listener with the dispatch queue on which changes will be posted. If the dispatch queue is not specified, the changes will be posted on the main queue. @param executor The executor object that calls listener. If null, use default executor. @param listener The listener to post changes. @return An opaque listener token object for removing the listener.
[ "Adds", "a", "query", "change", "listener", "with", "the", "dispatch", "queue", "on", "which", "changes", "will", "be", "posted", ".", "If", "the", "dispatch", "queue", "is", "not", "specified", "the", "changes", "will", "be", "posted", "on", "the", "main"...
train
https://github.com/couchbase/couchbase-lite-java/blob/cb72c44186456e6191a9ad0a7feb310011d0b081/src/main/java/com/couchbase/lite/AbstractQuery.java#L185-L190
kuali/ojb-1.0.4
src/java/org/apache/ojb/broker/query/FieldCriteria.java
FieldCriteria.buildLessCriteria
static FieldCriteria buildLessCriteria(Object anAttribute, Object aValue, UserAlias anAlias) { return new FieldCriteria(anAttribute, aValue, LESS, anAlias); }
java
static FieldCriteria buildLessCriteria(Object anAttribute, Object aValue, UserAlias anAlias) { return new FieldCriteria(anAttribute, aValue, LESS, anAlias); }
[ "static", "FieldCriteria", "buildLessCriteria", "(", "Object", "anAttribute", ",", "Object", "aValue", ",", "UserAlias", "anAlias", ")", "{", "return", "new", "FieldCriteria", "(", "anAttribute", ",", "aValue", ",", "LESS", ",", "anAlias", ")", ";", "}" ]
static FieldCriteria buildLessCriteria(Object anAttribute, Object aValue, String anAlias)
[ "static", "FieldCriteria", "buildLessCriteria", "(", "Object", "anAttribute", "Object", "aValue", "String", "anAlias", ")" ]
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/query/FieldCriteria.java#L56-L59
dita-ot/dita-ot
src/main/java/org/dita/dost/ProcessorFactory.java
ProcessorFactory.newProcessor
public Processor newProcessor(final String transtype) { if (ditaDir == null) { throw new IllegalStateException(); } if (!Configuration.transtypes.contains(transtype)) { throw new IllegalArgumentException("Transtype " + transtype + " not supported"); } return new Processor(ditaDir, transtype, Collections.unmodifiableMap(args)); }
java
public Processor newProcessor(final String transtype) { if (ditaDir == null) { throw new IllegalStateException(); } if (!Configuration.transtypes.contains(transtype)) { throw new IllegalArgumentException("Transtype " + transtype + " not supported"); } return new Processor(ditaDir, transtype, Collections.unmodifiableMap(args)); }
[ "public", "Processor", "newProcessor", "(", "final", "String", "transtype", ")", "{", "if", "(", "ditaDir", "==", "null", ")", "{", "throw", "new", "IllegalStateException", "(", ")", ";", "}", "if", "(", "!", "Configuration", ".", "transtypes", ".", "conta...
Create new Processor to run DITA-OT @param transtype transtype for the processor @return new Processor instance
[ "Create", "new", "Processor", "to", "run", "DITA", "-", "OT" ]
train
https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/ProcessorFactory.java#L53-L61
alkacon/opencms-core
src/org/opencms/xml/CmsXmlUtils.java
CmsXmlUtils.concatXpath
public static String concatXpath(String prefix, String suffix) { if (suffix == null) { // ensure suffix is not null suffix = ""; } else { if ((suffix.length() > 0) && (suffix.charAt(0) == '/')) { // remove leading '/' form suffix suffix = suffix.substring(1); } } if (prefix != null) { StringBuffer result = new StringBuffer(32); result.append(prefix); if (!CmsResource.isFolder(prefix) && (suffix.length() > 0)) { result.append('/'); } result.append(suffix); return result.toString(); } return suffix; }
java
public static String concatXpath(String prefix, String suffix) { if (suffix == null) { // ensure suffix is not null suffix = ""; } else { if ((suffix.length() > 0) && (suffix.charAt(0) == '/')) { // remove leading '/' form suffix suffix = suffix.substring(1); } } if (prefix != null) { StringBuffer result = new StringBuffer(32); result.append(prefix); if (!CmsResource.isFolder(prefix) && (suffix.length() > 0)) { result.append('/'); } result.append(suffix); return result.toString(); } return suffix; }
[ "public", "static", "String", "concatXpath", "(", "String", "prefix", ",", "String", "suffix", ")", "{", "if", "(", "suffix", "==", "null", ")", "{", "// ensure suffix is not null", "suffix", "=", "\"\"", ";", "}", "else", "{", "if", "(", "(", "suffix", ...
Concatenates two Xpath expressions, ensuring that exactly one slash "/" is between them.<p> Use this method if it's uncertain if the given arguments are starting or ending with a slash "/".<p> Examples:<br> <code>"title", "subtitle"</code> becomes <code>title/subtitle</code><br> <code>"title[1]/", "subtitle"</code> becomes <code>title[1]/subtitle</code><br> <code>"title[1]/", "/subtitle[1]"</code> becomes <code>title[1]/subtitle[1]</code><p> @param prefix the prefix Xpath @param suffix the suffix Xpath @return the concatenated Xpath build from prefix and suffix
[ "Concatenates", "two", "Xpath", "expressions", "ensuring", "that", "exactly", "one", "slash", "/", "is", "between", "them", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/xml/CmsXmlUtils.java#L136-L157
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDMath.java
SDMath.cosineSimilarity
public SDVariable cosineSimilarity(String name, SDVariable x, SDVariable y, int... dimensions) { validateNumerical("cosine similarity", x, y); SDVariable cosim = f().cosineSimilarity(x, y, dimensions); return updateVariableNameAndReference(cosim, name); }
java
public SDVariable cosineSimilarity(String name, SDVariable x, SDVariable y, int... dimensions) { validateNumerical("cosine similarity", x, y); SDVariable cosim = f().cosineSimilarity(x, y, dimensions); return updateVariableNameAndReference(cosim, name); }
[ "public", "SDVariable", "cosineSimilarity", "(", "String", "name", ",", "SDVariable", "x", ",", "SDVariable", "y", ",", "int", "...", "dimensions", ")", "{", "validateNumerical", "(", "\"cosine similarity\"", ",", "x", ",", "y", ")", ";", "SDVariable", "cosim"...
Cosine similarity pairwise reduction operation. The output contains the cosine similarity for each tensor/subset along the specified dimensions:<br> out = (sum_i x[i] * y[i]) / ( sqrt(sum_i x[i]^2) * sqrt(sum_i y[i]^2) @param x Input variable x @param y Input variable y @param dimensions Dimensions to calculate cosine similarity over @return Output variable
[ "Cosine", "similarity", "pairwise", "reduction", "operation", ".", "The", "output", "contains", "the", "cosine", "similarity", "for", "each", "tensor", "/", "subset", "along", "the", "specified", "dimensions", ":", "<br", ">", "out", "=", "(", "sum_i", "x", ...
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDMath.java#L678-L682
jenkinsci/jenkins
core/src/main/java/hudson/security/TokenBasedRememberMeServices2.java
TokenBasedRememberMeServices2.findRememberMeCookieValue
private String findRememberMeCookieValue(HttpServletRequest request, HttpServletResponse response) { Cookie[] cookies = request.getCookies(); if ((cookies == null) || (cookies.length == 0)) { return null; } for (Cookie cookie : cookies) { if (ACEGI_SECURITY_HASHED_REMEMBER_ME_COOKIE_KEY.equals(cookie.getName())) { return cookie.getValue(); } } return null; }
java
private String findRememberMeCookieValue(HttpServletRequest request, HttpServletResponse response) { Cookie[] cookies = request.getCookies(); if ((cookies == null) || (cookies.length == 0)) { return null; } for (Cookie cookie : cookies) { if (ACEGI_SECURITY_HASHED_REMEMBER_ME_COOKIE_KEY.equals(cookie.getName())) { return cookie.getValue(); } } return null; }
[ "private", "String", "findRememberMeCookieValue", "(", "HttpServletRequest", "request", ",", "HttpServletResponse", "response", ")", "{", "Cookie", "[", "]", "cookies", "=", "request", ".", "getCookies", "(", ")", ";", "if", "(", "(", "cookies", "==", "null", ...
Patched version of the super.autoLogin with a time-independent equality check for the token validation
[ "Patched", "version", "of", "the", "super", ".", "autoLogin", "with", "a", "time", "-", "independent", "equality", "check", "for", "the", "token", "validation" ]
train
https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/security/TokenBasedRememberMeServices2.java#L185-L199
lucee/Lucee
core/src/main/java/lucee/runtime/type/scope/ScopeContext.java
ScopeContext.getClusterScope
public static Cluster getClusterScope(Config config, boolean create) throws PageException { if (cluster == null && create) { cluster = ((ConfigImpl) config).createClusterScope(); } return cluster; }
java
public static Cluster getClusterScope(Config config, boolean create) throws PageException { if (cluster == null && create) { cluster = ((ConfigImpl) config).createClusterScope(); } return cluster; }
[ "public", "static", "Cluster", "getClusterScope", "(", "Config", "config", ",", "boolean", "create", ")", "throws", "PageException", "{", "if", "(", "cluster", "==", "null", "&&", "create", ")", "{", "cluster", "=", "(", "(", "ConfigImpl", ")", "config", "...
Returns the current Cluster Scope, if there is no current Cluster Scope and create is true, returns a new Cluster Scope. If create is false and the request has no valid Cluster Scope, this method returns null. @param config @param create @return @throws PageException
[ "Returns", "the", "current", "Cluster", "Scope", "if", "there", "is", "no", "current", "Cluster", "Scope", "and", "create", "is", "true", "returns", "a", "new", "Cluster", "Scope", ".", "If", "create", "is", "false", "and", "the", "request", "has", "no", ...
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/type/scope/ScopeContext.java#L201-L207
Azure/azure-sdk-for-java
kusto/resource-manager/v2018_09_07_preview/src/main/java/com/microsoft/azure/management/kusto/v2018_09_07_preview/implementation/ClustersInner.java
ClustersInner.createOrUpdateAsync
public Observable<ClusterInner> createOrUpdateAsync(String resourceGroupName, String clusterName, ClusterInner parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, clusterName, parameters).map(new Func1<ServiceResponse<ClusterInner>, ClusterInner>() { @Override public ClusterInner call(ServiceResponse<ClusterInner> response) { return response.body(); } }); }
java
public Observable<ClusterInner> createOrUpdateAsync(String resourceGroupName, String clusterName, ClusterInner parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, clusterName, parameters).map(new Func1<ServiceResponse<ClusterInner>, ClusterInner>() { @Override public ClusterInner call(ServiceResponse<ClusterInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "ClusterInner", ">", "createOrUpdateAsync", "(", "String", "resourceGroupName", ",", "String", "clusterName", ",", "ClusterInner", "parameters", ")", "{", "return", "createOrUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "clus...
Create or update a Kusto cluster. @param resourceGroupName The name of the resource group containing the Kusto cluster. @param clusterName The name of the Kusto cluster. @param parameters The Kusto cluster parameters supplied to the CreateOrUpdate operation. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request
[ "Create", "or", "update", "a", "Kusto", "cluster", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/kusto/resource-manager/v2018_09_07_preview/src/main/java/com/microsoft/azure/management/kusto/v2018_09_07_preview/implementation/ClustersInner.java#L258-L265
sdaschner/jaxrs-analyzer
src/main/java/com/sebastian_daschner/jaxrs_analyzer/analysis/ProjectAnalyzer.java
ProjectAnalyzer.addToClassPool
private void addToClassPool(final Path location) { if (!location.toFile().exists()) throw new IllegalArgumentException("The location '" + location + "' does not exist!"); try { ContextClassReader.addClassPath(location.toUri().toURL()); } catch (Exception e) { throw new IllegalArgumentException("The location '" + location + "' could not be loaded to the class path!", e); } }
java
private void addToClassPool(final Path location) { if (!location.toFile().exists()) throw new IllegalArgumentException("The location '" + location + "' does not exist!"); try { ContextClassReader.addClassPath(location.toUri().toURL()); } catch (Exception e) { throw new IllegalArgumentException("The location '" + location + "' could not be loaded to the class path!", e); } }
[ "private", "void", "addToClassPool", "(", "final", "Path", "location", ")", "{", "if", "(", "!", "location", ".", "toFile", "(", ")", ".", "exists", "(", ")", ")", "throw", "new", "IllegalArgumentException", "(", "\"The location '\"", "+", "location", "+", ...
Adds the location to the class pool. @param location The location of a jar file or a directory
[ "Adds", "the", "location", "to", "the", "class", "pool", "." ]
train
https://github.com/sdaschner/jaxrs-analyzer/blob/4ac62942202d05632977d6c14d3cd7e2d27e2b9b/src/main/java/com/sebastian_daschner/jaxrs_analyzer/analysis/ProjectAnalyzer.java#L137-L145
ngageoint/geopackage-android-map
geopackage-map/src/main/java/mil/nga/geopackage/map/features/StyleUtils.java
StyleUtils.setStyle
public static boolean setStyle(PolylineOptions polylineOptions, StyleRow style, float density) { if (style != null) { Color color = style.getColorOrDefault(); polylineOptions.color(color.getColorWithAlpha()); double width = style.getWidthOrDefault(); polylineOptions.width((float) width * density); } return style != null; }
java
public static boolean setStyle(PolylineOptions polylineOptions, StyleRow style, float density) { if (style != null) { Color color = style.getColorOrDefault(); polylineOptions.color(color.getColorWithAlpha()); double width = style.getWidthOrDefault(); polylineOptions.width((float) width * density); } return style != null; }
[ "public", "static", "boolean", "setStyle", "(", "PolylineOptions", "polylineOptions", ",", "StyleRow", "style", ",", "float", "density", ")", "{", "if", "(", "style", "!=", "null", ")", "{", "Color", "color", "=", "style", ".", "getColorOrDefault", "(", ")",...
Set the style into the polyline options @param polylineOptions polyline options @param style style row @param density display density: {@link android.util.DisplayMetrics#density} @return true if style was set into the polyline options
[ "Set", "the", "style", "into", "the", "polyline", "options" ]
train
https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/features/StyleUtils.java#L465-L478
Omertron/api-themoviedb
src/main/java/com/omertron/themoviedbapi/tools/PostTools.java
PostTools.convertToJson
private String convertToJson(Map<String, ?> map) throws MovieDbException { try { return MAPPER.writeValueAsString(map); } catch (JsonProcessingException ex) { throw new MovieDbException(ApiExceptionType.MAPPING_FAILED, "JSON conversion failed", "", ex); } }
java
private String convertToJson(Map<String, ?> map) throws MovieDbException { try { return MAPPER.writeValueAsString(map); } catch (JsonProcessingException ex) { throw new MovieDbException(ApiExceptionType.MAPPING_FAILED, "JSON conversion failed", "", ex); } }
[ "private", "String", "convertToJson", "(", "Map", "<", "String", ",", "?", ">", "map", ")", "throws", "MovieDbException", "{", "try", "{", "return", "MAPPER", ".", "writeValueAsString", "(", "map", ")", ";", "}", "catch", "(", "JsonProcessingException", "ex"...
Use Jackson to convert Map to JSON string. @param map Map to convert to json @return json string @throws MovieDbException exception
[ "Use", "Jackson", "to", "convert", "Map", "to", "JSON", "string", "." ]
train
https://github.com/Omertron/api-themoviedb/blob/bf132d7c7271734e13b58ba3bc92bba46f220118/src/main/java/com/omertron/themoviedbapi/tools/PostTools.java#L68-L74
mnlipp/jgrapes
org.jgrapes.io/src/org/jgrapes/io/NioDispatcher.java
NioDispatcher.onStart
@Handler public void onStart(Start event) { synchronized (this) { if (runner != null && !runner.isInterrupted()) { return; } runner = new Thread(this, Components.simpleObjectName(this)); runner.start(); } }
java
@Handler public void onStart(Start event) { synchronized (this) { if (runner != null && !runner.isInterrupted()) { return; } runner = new Thread(this, Components.simpleObjectName(this)); runner.start(); } }
[ "@", "Handler", "public", "void", "onStart", "(", "Start", "event", ")", "{", "synchronized", "(", "this", ")", "{", "if", "(", "runner", "!=", "null", "&&", "!", "runner", ".", "isInterrupted", "(", ")", ")", "{", "return", ";", "}", "runner", "=", ...
Starts this dispatcher. A dispatcher has an associated thread that keeps it running. @param event the event
[ "Starts", "this", "dispatcher", ".", "A", "dispatcher", "has", "an", "associated", "thread", "that", "keeps", "it", "running", "." ]
train
https://github.com/mnlipp/jgrapes/blob/8b5d874935d84c34a52d3e3d3745e869b5203fa0/org.jgrapes.io/src/org/jgrapes/io/NioDispatcher.java#L60-L69
google/error-prone-javac
src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/HtmlTree.java
HtmlTree.SECTION
public static HtmlTree SECTION(Content body) { HtmlTree htmltree = new HtmlTree(HtmlTag.SECTION, nullCheck(body)); htmltree.setRole(Role.REGION); return htmltree; }
java
public static HtmlTree SECTION(Content body) { HtmlTree htmltree = new HtmlTree(HtmlTag.SECTION, nullCheck(body)); htmltree.setRole(Role.REGION); return htmltree; }
[ "public", "static", "HtmlTree", "SECTION", "(", "Content", "body", ")", "{", "HtmlTree", "htmltree", "=", "new", "HtmlTree", "(", "HtmlTag", ".", "SECTION", ",", "nullCheck", "(", "body", ")", ")", ";", "htmltree", ".", "setRole", "(", "Role", ".", "REGI...
Generates a SECTION tag with role attribute and some content. @param body content of the section tag @return an HtmlTree object for the SECTION tag
[ "Generates", "a", "SECTION", "tag", "with", "role", "attribute", "and", "some", "content", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/HtmlTree.java#L685-L689
baidubce/bce-sdk-java
src/main/java/com/baidubce/services/tsdb/model/Datapoint.java
Datapoint.addStringValue
public Datapoint addStringValue(long time, String value) { initialValues(); checkType(TsdbConstants.TYPE_STRING); values.add(Lists.<JsonNode> newArrayList(new LongNode(time), new TextNode(value))); return this; }
java
public Datapoint addStringValue(long time, String value) { initialValues(); checkType(TsdbConstants.TYPE_STRING); values.add(Lists.<JsonNode> newArrayList(new LongNode(time), new TextNode(value))); return this; }
[ "public", "Datapoint", "addStringValue", "(", "long", "time", ",", "String", "value", ")", "{", "initialValues", "(", ")", ";", "checkType", "(", "TsdbConstants", ".", "TYPE_STRING", ")", ";", "values", ".", "add", "(", "Lists", ".", "<", "JsonNode", ">", ...
Add datapoint of String type value. @param time datapoint's timestamp @param value datapoint's value @return Datapoint
[ "Add", "datapoint", "of", "String", "type", "value", "." ]
train
https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/services/tsdb/model/Datapoint.java#L140-L146
OpenLiberty/open-liberty
dev/com.ibm.ws.kernel.feature.cmdline/src/com/ibm/ws/kernel/feature/internal/generator/ManifestFileProcessor.java
ManifestFileProcessor.getBundleRepository
public ContentBasedLocalBundleRepository getBundleRepository(String featureName, WsLocationAdmin locService) { return BundleRepositoryRegistry.getRepositoryHolder(featureName).getBundleRepository(); }
java
public ContentBasedLocalBundleRepository getBundleRepository(String featureName, WsLocationAdmin locService) { return BundleRepositoryRegistry.getRepositoryHolder(featureName).getBundleRepository(); }
[ "public", "ContentBasedLocalBundleRepository", "getBundleRepository", "(", "String", "featureName", ",", "WsLocationAdmin", "locService", ")", "{", "return", "BundleRepositoryRegistry", ".", "getRepositoryHolder", "(", "featureName", ")", ".", "getBundleRepository", "(", ")...
Get bundle repository @param locService a location service @param msgs true if messages should be output to the log, false otherwise. @return a bundle repository
[ "Get", "bundle", "repository" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.kernel.feature.cmdline/src/com/ibm/ws/kernel/feature/internal/generator/ManifestFileProcessor.java#L502-L504
auth0/auth0-java
src/main/java/com/auth0/client/mgmt/filter/PageFilter.java
PageFilter.withPage
public PageFilter withPage(int pageNumber, int amountPerPage) { parameters.put("page", pageNumber); parameters.put("per_page", amountPerPage); return this; }
java
public PageFilter withPage(int pageNumber, int amountPerPage) { parameters.put("page", pageNumber); parameters.put("per_page", amountPerPage); return this; }
[ "public", "PageFilter", "withPage", "(", "int", "pageNumber", ",", "int", "amountPerPage", ")", "{", "parameters", ".", "put", "(", "\"page\"", ",", "pageNumber", ")", ";", "parameters", ".", "put", "(", "\"per_page\"", ",", "amountPerPage", ")", ";", "retur...
Filter by page @param pageNumber the page number to retrieve. @param amountPerPage the amount of items per page to retrieve. @return this filter instance
[ "Filter", "by", "page" ]
train
https://github.com/auth0/auth0-java/blob/b7bc099ee9c6cde5a87c4ecfebc6d811aeb1027c/src/main/java/com/auth0/client/mgmt/filter/PageFilter.java#L14-L18
brettonw/Bag
src/main/java/com/brettonw/bag/formats/MimeType.java
MimeType.getFromMimeType
public static String getFromMimeType (String mimeType, Supplier<String> notFound) { mimeType = mimeType.toLowerCase (); return mimeTypeRemappings.containsKey (mimeType) ? mimeTypeRemappings.get (mimeType) : notFound.get (); }
java
public static String getFromMimeType (String mimeType, Supplier<String> notFound) { mimeType = mimeType.toLowerCase (); return mimeTypeRemappings.containsKey (mimeType) ? mimeTypeRemappings.get (mimeType) : notFound.get (); }
[ "public", "static", "String", "getFromMimeType", "(", "String", "mimeType", ",", "Supplier", "<", "String", ">", "notFound", ")", "{", "mimeType", "=", "mimeType", ".", "toLowerCase", "(", ")", ";", "return", "mimeTypeRemappings", ".", "containsKey", "(", "mim...
Returns a mime type with a known format reader from the given mime type. Some MIME types are application or vendor specific examples that use a standard underlying format, like XML. There are also examples of synonym types, like "text/csv" and "application/csv" that we want to support.
[ "Returns", "a", "mime", "type", "with", "a", "known", "format", "reader", "from", "the", "given", "mime", "type", ".", "Some", "MIME", "types", "are", "application", "or", "vendor", "specific", "examples", "that", "use", "a", "standard", "underlying", "forma...
train
https://github.com/brettonw/Bag/blob/25c0ff74893b6c9a2c61bf0f97189ab82e0b2f56/src/main/java/com/brettonw/bag/formats/MimeType.java#L66-L69
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/service/db/DBService.java
DBService.getColumn
public DColumn getColumn(String storeName, String rowKey, String colName) { List<String> colNames = new ArrayList<String>(1); colNames.add(colName); List<DColumn> columns = getColumns(storeName, rowKey, colNames); if(columns.size() == 0) return null; else return columns.get(0); }
java
public DColumn getColumn(String storeName, String rowKey, String colName) { List<String> colNames = new ArrayList<String>(1); colNames.add(colName); List<DColumn> columns = getColumns(storeName, rowKey, colNames); if(columns.size() == 0) return null; else return columns.get(0); }
[ "public", "DColumn", "getColumn", "(", "String", "storeName", ",", "String", "rowKey", ",", "String", "colName", ")", "{", "List", "<", "String", ">", "colNames", "=", "new", "ArrayList", "<", "String", ">", "(", "1", ")", ";", "colNames", ".", "add", ...
Get a single column for a single row in the given store. If the given row or column is not found, null is returned. Otherwise, a {@link DColumn} containing the column name and value is returned. @param storeName Name of store to query. @param rowKey Key of row to read. @param colName Name of column to fetch. @return {@link DColumn} containing the column name and value or null if the row or column was not found.
[ "Get", "a", "single", "column", "for", "a", "single", "row", "in", "the", "given", "store", ".", "If", "the", "given", "row", "or", "column", "is", "not", "found", "null", "is", "returned", ".", "Otherwise", "a", "{", "@link", "DColumn", "}", "containi...
train
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/db/DBService.java#L274-L280
EdwardRaff/JSAT
JSAT/src/jsat/linear/Matrix.java
Matrix.getRowView
public Vec getRowView(final int r) { final Matrix M = this; return new Vec() { private static final long serialVersionUID = 8484494698777822563L; @Override public int length() { return M.cols(); } @Override public double get(int index) { return M.get(r, index); } @Override public void set(int index, double val) { M.set(r, index, val); } @Override public boolean isSparse() { return M.isSparce(); } @Override public Vec clone() { if(M.isSparce()) return new SparseVector(this); else return new DenseVector(this); } @Override public void setLength(int length) { throw new UnsupportedOperationException("Vector view can not extend original matrix"); } }; }
java
public Vec getRowView(final int r) { final Matrix M = this; return new Vec() { private static final long serialVersionUID = 8484494698777822563L; @Override public int length() { return M.cols(); } @Override public double get(int index) { return M.get(r, index); } @Override public void set(int index, double val) { M.set(r, index, val); } @Override public boolean isSparse() { return M.isSparce(); } @Override public Vec clone() { if(M.isSparce()) return new SparseVector(this); else return new DenseVector(this); } @Override public void setLength(int length) { throw new UnsupportedOperationException("Vector view can not extend original matrix"); } }; }
[ "public", "Vec", "getRowView", "(", "final", "int", "r", ")", "{", "final", "Matrix", "M", "=", "this", ";", "return", "new", "Vec", "(", ")", "{", "private", "static", "final", "long", "serialVersionUID", "=", "8484494698777822563L", ";", "@", "Override",...
Obtains a vector that is backed by <i>this</i>, at very little memory cost. Mutations to this vector will alter the values stored in the matrix, and vice versa. @param r the row to obtain a view of @return a vector backed by the specified row of the matrix
[ "Obtains", "a", "vector", "that", "is", "backed", "by", "<i", ">", "this<", "/", "i", ">", "at", "very", "little", "memory", "cost", ".", "Mutations", "to", "this", "vector", "will", "alter", "the", "values", "stored", "in", "the", "matrix", "and", "vi...
train
https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/linear/Matrix.java#L700-L746
Azure/azure-sdk-for-java
keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java
KeyVaultClientBaseImpl.restoreStorageAccount
public StorageBundle restoreStorageAccount(String vaultBaseUrl, byte[] storageBundleBackup) { return restoreStorageAccountWithServiceResponseAsync(vaultBaseUrl, storageBundleBackup).toBlocking().single().body(); }
java
public StorageBundle restoreStorageAccount(String vaultBaseUrl, byte[] storageBundleBackup) { return restoreStorageAccountWithServiceResponseAsync(vaultBaseUrl, storageBundleBackup).toBlocking().single().body(); }
[ "public", "StorageBundle", "restoreStorageAccount", "(", "String", "vaultBaseUrl", ",", "byte", "[", "]", "storageBundleBackup", ")", "{", "return", "restoreStorageAccountWithServiceResponseAsync", "(", "vaultBaseUrl", ",", "storageBundleBackup", ")", ".", "toBlocking", "...
Restores a backed up storage account to a vault. Restores a backed up storage account to a vault. This operation requires the storage/restore permission. @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. @param storageBundleBackup The backup blob associated with a storage account. @throws IllegalArgumentException thrown if parameters fail the validation @throws KeyVaultErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the StorageBundle object if successful.
[ "Restores", "a", "backed", "up", "storage", "account", "to", "a", "vault", ".", "Restores", "a", "backed", "up", "storage", "account", "to", "a", "vault", ".", "This", "operation", "requires", "the", "storage", "/", "restore", "permission", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java#L9608-L9610
MenoData/Time4J
base/src/main/java/net/time4j/engine/TimeAxis.java
TimeAxis.getRule
UnitRule<T> getRule(U unit) { if (unit == null) { throw new NullPointerException("Missing chronological unit."); } UnitRule<T> rule = this.unitRules.get(unit); if (rule == null) { if (unit instanceof BasicUnit) { rule = BasicUnit.class.cast(unit).derive(this); } if (rule == null) { throw new RuleNotFoundException(this, unit); } } return rule; }
java
UnitRule<T> getRule(U unit) { if (unit == null) { throw new NullPointerException("Missing chronological unit."); } UnitRule<T> rule = this.unitRules.get(unit); if (rule == null) { if (unit instanceof BasicUnit) { rule = BasicUnit.class.cast(unit).derive(this); } if (rule == null) { throw new RuleNotFoundException(this, unit); } } return rule; }
[ "UnitRule", "<", "T", ">", "getRule", "(", "U", "unit", ")", "{", "if", "(", "unit", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"Missing chronological unit.\"", ")", ";", "}", "UnitRule", "<", "T", ">", "rule", "=", "this", ...
<p>Liefert die chronologische Regel zur angegebenen Zeiteinheit. </p> @param unit time unit @return unit rule or {@code null} if not registered
[ "<p", ">", "Liefert", "die", "chronologische", "Regel", "zur", "angegebenen", "Zeiteinheit", ".", "<", "/", "p", ">" ]
train
https://github.com/MenoData/Time4J/blob/08b2eda6b2dbb140b92011cf7071bb087edd46a5/base/src/main/java/net/time4j/engine/TimeAxis.java#L555-L574
smartsheet-platform/smartsheet-java-sdk
src/main/java/com/smartsheet/api/internal/SheetResourcesImpl.java
SheetResourcesImpl.getSheetAsFile
private void getSheetAsFile(long id, PaperSize paperSize, OutputStream outputStream, String contentType) throws SmartsheetException { Util.throwIfNull(outputStream, contentType); String path = "sheets/" + id; if (paperSize != null) { path += "?paperSize=" + paperSize; } HttpRequest request; request = createHttpRequest(this.getSmartsheet().getBaseURI().resolve(path), HttpMethod.GET); request.getHeaders().put("Accept", contentType); com.smartsheet.api.internal.http.HttpResponse response = getSmartsheet().getHttpClient().request(request); switch (response.getStatusCode()) { case 200: try { copyStream(response.getEntity().getContent(), outputStream); } catch (IOException e) { throw new SmartsheetException(e); } break; default: handleError(response); } getSmartsheet().getHttpClient().releaseConnection(); }
java
private void getSheetAsFile(long id, PaperSize paperSize, OutputStream outputStream, String contentType) throws SmartsheetException { Util.throwIfNull(outputStream, contentType); String path = "sheets/" + id; if (paperSize != null) { path += "?paperSize=" + paperSize; } HttpRequest request; request = createHttpRequest(this.getSmartsheet().getBaseURI().resolve(path), HttpMethod.GET); request.getHeaders().put("Accept", contentType); com.smartsheet.api.internal.http.HttpResponse response = getSmartsheet().getHttpClient().request(request); switch (response.getStatusCode()) { case 200: try { copyStream(response.getEntity().getContent(), outputStream); } catch (IOException e) { throw new SmartsheetException(e); } break; default: handleError(response); } getSmartsheet().getHttpClient().releaseConnection(); }
[ "private", "void", "getSheetAsFile", "(", "long", "id", ",", "PaperSize", "paperSize", ",", "OutputStream", "outputStream", ",", "String", "contentType", ")", "throws", "SmartsheetException", "{", "Util", ".", "throwIfNull", "(", "outputStream", ",", "contentType", ...
Get a sheet as a file. Exceptions: - InvalidRequestException : if there is any problem with the REST API request - AuthorizationException : if there is any problem with the REST API authorization(access token) - ResourceNotFoundException : if the resource can not be found - ServiceUnavailableException : if the REST API service is not available (possibly due to rate limiting) - SmartsheetRestException : if there is any other REST API related error occurred during the operation - SmartsheetException : if there is any other error occurred during the operation @param id the id @param paperSize the paper size @param outputStream the OutputStream to which the Excel file will be written @param contentType the content type @return the sheet as file @throws SmartsheetException the smartsheet exception
[ "Get", "a", "sheet", "as", "a", "file", "." ]
train
https://github.com/smartsheet-platform/smartsheet-java-sdk/blob/f60e264412076271f83b65889ef9b891fad83df8/src/main/java/com/smartsheet/api/internal/SheetResourcesImpl.java#L987-L1015
looly/hutool
hutool-poi/src/main/java/cn/hutool/poi/excel/ExcelUtil.java
ExcelUtil.getReader
public static ExcelReader getReader(String bookFilePath, int sheetIndex) { try { return new ExcelReader(bookFilePath, sheetIndex); } catch (NoClassDefFoundError e) { throw new DependencyException(ObjectUtil.defaultIfNull(e.getCause(), e), PoiChecker.NO_POI_ERROR_MSG); } }
java
public static ExcelReader getReader(String bookFilePath, int sheetIndex) { try { return new ExcelReader(bookFilePath, sheetIndex); } catch (NoClassDefFoundError e) { throw new DependencyException(ObjectUtil.defaultIfNull(e.getCause(), e), PoiChecker.NO_POI_ERROR_MSG); } }
[ "public", "static", "ExcelReader", "getReader", "(", "String", "bookFilePath", ",", "int", "sheetIndex", ")", "{", "try", "{", "return", "new", "ExcelReader", "(", "bookFilePath", ",", "sheetIndex", ")", ";", "}", "catch", "(", "NoClassDefFoundError", "e", ")"...
获取Excel读取器,通过调用{@link ExcelReader}的read或readXXX方法读取Excel内容 @param bookFilePath Excel文件路径,绝对路径或相对于ClassPath路径 @param sheetIndex sheet序号,0表示第一个sheet @return {@link ExcelReader} @since 3.1.1
[ "获取Excel读取器,通过调用", "{", "@link", "ExcelReader", "}", "的read或readXXX方法读取Excel内容" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-poi/src/main/java/cn/hutool/poi/excel/ExcelUtil.java#L215-L221
apache/spark
sql/hive-thriftserver/src/main/java/org/apache/hive/service/cli/operation/MetadataOperation.java
MetadataOperation.convertSchemaPattern
protected String convertSchemaPattern(final String pattern) { if ((pattern == null) || pattern.isEmpty()) { return convertPattern("%", true); } else { return convertPattern(pattern, true); } }
java
protected String convertSchemaPattern(final String pattern) { if ((pattern == null) || pattern.isEmpty()) { return convertPattern("%", true); } else { return convertPattern(pattern, true); } }
[ "protected", "String", "convertSchemaPattern", "(", "final", "String", "pattern", ")", "{", "if", "(", "(", "pattern", "==", "null", ")", "||", "pattern", ".", "isEmpty", "(", ")", ")", "{", "return", "convertPattern", "(", "\"%\"", ",", "true", ")", ";"...
Convert wildchars and escape sequence of schema pattern from JDBC format to datanucleous/regex The schema pattern treats empty string also as wildchar
[ "Convert", "wildchars", "and", "escape", "sequence", "of", "schema", "pattern", "from", "JDBC", "format", "to", "datanucleous", "/", "regex", "The", "schema", "pattern", "treats", "empty", "string", "also", "as", "wildchar" ]
train
https://github.com/apache/spark/blob/25ee0474f47d9c30d6f553a7892d9549f91071cf/sql/hive-thriftserver/src/main/java/org/apache/hive/service/cli/operation/MetadataOperation.java#L76-L82
pmwmedia/tinylog
benchmarks/src/main/java/org/tinylog/benchmarks/api/WritingBenchmark.java
WritingBenchmark.byteBufferRandomAccessFile
@Benchmark @BenchmarkMode(Mode.AverageTime) public void byteBufferRandomAccessFile(final Configuration configuration) throws IOException { ByteBuffer buffer = ByteBuffer.allocate(BUFFER_CAPACITY); try (RandomAccessFile file = new RandomAccessFile(configuration.file, "rw")) { for (long i = 0; i < LINES; ++i) { if (buffer.remaining() < DATA.length) { file.write(buffer.array(), 0, buffer.position()); buffer.rewind(); } if (buffer.remaining() < DATA.length) { file.write(DATA); } else { buffer.put(DATA); } } if (buffer.position() > 0) { file.write(buffer.array(), 0, buffer.position()); } } }
java
@Benchmark @BenchmarkMode(Mode.AverageTime) public void byteBufferRandomAccessFile(final Configuration configuration) throws IOException { ByteBuffer buffer = ByteBuffer.allocate(BUFFER_CAPACITY); try (RandomAccessFile file = new RandomAccessFile(configuration.file, "rw")) { for (long i = 0; i < LINES; ++i) { if (buffer.remaining() < DATA.length) { file.write(buffer.array(), 0, buffer.position()); buffer.rewind(); } if (buffer.remaining() < DATA.length) { file.write(DATA); } else { buffer.put(DATA); } } if (buffer.position() > 0) { file.write(buffer.array(), 0, buffer.position()); } } }
[ "@", "Benchmark", "@", "BenchmarkMode", "(", "Mode", ".", "AverageTime", ")", "public", "void", "byteBufferRandomAccessFile", "(", "final", "Configuration", "configuration", ")", "throws", "IOException", "{", "ByteBuffer", "buffer", "=", "ByteBuffer", ".", "allocate...
Benchmarks writing via {@link RandomAccessFile} with using a {@link ByteBuffer} for buffering. @param configuration Configuration with target file @throws IOException Failed to write to target file
[ "Benchmarks", "writing", "via", "{", "@link", "RandomAccessFile", "}", "with", "using", "a", "{", "@link", "ByteBuffer", "}", "for", "buffering", "." ]
train
https://github.com/pmwmedia/tinylog/blob/d03d4ef84a1310155037e08ca8822a91697d1086/benchmarks/src/main/java/org/tinylog/benchmarks/api/WritingBenchmark.java#L184-L207
Red5/red5-server-common
src/main/java/org/red5/server/stream/SingleItemSubscriberStream.java
SingleItemSubscriberStream.createEngine
PlayEngine createEngine(ISchedulingService schedulingService, IConsumerService consumerService, IProviderService providerService) { engine = new PlayEngine.Builder(this, schedulingService, consumerService, providerService).build(); return engine; }
java
PlayEngine createEngine(ISchedulingService schedulingService, IConsumerService consumerService, IProviderService providerService) { engine = new PlayEngine.Builder(this, schedulingService, consumerService, providerService).build(); return engine; }
[ "PlayEngine", "createEngine", "(", "ISchedulingService", "schedulingService", ",", "IConsumerService", "consumerService", ",", "IProviderService", "providerService", ")", "{", "engine", "=", "new", "PlayEngine", ".", "Builder", "(", "this", ",", "schedulingService", ","...
Creates a play engine based on current services (scheduling service, consumer service, and provider service). This method is useful during unit testing.
[ "Creates", "a", "play", "engine", "based", "on", "current", "services", "(", "scheduling", "service", "consumer", "service", "and", "provider", "service", ")", ".", "This", "method", "is", "useful", "during", "unit", "testing", "." ]
train
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/stream/SingleItemSubscriberStream.java#L163-L166
rometools/rome
rome/src/main/java/com/rometools/rome/io/impl/DateParser.java
DateParser.parseW3CDateTime
public static Date parseW3CDateTime(String sDate, final Locale locale) { // if sDate has time on it, it injects 'GTM' before de TZ displacement to allow the // SimpleDateFormat parser to parse it properly final int tIndex = sDate.indexOf("T"); if (tIndex > -1) { if (sDate.endsWith("Z")) { sDate = sDate.substring(0, sDate.length() - 1) + "+00:00"; } int tzdIndex = sDate.indexOf("+", tIndex); if (tzdIndex == -1) { tzdIndex = sDate.indexOf("-", tIndex); } if (tzdIndex > -1) { String pre = sDate.substring(0, tzdIndex); final int secFraction = pre.indexOf(","); if (secFraction > -1) { pre = pre.substring(0, secFraction); } final String post = sDate.substring(tzdIndex); sDate = pre + "GMT" + post; } } else { sDate += "T00:00GMT"; } return parseUsingMask(W3CDATETIME_MASKS, sDate, locale); }
java
public static Date parseW3CDateTime(String sDate, final Locale locale) { // if sDate has time on it, it injects 'GTM' before de TZ displacement to allow the // SimpleDateFormat parser to parse it properly final int tIndex = sDate.indexOf("T"); if (tIndex > -1) { if (sDate.endsWith("Z")) { sDate = sDate.substring(0, sDate.length() - 1) + "+00:00"; } int tzdIndex = sDate.indexOf("+", tIndex); if (tzdIndex == -1) { tzdIndex = sDate.indexOf("-", tIndex); } if (tzdIndex > -1) { String pre = sDate.substring(0, tzdIndex); final int secFraction = pre.indexOf(","); if (secFraction > -1) { pre = pre.substring(0, secFraction); } final String post = sDate.substring(tzdIndex); sDate = pre + "GMT" + post; } } else { sDate += "T00:00GMT"; } return parseUsingMask(W3CDATETIME_MASKS, sDate, locale); }
[ "public", "static", "Date", "parseW3CDateTime", "(", "String", "sDate", ",", "final", "Locale", "locale", ")", "{", "// if sDate has time on it, it injects 'GTM' before de TZ displacement to allow the", "// SimpleDateFormat parser to parse it properly", "final", "int", "tIndex", ...
Parses a Date out of a String with a date in W3C date-time format. <p/> It parsers the following formats: <ul> <li>"yyyy-MM-dd'T'HH:mm:ssz"</li> <li>"yyyy-MM-dd'T'HH:mmz"</li> <li>"yyyy-MM-dd"</li> <li>"yyyy-MM"</li> <li>"yyyy"</li> </ul> <p/> Refer to the java.text.SimpleDateFormat javadocs for details on the format of each element. <p/> @param sDate string to parse for a date. @return the Date represented by the given W3C date-time string. It returns <b>null</b> if it was not possible to parse the given string into a Date.
[ "Parses", "a", "Date", "out", "of", "a", "String", "with", "a", "date", "in", "W3C", "date", "-", "time", "format", ".", "<p", "/", ">", "It", "parsers", "the", "following", "formats", ":", "<ul", ">", "<li", ">", "yyyy", "-", "MM", "-", "dd", "T...
train
https://github.com/rometools/rome/blob/5fcf0b1a9a6cdedbe253a45ad9468c54a0f97010/rome/src/main/java/com/rometools/rome/io/impl/DateParser.java#L193-L218
landawn/AbacusUtil
src/com/landawn/abacus/util/JdbcUtil.java
JdbcUtil.importData
public static int importData(final DataSet dataset, final int offset, final int count, final PreparedStatement stmt, final int batchSize, final int batchInterval, final Try.BiConsumer<? super PreparedStatement, ? super Object[], SQLException> stmtSetter) throws UncheckedSQLException { return importData(dataset, offset, count, Fn.alwaysTrue(), stmt, batchSize, batchInterval, stmtSetter); }
java
public static int importData(final DataSet dataset, final int offset, final int count, final PreparedStatement stmt, final int batchSize, final int batchInterval, final Try.BiConsumer<? super PreparedStatement, ? super Object[], SQLException> stmtSetter) throws UncheckedSQLException { return importData(dataset, offset, count, Fn.alwaysTrue(), stmt, batchSize, batchInterval, stmtSetter); }
[ "public", "static", "int", "importData", "(", "final", "DataSet", "dataset", ",", "final", "int", "offset", ",", "final", "int", "count", ",", "final", "PreparedStatement", "stmt", ",", "final", "int", "batchSize", ",", "final", "int", "batchInterval", ",", ...
Imports the data from <code>DataSet</code> to database. @param dataset @param columnTypeMap @param offset @param count @param stmt the column order in the sql must be consistent with the column order in the DataSet. @param filter @param stmtSetter @return @throws UncheckedSQLException
[ "Imports", "the", "data", "from", "<code", ">", "DataSet<", "/", "code", ">", "to", "database", "." ]
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/JdbcUtil.java#L2426-L2429
bmelnychuk/AndroidTreeView
library/src/main/java/com/unnamed/b/atv/view/TwoDScrollView.java
TwoDScrollView.findFocusableViewInMyBounds
private View findFocusableViewInMyBounds(final boolean topFocus, final int top, final boolean leftFocus, final int left, View preferredFocusable) { /* * The fading edge's transparent side should be considered for focus * since it's mostly visible, so we divide the actual fading edge length * by 2. */ final int verticalFadingEdgeLength = getVerticalFadingEdgeLength() / 2; final int topWithoutFadingEdge = top + verticalFadingEdgeLength; final int bottomWithoutFadingEdge = top + getHeight() - verticalFadingEdgeLength; final int horizontalFadingEdgeLength = getHorizontalFadingEdgeLength() / 2; final int leftWithoutFadingEdge = left + horizontalFadingEdgeLength; final int rightWithoutFadingEdge = left + getWidth() - horizontalFadingEdgeLength; if ((preferredFocusable != null) && (preferredFocusable.getTop() < bottomWithoutFadingEdge) && (preferredFocusable.getBottom() > topWithoutFadingEdge) && (preferredFocusable.getLeft() < rightWithoutFadingEdge) && (preferredFocusable.getRight() > leftWithoutFadingEdge)) { return preferredFocusable; } return findFocusableViewInBounds(topFocus, topWithoutFadingEdge, bottomWithoutFadingEdge, leftFocus, leftWithoutFadingEdge, rightWithoutFadingEdge); }
java
private View findFocusableViewInMyBounds(final boolean topFocus, final int top, final boolean leftFocus, final int left, View preferredFocusable) { /* * The fading edge's transparent side should be considered for focus * since it's mostly visible, so we divide the actual fading edge length * by 2. */ final int verticalFadingEdgeLength = getVerticalFadingEdgeLength() / 2; final int topWithoutFadingEdge = top + verticalFadingEdgeLength; final int bottomWithoutFadingEdge = top + getHeight() - verticalFadingEdgeLength; final int horizontalFadingEdgeLength = getHorizontalFadingEdgeLength() / 2; final int leftWithoutFadingEdge = left + horizontalFadingEdgeLength; final int rightWithoutFadingEdge = left + getWidth() - horizontalFadingEdgeLength; if ((preferredFocusable != null) && (preferredFocusable.getTop() < bottomWithoutFadingEdge) && (preferredFocusable.getBottom() > topWithoutFadingEdge) && (preferredFocusable.getLeft() < rightWithoutFadingEdge) && (preferredFocusable.getRight() > leftWithoutFadingEdge)) { return preferredFocusable; } return findFocusableViewInBounds(topFocus, topWithoutFadingEdge, bottomWithoutFadingEdge, leftFocus, leftWithoutFadingEdge, rightWithoutFadingEdge); }
[ "private", "View", "findFocusableViewInMyBounds", "(", "final", "boolean", "topFocus", ",", "final", "int", "top", ",", "final", "boolean", "leftFocus", ",", "final", "int", "left", ",", "View", "preferredFocusable", ")", "{", "/*\n * The fading edge's transparent s...
Finds the next focusable component that fits in this View's bounds (excluding fading edges) pretending that this View's top is located at the parameter top. @param topFocus look for a candidate is the one at the top of the bounds if topFocus is true, or at the bottom of the bounds if topFocus is false @param top the top offset of the bounds in which a focusable must be found (the fading edge is assumed to start at this position) @param preferredFocusable the View that has highest priority and will be returned if it is within my bounds (null is valid) @return the next focusable component in the bounds or null if none can be found
[ "Finds", "the", "next", "focusable", "component", "that", "fits", "in", "this", "View", "s", "bounds", "(", "excluding", "fading", "edges", ")", "pretending", "that", "this", "View", "s", "top", "is", "located", "at", "the", "parameter", "top", "." ]
train
https://github.com/bmelnychuk/AndroidTreeView/blob/d051ce75f5c9bd5206481808f6133b51f581c8f1/library/src/main/java/com/unnamed/b/atv/view/TwoDScrollView.java#L460-L481
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/utils/geometry/GeometryUtilities.java
GeometryUtilities.getSectionsFromCoordinates
public static List<LineString> getSectionsFromCoordinates( List<Coordinate> coordinates, double width ) { if (coordinates.size() < 3) { throw new IllegalArgumentException("This method works only on lines with at least 3 coordinates."); } double halfWidth = width / 2.0; List<LineString> linesList = new ArrayList<LineString>(); // first section Coordinate centerCoordinate = coordinates.get(0); LineSegment l1 = new LineSegment(centerCoordinate, coordinates.get(1)); Coordinate leftCoordinate = l1.pointAlongOffset(0.0, halfWidth); Coordinate rightCoordinate = l1.pointAlongOffset(0.0, -halfWidth); LineString lineString = geomFactory.createLineString(new Coordinate[]{leftCoordinate, centerCoordinate, rightCoordinate}); linesList.add(lineString); for( int i = 1; i < coordinates.size() - 1; i++ ) { Coordinate previous = coordinates.get(i - 1); Coordinate current = coordinates.get(i); Coordinate after = coordinates.get(i + 1); double firstAngle = azimuth(current, previous); double secondAngle = azimuth(current, after); double a1 = min(firstAngle, secondAngle); double a2 = max(firstAngle, secondAngle); double centerAngle = a1 + (a2 - a1) / 2.0; AffineTransformation rotationInstance = AffineTransformation.rotationInstance(-toRadians(centerAngle), current.x, current.y); LineString vertical = geomFactory.createLineString(new Coordinate[]{new Coordinate(current.x, current.y + halfWidth), current, new Coordinate(current.x, current.y - halfWidth)}); Geometry transformed = rotationInstance.transform(vertical); linesList.add((LineString) transformed); } // last section centerCoordinate = coordinates.get(coordinates.size() - 1); LineSegment l2 = new LineSegment(centerCoordinate, coordinates.get(coordinates.size() - 2)); leftCoordinate = l2.pointAlongOffset(0.0, halfWidth); rightCoordinate = l2.pointAlongOffset(0.0, -halfWidth); lineString = geomFactory.createLineString(new Coordinate[]{leftCoordinate, centerCoordinate, rightCoordinate}); linesList.add(lineString); return linesList; }
java
public static List<LineString> getSectionsFromCoordinates( List<Coordinate> coordinates, double width ) { if (coordinates.size() < 3) { throw new IllegalArgumentException("This method works only on lines with at least 3 coordinates."); } double halfWidth = width / 2.0; List<LineString> linesList = new ArrayList<LineString>(); // first section Coordinate centerCoordinate = coordinates.get(0); LineSegment l1 = new LineSegment(centerCoordinate, coordinates.get(1)); Coordinate leftCoordinate = l1.pointAlongOffset(0.0, halfWidth); Coordinate rightCoordinate = l1.pointAlongOffset(0.0, -halfWidth); LineString lineString = geomFactory.createLineString(new Coordinate[]{leftCoordinate, centerCoordinate, rightCoordinate}); linesList.add(lineString); for( int i = 1; i < coordinates.size() - 1; i++ ) { Coordinate previous = coordinates.get(i - 1); Coordinate current = coordinates.get(i); Coordinate after = coordinates.get(i + 1); double firstAngle = azimuth(current, previous); double secondAngle = azimuth(current, after); double a1 = min(firstAngle, secondAngle); double a2 = max(firstAngle, secondAngle); double centerAngle = a1 + (a2 - a1) / 2.0; AffineTransformation rotationInstance = AffineTransformation.rotationInstance(-toRadians(centerAngle), current.x, current.y); LineString vertical = geomFactory.createLineString(new Coordinate[]{new Coordinate(current.x, current.y + halfWidth), current, new Coordinate(current.x, current.y - halfWidth)}); Geometry transformed = rotationInstance.transform(vertical); linesList.add((LineString) transformed); } // last section centerCoordinate = coordinates.get(coordinates.size() - 1); LineSegment l2 = new LineSegment(centerCoordinate, coordinates.get(coordinates.size() - 2)); leftCoordinate = l2.pointAlongOffset(0.0, halfWidth); rightCoordinate = l2.pointAlongOffset(0.0, -halfWidth); lineString = geomFactory.createLineString(new Coordinate[]{leftCoordinate, centerCoordinate, rightCoordinate}); linesList.add(lineString); return linesList; }
[ "public", "static", "List", "<", "LineString", ">", "getSectionsFromCoordinates", "(", "List", "<", "Coordinate", ">", "coordinates", ",", "double", "width", ")", "{", "if", "(", "coordinates", ".", "size", "(", ")", "<", "3", ")", "{", "throw", "new", "...
Extracts traversal sections of a given with from the supplied {@link Coordinate}s. @param coordinates the list of coordinates. @param width the total with of the sections. @return the list of {@link LineString sections}.
[ "Extracts", "traversal", "sections", "of", "a", "given", "with", "from", "the", "supplied", "{", "@link", "Coordinate", "}", "s", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/geometry/GeometryUtilities.java#L490-L536
b3dgs/lionengine
lionengine-game/src/main/java/com/b3dgs/lionengine/game/Configurer.java
Configurer.getImplementation
public final <T> T getImplementation(ClassLoader loader, Class<T> type, Class<?>[] paramsType, Collection<?> paramsValue, String... path) { final String className = getText(path).trim(); return getImplementation(loader, type, paramsType, paramsValue, className); }
java
public final <T> T getImplementation(ClassLoader loader, Class<T> type, Class<?>[] paramsType, Collection<?> paramsValue, String... path) { final String className = getText(path).trim(); return getImplementation(loader, type, paramsType, paramsValue, className); }
[ "public", "final", "<", "T", ">", "T", "getImplementation", "(", "ClassLoader", "loader", ",", "Class", "<", "T", ">", "type", ",", "Class", "<", "?", ">", "[", "]", "paramsType", ",", "Collection", "<", "?", ">", "paramsValue", ",", "String", "...", ...
Get the class implementation from its name by using a custom constructor. @param <T> The instance type. @param loader The class loader to use. @param type The class type. @param paramsType The parameters type. @param paramsValue The parameters value. @param path The node path. @return The typed class instance. @throws LionEngineException If invalid class.
[ "Get", "the", "class", "implementation", "from", "its", "name", "by", "using", "a", "custom", "constructor", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/Configurer.java#L365-L373
hubrick/vertx-rest-client
src/main/java/com/hubrick/vertx/rest/MediaType.java
MediaType.parseMediaType
public static MediaType parseMediaType(String mediaType) { MimeType type; try { type = MimeTypeUtils.parseMimeType(mediaType); } catch (InvalidMimeTypeException ex) { throw new InvalidMediaTypeException(ex); } try { return new MediaType(type.getType(), type.getSubtype(), type.getParameters()); } catch (IllegalArgumentException ex) { throw new InvalidMediaTypeException(mediaType, ex.getMessage()); } }
java
public static MediaType parseMediaType(String mediaType) { MimeType type; try { type = MimeTypeUtils.parseMimeType(mediaType); } catch (InvalidMimeTypeException ex) { throw new InvalidMediaTypeException(ex); } try { return new MediaType(type.getType(), type.getSubtype(), type.getParameters()); } catch (IllegalArgumentException ex) { throw new InvalidMediaTypeException(mediaType, ex.getMessage()); } }
[ "public", "static", "MediaType", "parseMediaType", "(", "String", "mediaType", ")", "{", "MimeType", "type", ";", "try", "{", "type", "=", "MimeTypeUtils", ".", "parseMimeType", "(", "mediaType", ")", ";", "}", "catch", "(", "InvalidMimeTypeException", "ex", "...
Parse the given String into a single {@code MediaType}. @param mediaType the string to parse @return the media type @throws InvalidMediaTypeException if the string cannot be parsed
[ "Parse", "the", "given", "String", "into", "a", "single", "{", "@code", "MediaType", "}", "." ]
train
https://github.com/hubrick/vertx-rest-client/blob/4e6715bc2fb031555fc635adbf94a53b9cfba81e/src/main/java/com/hubrick/vertx/rest/MediaType.java#L357-L369
sagiegurari/fax4j
src/main/java/org/fax4j/common/SimpleLogger.java
SimpleLogger.logImpl
@Override protected void logImpl(LogLevel level,Object[] message,Throwable throwable) { //format log message String text=this.formatLogMessage(level,message,throwable); //print text to system out System.out.println(text); }
java
@Override protected void logImpl(LogLevel level,Object[] message,Throwable throwable) { //format log message String text=this.formatLogMessage(level,message,throwable); //print text to system out System.out.println(text); }
[ "@", "Override", "protected", "void", "logImpl", "(", "LogLevel", "level", ",", "Object", "[", "]", "message", ",", "Throwable", "throwable", ")", "{", "//format log message", "String", "text", "=", "this", ".", "formatLogMessage", "(", "level", ",", "message"...
Logs the provided data. @param level The log level @param message The message parts (may be null) @param throwable The error (may be null)
[ "Logs", "the", "provided", "data", "." ]
train
https://github.com/sagiegurari/fax4j/blob/42fa51acabe7bf279e27ab3dd1cf76146b27955f/src/main/java/org/fax4j/common/SimpleLogger.java#L31-L39
ahome-it/lienzo-core
src/main/java/com/ait/lienzo/client/core/shape/Viewport.java
Viewport.setPixelSize
public final Viewport setPixelSize(final int wide, final int high) { m_wide = wide; m_high = high; getElement().getStyle().setWidth(wide, Unit.PX); getElement().getStyle().setHeight(high, Unit.PX); final NFastArrayList<Scene> scenes = getChildNodes(); if (null != scenes) { final int size = scenes.size(); for (int i = 0; i < size; i++) { final Scene scene = scenes.get(i); if (null != scene) { scene.setPixelSize(wide, high); } } } m_spad.setPixelSize(wide, high); return this; }
java
public final Viewport setPixelSize(final int wide, final int high) { m_wide = wide; m_high = high; getElement().getStyle().setWidth(wide, Unit.PX); getElement().getStyle().setHeight(high, Unit.PX); final NFastArrayList<Scene> scenes = getChildNodes(); if (null != scenes) { final int size = scenes.size(); for (int i = 0; i < size; i++) { final Scene scene = scenes.get(i); if (null != scene) { scene.setPixelSize(wide, high); } } } m_spad.setPixelSize(wide, high); return this; }
[ "public", "final", "Viewport", "setPixelSize", "(", "final", "int", "wide", ",", "final", "int", "high", ")", "{", "m_wide", "=", "wide", ";", "m_high", "=", "high", ";", "getElement", "(", ")", ".", "getStyle", "(", ")", ".", "setWidth", "(", "wide", ...
Sets size of the {@link Viewport} in pixels @param wide @param high @return Viewpor this viewport
[ "Sets", "size", "of", "the", "{", "@link", "Viewport", "}", "in", "pixels" ]
train
https://github.com/ahome-it/lienzo-core/blob/8e03723700dec366f77064d12fb8676d8cd6be99/src/main/java/com/ait/lienzo/client/core/shape/Viewport.java#L228-L257
intuit/QuickBooks-V3-Java-SDK
ipp-v3-java-devkit/src/main/java/com/intuit/ipp/services/DataService.java
DataService.findByIdAsync
public <T extends IEntity> void findByIdAsync(T entity, CallbackHandler callbackHandler) throws FMSException { IntuitMessage intuitMessage = prepareFindById(entity); //set callback handler intuitMessage.getRequestElements().setCallbackHandler(callbackHandler); //execute async interceptors executeAsyncInterceptors(intuitMessage); }
java
public <T extends IEntity> void findByIdAsync(T entity, CallbackHandler callbackHandler) throws FMSException { IntuitMessage intuitMessage = prepareFindById(entity); //set callback handler intuitMessage.getRequestElements().setCallbackHandler(callbackHandler); //execute async interceptors executeAsyncInterceptors(intuitMessage); }
[ "public", "<", "T", "extends", "IEntity", ">", "void", "findByIdAsync", "(", "T", "entity", ",", "CallbackHandler", "callbackHandler", ")", "throws", "FMSException", "{", "IntuitMessage", "intuitMessage", "=", "prepareFindById", "(", "entity", ")", ";", "//set cal...
Method to find the record for the given id for the corresponding entity in asynchronous fashion @param entity the entity @param callbackHandler the callback handler @throws FMSException
[ "Method", "to", "find", "the", "record", "for", "the", "given", "id", "for", "the", "corresponding", "entity", "in", "asynchronous", "fashion" ]
train
https://github.com/intuit/QuickBooks-V3-Java-SDK/blob/59f988d0776d46620d0b34711c411b2b5b1da06b/ipp-v3-java-devkit/src/main/java/com/intuit/ipp/services/DataService.java#L819-L828
burberius/eve-esi
src/main/java/net/troja/eve/esi/api/CorporationApi.java
CorporationApi.getCorporationsCorporationId
public CorporationResponse getCorporationsCorporationId(Integer corporationId, String datasource, String ifNoneMatch) throws ApiException { ApiResponse<CorporationResponse> resp = getCorporationsCorporationIdWithHttpInfo(corporationId, datasource, ifNoneMatch); return resp.getData(); }
java
public CorporationResponse getCorporationsCorporationId(Integer corporationId, String datasource, String ifNoneMatch) throws ApiException { ApiResponse<CorporationResponse> resp = getCorporationsCorporationIdWithHttpInfo(corporationId, datasource, ifNoneMatch); return resp.getData(); }
[ "public", "CorporationResponse", "getCorporationsCorporationId", "(", "Integer", "corporationId", ",", "String", "datasource", ",", "String", "ifNoneMatch", ")", "throws", "ApiException", "{", "ApiResponse", "<", "CorporationResponse", ">", "resp", "=", "getCorporationsCo...
Get corporation information Public information about a corporation --- This route is cached for up to 3600 seconds @param corporationId An EVE corporation ID (required) @param datasource The server name you would like data from (optional, default to tranquility) @param ifNoneMatch ETag from a previous request. A 304 will be returned if this matches the current ETag (optional) @return CorporationResponse @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
[ "Get", "corporation", "information", "Public", "information", "about", "a", "corporation", "---", "This", "route", "is", "cached", "for", "up", "to", "3600", "seconds" ]
train
https://github.com/burberius/eve-esi/blob/24a941c592cfc15f23471ef849b282fbc582ca13/src/main/java/net/troja/eve/esi/api/CorporationApi.java#L159-L164
Axway/Grapes
utils/src/main/java/org/axway/grapes/utils/client/GrapesClient.java
GrapesClient.deleteArtifact
public void deleteArtifact(final String gavc, final String user, final String password) throws GrapesCommunicationException, AuthenticationException{ final Client client = getClient(user, password); final WebResource resource = client.resource(serverURL).path(RequestUtils.getArtifactPath(gavc)); final ClientResponse response = resource.delete(ClientResponse.class); client.destroy(); if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){ final String message = "Failed to DELETE artifact " + gavc; if(LOG.isErrorEnabled()) { LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus())); } throw new GrapesCommunicationException(message, response.getStatus()); } }
java
public void deleteArtifact(final String gavc, final String user, final String password) throws GrapesCommunicationException, AuthenticationException{ final Client client = getClient(user, password); final WebResource resource = client.resource(serverURL).path(RequestUtils.getArtifactPath(gavc)); final ClientResponse response = resource.delete(ClientResponse.class); client.destroy(); if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){ final String message = "Failed to DELETE artifact " + gavc; if(LOG.isErrorEnabled()) { LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus())); } throw new GrapesCommunicationException(message, response.getStatus()); } }
[ "public", "void", "deleteArtifact", "(", "final", "String", "gavc", ",", "final", "String", "user", ",", "final", "String", "password", ")", "throws", "GrapesCommunicationException", ",", "AuthenticationException", "{", "final", "Client", "client", "=", "getClient",...
Delete an artifact in the Grapes server @param gavc @throws GrapesCommunicationException @throws javax.naming.AuthenticationException
[ "Delete", "an", "artifact", "in", "the", "Grapes", "server" ]
train
https://github.com/Axway/Grapes/blob/ce9cc73d85f83eaa5fbc991abb593915a8c8374e/utils/src/main/java/org/axway/grapes/utils/client/GrapesClient.java#L440-L453
dbracewell/hermes
hermes-core/src/main/java/com/davidbracewell/hermes/corpus/processing/ProcessorContext.java
ProcessorContext.getString
public String getString(String name, String defaultValue) { return getAs(name, String.class, defaultValue); }
java
public String getString(String name, String defaultValue) { return getAs(name, String.class, defaultValue); }
[ "public", "String", "getString", "(", "String", "name", ",", "String", "defaultValue", ")", "{", "return", "getAs", "(", "name", ",", "String", ".", "class", ",", "defaultValue", ")", ";", "}" ]
Gets string. @param name the name @param defaultValue the default value @return the string
[ "Gets", "string", "." ]
train
https://github.com/dbracewell/hermes/blob/9ebefe7ad5dea1b731ae6931a30771eb75325ea3/hermes-core/src/main/java/com/davidbracewell/hermes/corpus/processing/ProcessorContext.java#L152-L154
twitter/finagle
finagle-serversets/src/main/java/com/twitter/finagle/common/util/BackoffHelper.java
BackoffHelper.doUntilResult
public <T, E extends Exception> T doUntilResult(ExceptionalSupplier<T, E> task) throws InterruptedException, BackoffStoppedException, E { T result = task.get(); // give an immediate try return (result != null) ? result : retryWork(task); }
java
public <T, E extends Exception> T doUntilResult(ExceptionalSupplier<T, E> task) throws InterruptedException, BackoffStoppedException, E { T result = task.get(); // give an immediate try return (result != null) ? result : retryWork(task); }
[ "public", "<", "T", ",", "E", "extends", "Exception", ">", "T", "doUntilResult", "(", "ExceptionalSupplier", "<", "T", ",", "E", ">", "task", ")", "throws", "InterruptedException", ",", "BackoffStoppedException", ",", "E", "{", "T", "result", "=", "task", ...
Executes the given task using the configured backoff strategy until the task succeeds as indicated by returning a non-null value. @param task the retryable task to execute until success @return the result of the successfully executed task @throws InterruptedException if interrupted while waiting for the task to execute successfully @throws BackoffStoppedException if the backoff stopped unsuccessfully @throws E if the task throws
[ "Executes", "the", "given", "task", "using", "the", "configured", "backoff", "strategy", "until", "the", "task", "succeeds", "as", "indicated", "by", "returning", "a", "non", "-", "null", "value", "." ]
train
https://github.com/twitter/finagle/blob/872be5f2b147fa50351bdbf08b003a26745e1df8/finagle-serversets/src/main/java/com/twitter/finagle/common/util/BackoffHelper.java#L118-L122
hankcs/HanLP
src/main/java/com/hankcs/hanlp/model/perceptron/model/LinearModel.java
LinearModel.save
public void save(String modelFile, Set<Map.Entry<String, Integer>> featureIdSet, final double ratio, boolean text) throws IOException { float[] parameter = this.parameter; this.compress(ratio, 1e-3f); DataOutputStream out = new DataOutputStream(new BufferedOutputStream(IOUtil.newOutputStream(modelFile))); save(out); out.close(); if (text) { BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(IOUtil.newOutputStream(modelFile + ".txt"), "UTF-8")); TagSet tagSet = featureMap.tagSet; for (Map.Entry<String, Integer> entry : featureIdSet) { bw.write(entry.getKey()); if (featureIdSet.size() == parameter.length) { bw.write("\t"); bw.write(String.valueOf(parameter[entry.getValue()])); } else { for (int i = 0; i < tagSet.size(); ++i) { bw.write("\t"); bw.write(String.valueOf(parameter[entry.getValue() * tagSet.size() + i])); } } bw.newLine(); } bw.close(); } }
java
public void save(String modelFile, Set<Map.Entry<String, Integer>> featureIdSet, final double ratio, boolean text) throws IOException { float[] parameter = this.parameter; this.compress(ratio, 1e-3f); DataOutputStream out = new DataOutputStream(new BufferedOutputStream(IOUtil.newOutputStream(modelFile))); save(out); out.close(); if (text) { BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(IOUtil.newOutputStream(modelFile + ".txt"), "UTF-8")); TagSet tagSet = featureMap.tagSet; for (Map.Entry<String, Integer> entry : featureIdSet) { bw.write(entry.getKey()); if (featureIdSet.size() == parameter.length) { bw.write("\t"); bw.write(String.valueOf(parameter[entry.getValue()])); } else { for (int i = 0; i < tagSet.size(); ++i) { bw.write("\t"); bw.write(String.valueOf(parameter[entry.getValue() * tagSet.size() + i])); } } bw.newLine(); } bw.close(); } }
[ "public", "void", "save", "(", "String", "modelFile", ",", "Set", "<", "Map", ".", "Entry", "<", "String", ",", "Integer", ">", ">", "featureIdSet", ",", "final", "double", "ratio", ",", "boolean", "text", ")", "throws", "IOException", "{", "float", "[",...
保存 @param modelFile 路径 @param featureIdSet 特征集(有些数据结构不支持遍历,可以提供构造时用到的特征集来规避这个缺陷) @param ratio 压缩比 @param text 是否输出文本以供调试 @throws IOException
[ "保存" ]
train
https://github.com/hankcs/HanLP/blob/a538d0722ab2e4980a9dcd9ea40324fc3ddba7ce/src/main/java/com/hankcs/hanlp/model/perceptron/model/LinearModel.java#L193-L226
OpenBEL/openbel-framework
org.openbel.framework.core/src/main/java/org/openbel/framework/core/compiler/SemanticServiceImpl.java
SemanticServiceImpl.pruneStatement
private void pruneStatement(final Statement stmt, final Document doc) { final List<StatementGroup> stmtgroups = doc.getAllStatementGroups(); for (final StatementGroup stmtgroup : stmtgroups) { final Iterator<Statement> sgi = stmtgroup.getStatements() .iterator(); while (sgi.hasNext()) { final Statement sgs = sgi.next(); if (stmt.equals(sgs)) { // prune sgi.remove(); return; } } } }
java
private void pruneStatement(final Statement stmt, final Document doc) { final List<StatementGroup> stmtgroups = doc.getAllStatementGroups(); for (final StatementGroup stmtgroup : stmtgroups) { final Iterator<Statement> sgi = stmtgroup.getStatements() .iterator(); while (sgi.hasNext()) { final Statement sgs = sgi.next(); if (stmt.equals(sgs)) { // prune sgi.remove(); return; } } } }
[ "private", "void", "pruneStatement", "(", "final", "Statement", "stmt", ",", "final", "Document", "doc", ")", "{", "final", "List", "<", "StatementGroup", ">", "stmtgroups", "=", "doc", ".", "getAllStatementGroups", "(", ")", ";", "for", "(", "final", "State...
Prunes the provided {@link Statement statement} from the {@link Document document}.
[ "Prunes", "the", "provided", "{" ]
train
https://github.com/OpenBEL/openbel-framework/blob/149f80b1d6eabb15ab15815b6f745b0afa9fd2d3/org.openbel.framework.core/src/main/java/org/openbel/framework/core/compiler/SemanticServiceImpl.java#L320-L334
apache/groovy
subprojects/groovy-xml/src/main/java/groovy/util/XmlParser.java
XmlParser.getElementName
protected Object getElementName(String namespaceURI, String localName, String qName) { String name = localName; String prefix = ""; if ((name == null) || (name.length() < 1)) { name = qName; } if (namespaceURI == null || namespaceURI.length() <= 0) { return name; } if (qName != null && qName.length() > 0 && namespaceAware) { int index = qName.lastIndexOf(":"); if (index > 0) { prefix = qName.substring(0, index); } } return new QName(namespaceURI, name, prefix); }
java
protected Object getElementName(String namespaceURI, String localName, String qName) { String name = localName; String prefix = ""; if ((name == null) || (name.length() < 1)) { name = qName; } if (namespaceURI == null || namespaceURI.length() <= 0) { return name; } if (qName != null && qName.length() > 0 && namespaceAware) { int index = qName.lastIndexOf(":"); if (index > 0) { prefix = qName.substring(0, index); } } return new QName(namespaceURI, name, prefix); }
[ "protected", "Object", "getElementName", "(", "String", "namespaceURI", ",", "String", "localName", ",", "String", "qName", ")", "{", "String", "name", "=", "localName", ";", "String", "prefix", "=", "\"\"", ";", "if", "(", "(", "name", "==", "null", ")", ...
Return a name given the namespaceURI, localName and qName. @param namespaceURI the namespace URI @param localName the local name @param qName the qualified name @return the newly created representation of the name
[ "Return", "a", "name", "given", "the", "namespaceURI", "localName", "and", "qName", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-xml/src/main/java/groovy/util/XmlParser.java#L485-L501
apache/fluo-recipes
modules/accumulo/src/main/java/org/apache/fluo/recipes/accumulo/ops/TableOperations.java
TableOperations.optimizeTable
public static void optimizeTable(FluoConfiguration fluoConfig, TableOptimizations tableOptim) throws Exception { Connector conn = getConnector(fluoConfig); TreeSet<Text> splits = new TreeSet<>(); for (Bytes split : tableOptim.getSplits()) { splits.add(new Text(split.toArray())); } String table = fluoConfig.getAccumuloTable(); conn.tableOperations().addSplits(table, splits); if (tableOptim.getTabletGroupingRegex() != null && !tableOptim.getTabletGroupingRegex().isEmpty()) { // was going to call : // conn.instanceOperations().testClassLoad(RGB_CLASS, TABLET_BALANCER_CLASS) // but that failed. See ACCUMULO-4068 try { // setting this prop first intentionally because it should fail in 1.6 conn.tableOperations().setProperty(table, RGB_PATTERN_PROP, tableOptim.getTabletGroupingRegex()); conn.tableOperations().setProperty(table, RGB_DEFAULT_PROP, "none"); conn.tableOperations().setProperty(table, TABLE_BALANCER_PROP, RGB_CLASS); } catch (AccumuloException e) { logger.warn("Unable to setup regex balancer (this is expected to fail in Accumulo 1.6.X) : " + e.getMessage()); logger.debug("Unable to setup regex balancer (this is expected to fail in Accumulo 1.6.X)", e); } } }
java
public static void optimizeTable(FluoConfiguration fluoConfig, TableOptimizations tableOptim) throws Exception { Connector conn = getConnector(fluoConfig); TreeSet<Text> splits = new TreeSet<>(); for (Bytes split : tableOptim.getSplits()) { splits.add(new Text(split.toArray())); } String table = fluoConfig.getAccumuloTable(); conn.tableOperations().addSplits(table, splits); if (tableOptim.getTabletGroupingRegex() != null && !tableOptim.getTabletGroupingRegex().isEmpty()) { // was going to call : // conn.instanceOperations().testClassLoad(RGB_CLASS, TABLET_BALANCER_CLASS) // but that failed. See ACCUMULO-4068 try { // setting this prop first intentionally because it should fail in 1.6 conn.tableOperations().setProperty(table, RGB_PATTERN_PROP, tableOptim.getTabletGroupingRegex()); conn.tableOperations().setProperty(table, RGB_DEFAULT_PROP, "none"); conn.tableOperations().setProperty(table, TABLE_BALANCER_PROP, RGB_CLASS); } catch (AccumuloException e) { logger.warn("Unable to setup regex balancer (this is expected to fail in Accumulo 1.6.X) : " + e.getMessage()); logger.debug("Unable to setup regex balancer (this is expected to fail in Accumulo 1.6.X)", e); } } }
[ "public", "static", "void", "optimizeTable", "(", "FluoConfiguration", "fluoConfig", ",", "TableOptimizations", "tableOptim", ")", "throws", "Exception", "{", "Connector", "conn", "=", "getConnector", "(", "fluoConfig", ")", ";", "TreeSet", "<", "Text", ">", "spli...
Make the requested table optimizations. @param fluoConfig should contain information need to connect to Accumulo and name of Fluo table @param tableOptim Will perform these optimizations on Fluo table in Accumulo.
[ "Make", "the", "requested", "table", "optimizations", "." ]
train
https://github.com/apache/fluo-recipes/blob/24c11234c9654b16d999437ff49ddc3db86665f8/modules/accumulo/src/main/java/org/apache/fluo/recipes/accumulo/ops/TableOperations.java#L70-L102
xiancloud/xian
xian-core/src/main/java/info/xiancloud/core/support/cache/api/CacheListUtil.java
CacheListUtil.addAll
public static Single<Boolean> addAll(String cacheKey, List list) { return addAll(CacheService.CACHE_CONFIG_BEAN, cacheKey, list); }
java
public static Single<Boolean> addAll(String cacheKey, List list) { return addAll(CacheService.CACHE_CONFIG_BEAN, cacheKey, list); }
[ "public", "static", "Single", "<", "Boolean", ">", "addAll", "(", "String", "cacheKey", ",", "List", "list", ")", "{", "return", "addAll", "(", "CacheService", ".", "CACHE_CONFIG_BEAN", ",", "cacheKey", ",", "list", ")", ";", "}" ]
Add a list of elements to the end of the cached list. @param cacheKey the key for the cached list. @param list the list of elements to be added. @return true on success, false on failure.
[ "Add", "a", "list", "of", "elements", "to", "the", "end", "of", "the", "cached", "list", "." ]
train
https://github.com/xiancloud/xian/blob/1948e088545553d2745b2c86d8b5a64988bb850e/xian-core/src/main/java/info/xiancloud/core/support/cache/api/CacheListUtil.java#L158-L160
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/dimensionalityreduction/RandomProjection.java
RandomProjection.johnsonLindenstraussMinDim
public static List<Integer> johnsonLindenstraussMinDim(int[] n, double... eps){ Boolean basicCheck = n == null || n.length == 0 || eps == null || eps.length == 0; if (basicCheck) throw new IllegalArgumentException("Johnson-Lindenstrauss dimension estimation requires > 0 components and at least a relative error"); for (double epsilon: eps){ if (epsilon <= 0 || epsilon >= 1) { throw new IllegalArgumentException("A relative error should be in ]0, 1["); } } List<Integer> res = new ArrayList(n.length * eps.length); for (double epsilon : eps){ double denom = (Math.pow(epsilon, 2) / 2 - Math.pow(epsilon, 3) / 3); for (int components: n){ res.add((int) (4 * Math.log(components) / denom)); } } return res; }
java
public static List<Integer> johnsonLindenstraussMinDim(int[] n, double... eps){ Boolean basicCheck = n == null || n.length == 0 || eps == null || eps.length == 0; if (basicCheck) throw new IllegalArgumentException("Johnson-Lindenstrauss dimension estimation requires > 0 components and at least a relative error"); for (double epsilon: eps){ if (epsilon <= 0 || epsilon >= 1) { throw new IllegalArgumentException("A relative error should be in ]0, 1["); } } List<Integer> res = new ArrayList(n.length * eps.length); for (double epsilon : eps){ double denom = (Math.pow(epsilon, 2) / 2 - Math.pow(epsilon, 3) / 3); for (int components: n){ res.add((int) (4 * Math.log(components) / denom)); } } return res; }
[ "public", "static", "List", "<", "Integer", ">", "johnsonLindenstraussMinDim", "(", "int", "[", "]", "n", ",", "double", "...", "eps", ")", "{", "Boolean", "basicCheck", "=", "n", "==", "null", "||", "n", ".", "length", "==", "0", "||", "eps", "==", ...
Find a safe number of components to project this to, through the Johnson-Lindenstrauss lemma The minimum number n' of components to guarantee the eps-embedding is given by: n' >= 4 log(n) / (eps² / 2 - eps³ / 3) see http://cseweb.ucsd.edu/~dasgupta/papers/jl.pdf §2.1 @param n Number of samples. If an array is given, it will compute a safe number of components array-wise. @param eps Maximum distortion rate as defined by the Johnson-Lindenstrauss lemma. Will compute array-wise if an array is given. @return
[ "Find", "a", "safe", "number", "of", "components", "to", "project", "this", "to", "through", "the", "Johnson", "-", "Lindenstrauss", "lemma", "The", "minimum", "number", "n", "of", "components", "to", "guarantee", "the", "eps", "-", "embedding", "is", "given...
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/dimensionalityreduction/RandomProjection.java#L76-L93
UrielCh/ovh-java-sdk
ovh-java-sdk-dedicatedCloud/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedCloud.java
ApiOvhDedicatedCloud.location_pccZone_GET
public OvhPccZone location_pccZone_GET(String pccZone) throws IOException { String qPath = "/dedicatedCloud/location/{pccZone}"; StringBuilder sb = path(qPath, pccZone); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhPccZone.class); }
java
public OvhPccZone location_pccZone_GET(String pccZone) throws IOException { String qPath = "/dedicatedCloud/location/{pccZone}"; StringBuilder sb = path(qPath, pccZone); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhPccZone.class); }
[ "public", "OvhPccZone", "location_pccZone_GET", "(", "String", "pccZone", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/dedicatedCloud/location/{pccZone}\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "pccZone", ")", ";", "String", ...
Get this object properties REST: GET /dedicatedCloud/location/{pccZone} @param pccZone [required] Name of pccZone
[ "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#L3094-L3099
alkacon/opencms-core
src-gwt/org/opencms/ugc/client/export/CmsClientUgcSession.java
CmsClientUgcSession.saveContent
public void saveContent( JavaScriptObject newValues, final I_CmsStringCallback onSuccess, final I_CmsErrorCallback onFailure) { m_apiRoot.getRpcHelper().executeRpc( CmsXmlContentUgcApi.SERVICE.saveContent( m_content.getSessionId(), CmsJsUtils.convertJsObjectToMap(newValues), new AsyncCallback<Map<String, String>>() { @SuppressWarnings("synthetic-access") public void onFailure(Throwable caught) { CmsUgcException formException = (CmsUgcException)caught; m_apiRoot.handleError(formException, onFailure); } public void onSuccess(Map<String, String> result) { if ((result == null) || result.isEmpty()) { onSuccess.call(""); } else { JavaScriptObject validationErrorsJso = CmsJsUtils.convertMapToJsObject(result); onFailure.call(CmsUgcConstants.ErrorCode.errValidation.toString(), "", validationErrorsJso); } } })); }
java
public void saveContent( JavaScriptObject newValues, final I_CmsStringCallback onSuccess, final I_CmsErrorCallback onFailure) { m_apiRoot.getRpcHelper().executeRpc( CmsXmlContentUgcApi.SERVICE.saveContent( m_content.getSessionId(), CmsJsUtils.convertJsObjectToMap(newValues), new AsyncCallback<Map<String, String>>() { @SuppressWarnings("synthetic-access") public void onFailure(Throwable caught) { CmsUgcException formException = (CmsUgcException)caught; m_apiRoot.handleError(formException, onFailure); } public void onSuccess(Map<String, String> result) { if ((result == null) || result.isEmpty()) { onSuccess.call(""); } else { JavaScriptObject validationErrorsJso = CmsJsUtils.convertMapToJsObject(result); onFailure.call(CmsUgcConstants.ErrorCode.errValidation.toString(), "", validationErrorsJso); } } })); }
[ "public", "void", "saveContent", "(", "JavaScriptObject", "newValues", ",", "final", "I_CmsStringCallback", "onSuccess", ",", "final", "I_CmsErrorCallback", "onFailure", ")", "{", "m_apiRoot", ".", "getRpcHelper", "(", ")", ".", "executeRpc", "(", "CmsXmlContentUgcApi...
Asks the server to save the values set via setNewValue in the XML content.<p> @param newValues the new values to set @param onSuccess the callback to be called in case of success @param onFailure the callback to be called in case of failure
[ "Asks", "the", "server", "to", "save", "the", "values", "set", "via", "setNewValue", "in", "the", "XML", "content", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ugc/client/export/CmsClientUgcSession.java#L198-L227
jenkinsci/jenkins
core/src/main/java/hudson/FilePath.java
FilePath.symlinkTo
public void symlinkTo(final String target, final TaskListener listener) throws IOException, InterruptedException { act(new SymlinkTo(target, listener)); }
java
public void symlinkTo(final String target, final TaskListener listener) throws IOException, InterruptedException { act(new SymlinkTo(target, listener)); }
[ "public", "void", "symlinkTo", "(", "final", "String", "target", ",", "final", "TaskListener", "listener", ")", "throws", "IOException", ",", "InterruptedException", "{", "act", "(", "new", "SymlinkTo", "(", "target", ",", "listener", ")", ")", ";", "}" ]
Creates a symlink to the specified target. @param target The file that the symlink should point to. @param listener If symlink creation requires a help of an external process, the error will be reported here. @since 1.456
[ "Creates", "a", "symlink", "to", "the", "specified", "target", "." ]
train
https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/FilePath.java#L699-L701
bitcoinj/bitcoinj
core/src/main/java/org/bitcoinj/utils/BlockFileLoader.java
BlockFileLoader.getReferenceClientBlockFileList
public static List<File> getReferenceClientBlockFileList(File blocksDir) { checkArgument(blocksDir.isDirectory(), "%s is not a directory", blocksDir); List<File> list = new LinkedList<>(); for (int i = 0; true; i++) { File file = new File(blocksDir, String.format(Locale.US, "blk%05d.dat", i)); if (!file.exists()) break; list.add(file); } return list; }
java
public static List<File> getReferenceClientBlockFileList(File blocksDir) { checkArgument(blocksDir.isDirectory(), "%s is not a directory", blocksDir); List<File> list = new LinkedList<>(); for (int i = 0; true; i++) { File file = new File(blocksDir, String.format(Locale.US, "blk%05d.dat", i)); if (!file.exists()) break; list.add(file); } return list; }
[ "public", "static", "List", "<", "File", ">", "getReferenceClientBlockFileList", "(", "File", "blocksDir", ")", "{", "checkArgument", "(", "blocksDir", ".", "isDirectory", "(", ")", ",", "\"%s is not a directory\"", ",", "blocksDir", ")", ";", "List", "<", "File...
Gets the list of files which contain blocks from Bitcoin Core.
[ "Gets", "the", "list", "of", "files", "which", "contain", "blocks", "from", "Bitcoin", "Core", "." ]
train
https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/utils/BlockFileLoader.java#L57-L67
roboconf/roboconf-platform
core/roboconf-core/src/main/java/net/roboconf/core/model/helpers/InstanceHelpers.java
InstanceHelpers.tryToInsertChildInstance
public static boolean tryToInsertChildInstance( AbstractApplication application, Instance parentInstance, Instance childInstance ) { // First, make sure there is no child instance with this name before inserting. // Otherwise, removing the child instance may result randomly. boolean hasAlreadyAChildWithThisName = hasChildWithThisName( application, parentInstance, childInstance.getName()); // We insert a "root instance" boolean success = false; if( parentInstance == null ) { if( ! hasAlreadyAChildWithThisName && ComponentHelpers.findAllAncestors( childInstance.getComponent()).isEmpty()) { application.getRootInstances().add( childInstance ); success = true; // No validation here, but maybe we should... } } // We insert a child instance else { if( ! hasAlreadyAChildWithThisName && ComponentHelpers.findAllChildren( parentInstance.getComponent()).contains( childInstance.getComponent())) { InstanceHelpers.insertChild( parentInstance, childInstance ); Collection<Instance> allInstances = InstanceHelpers.getAllInstances( application ); Collection<ModelError> errors = RuntimeModelValidator.validate( allInstances ); if( RoboconfErrorHelpers.containsCriticalErrors( errors )) { parentInstance.getChildren().remove( childInstance ); childInstance.setParent( null ); } else { success = true; } } } return success; }
java
public static boolean tryToInsertChildInstance( AbstractApplication application, Instance parentInstance, Instance childInstance ) { // First, make sure there is no child instance with this name before inserting. // Otherwise, removing the child instance may result randomly. boolean hasAlreadyAChildWithThisName = hasChildWithThisName( application, parentInstance, childInstance.getName()); // We insert a "root instance" boolean success = false; if( parentInstance == null ) { if( ! hasAlreadyAChildWithThisName && ComponentHelpers.findAllAncestors( childInstance.getComponent()).isEmpty()) { application.getRootInstances().add( childInstance ); success = true; // No validation here, but maybe we should... } } // We insert a child instance else { if( ! hasAlreadyAChildWithThisName && ComponentHelpers.findAllChildren( parentInstance.getComponent()).contains( childInstance.getComponent())) { InstanceHelpers.insertChild( parentInstance, childInstance ); Collection<Instance> allInstances = InstanceHelpers.getAllInstances( application ); Collection<ModelError> errors = RuntimeModelValidator.validate( allInstances ); if( RoboconfErrorHelpers.containsCriticalErrors( errors )) { parentInstance.getChildren().remove( childInstance ); childInstance.setParent( null ); } else { success = true; } } } return success; }
[ "public", "static", "boolean", "tryToInsertChildInstance", "(", "AbstractApplication", "application", ",", "Instance", "parentInstance", ",", "Instance", "childInstance", ")", "{", "// First, make sure there is no child instance with this name before inserting.", "// Otherwise, remov...
Tries to insert a child instance. <ol> <li>Check if there is no child instance with this name.</li> <li>Check that the graph(s) allow it (coherence with respect to the components).</li> <li>Insert the instance.</li> <li>Validate the application after insertion.</li> <li>Critical error =&gt; revert the insertion.</li> </ol> <p> This method assumes the application is already valid before the insertion. Which makes sense. </p> @param application the application (not null) @param parentInstance the parent instance (can be null) @param childInstance the child instance (not null) @return true if the child instance could be inserted, false otherwise
[ "Tries", "to", "insert", "a", "child", "instance", ".", "<ol", ">", "<li", ">", "Check", "if", "there", "is", "no", "child", "instance", "with", "this", "name", ".", "<", "/", "li", ">", "<li", ">", "Check", "that", "the", "graph", "(", "s", ")", ...
train
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/model/helpers/InstanceHelpers.java#L420-L457
wdullaer/MaterialDateTimePicker
library/src/main/java/com/wdullaer/materialdatetimepicker/Utils.java
Utils.isDarkTheme
public static boolean isDarkTheme(Context context, boolean current) { return resolveBoolean(context, R.attr.mdtp_theme_dark, current); }
java
public static boolean isDarkTheme(Context context, boolean current) { return resolveBoolean(context, R.attr.mdtp_theme_dark, current); }
[ "public", "static", "boolean", "isDarkTheme", "(", "Context", "context", ",", "boolean", "current", ")", "{", "return", "resolveBoolean", "(", "context", ",", "R", ".", "attr", ".", "mdtp_theme_dark", ",", "current", ")", ";", "}" ]
Gets dialog type (Light/Dark) from current theme @param context The context to use as reference for the boolean @param current Default value to return if cannot resolve the attribute @return true if dark mode, false if light.
[ "Gets", "dialog", "type", "(", "Light", "/", "Dark", ")", "from", "current", "theme" ]
train
https://github.com/wdullaer/MaterialDateTimePicker/blob/0a8fe28f19db4f5a5a6cfc525a852416232873a8/library/src/main/java/com/wdullaer/materialdatetimepicker/Utils.java#L123-L125
rometools/rome
rome-fetcher/src/main/java/com/rometools/fetcher/impl/HttpURLFeedFetcher.java
HttpURLFeedFetcher.setRequestHeaders
protected void setRequestHeaders(final URLConnection connection, final SyndFeedInfo syndFeedInfo, final String userAgent) { if (syndFeedInfo != null) { // set the headers to get feed only if modified // we support the use of both last modified and eTag headers if (syndFeedInfo.getLastModified() != null) { final Object lastModified = syndFeedInfo.getLastModified(); if (lastModified instanceof Long) { connection.setIfModifiedSince((Long) syndFeedInfo.getLastModified()); } } if (syndFeedInfo.getETag() != null) { connection.setRequestProperty("If-None-Match", syndFeedInfo.getETag()); } } // header to retrieve feed gzipped connection.setRequestProperty("Accept-Encoding", "gzip"); connection.addRequestProperty("User-Agent", userAgent); if (isUsingDeltaEncoding()) { connection.addRequestProperty("A-IM", "feed"); } }
java
protected void setRequestHeaders(final URLConnection connection, final SyndFeedInfo syndFeedInfo, final String userAgent) { if (syndFeedInfo != null) { // set the headers to get feed only if modified // we support the use of both last modified and eTag headers if (syndFeedInfo.getLastModified() != null) { final Object lastModified = syndFeedInfo.getLastModified(); if (lastModified instanceof Long) { connection.setIfModifiedSince((Long) syndFeedInfo.getLastModified()); } } if (syndFeedInfo.getETag() != null) { connection.setRequestProperty("If-None-Match", syndFeedInfo.getETag()); } } // header to retrieve feed gzipped connection.setRequestProperty("Accept-Encoding", "gzip"); connection.addRequestProperty("User-Agent", userAgent); if (isUsingDeltaEncoding()) { connection.addRequestProperty("A-IM", "feed"); } }
[ "protected", "void", "setRequestHeaders", "(", "final", "URLConnection", "connection", ",", "final", "SyndFeedInfo", "syndFeedInfo", ",", "final", "String", "userAgent", ")", "{", "if", "(", "syndFeedInfo", "!=", "null", ")", "{", "// set the headers to get feed only ...
<p> Set appropriate HTTP headers, including conditional get and gzip encoding headers </p> @param connection A URLConnection @param syndFeedInfo The SyndFeedInfo for the feed to be retrieved. May be null @param userAgent the name of the user-agent to be placed in HTTP-header.
[ "<p", ">", "Set", "appropriate", "HTTP", "headers", "including", "conditional", "get", "and", "gzip", "encoding", "headers", "<", "/", "p", ">" ]
train
https://github.com/rometools/rome/blob/5fcf0b1a9a6cdedbe253a45ad9468c54a0f97010/rome-fetcher/src/main/java/com/rometools/fetcher/impl/HttpURLFeedFetcher.java#L253-L275
jamesagnew/hapi-fhir
hapi-fhir-structures-dstu/src/main/java/ca/uhn/fhir/rest/server/interceptor/AuditingInterceptor.java
AuditingInterceptor.getObjectElement
protected ObjectElement getObjectElement(IResource resource, SecurityEventObjectLifecycleEnum lifecycle, byte[] query) throws InstantiationException, IllegalAccessException { String resourceType = resource.getResourceName(); if (myAuditableResources.containsKey(resourceType)) { log.debug("Found auditable resource of type: " + resourceType); @SuppressWarnings("unchecked") IResourceAuditor<IResource> auditableResource = (IResourceAuditor<IResource>) myAuditableResources.get(resourceType).newInstance(); auditableResource.setResource(resource); if (auditableResource.isAuditable()) { ObjectElement object = new ObjectElement(); object.setReference(new ResourceReferenceDt(resource.getId())); object.setLifecycle(lifecycle); object.setQuery(query); object.setName(auditableResource.getName()); object.setIdentifier((IdentifierDt) auditableResource.getIdentifier()); object.setType(auditableResource.getType()); object.setDescription(auditableResource.getDescription()); Map<String, String> detailMap = auditableResource.getDetail(); if (detailMap != null && !detailMap.isEmpty()) { List<ObjectDetail> details = new ArrayList<SecurityEvent.ObjectDetail>(); for (Entry<String, String> entry : detailMap.entrySet()) { ObjectDetail detail = makeObjectDetail(entry.getKey(), entry.getValue()); details.add(detail); } object.setDetail(details); } if (auditableResource.getSensitivity() != null) { CodingDt coding = object.getSensitivity().addCoding(); coding.setSystem(auditableResource.getSensitivity().getSystemElement().getValue()); coding.setCode(auditableResource.getSensitivity().getCodeElement().getValue()); coding.setDisplay(auditableResource.getSensitivity().getDisplayElement().getValue()); } return object; } else { log.debug("Resource is not auditable"); } } else { log.debug("No auditor configured for resource type " + resourceType); } return null; // not something we care to audit }
java
protected ObjectElement getObjectElement(IResource resource, SecurityEventObjectLifecycleEnum lifecycle, byte[] query) throws InstantiationException, IllegalAccessException { String resourceType = resource.getResourceName(); if (myAuditableResources.containsKey(resourceType)) { log.debug("Found auditable resource of type: " + resourceType); @SuppressWarnings("unchecked") IResourceAuditor<IResource> auditableResource = (IResourceAuditor<IResource>) myAuditableResources.get(resourceType).newInstance(); auditableResource.setResource(resource); if (auditableResource.isAuditable()) { ObjectElement object = new ObjectElement(); object.setReference(new ResourceReferenceDt(resource.getId())); object.setLifecycle(lifecycle); object.setQuery(query); object.setName(auditableResource.getName()); object.setIdentifier((IdentifierDt) auditableResource.getIdentifier()); object.setType(auditableResource.getType()); object.setDescription(auditableResource.getDescription()); Map<String, String> detailMap = auditableResource.getDetail(); if (detailMap != null && !detailMap.isEmpty()) { List<ObjectDetail> details = new ArrayList<SecurityEvent.ObjectDetail>(); for (Entry<String, String> entry : detailMap.entrySet()) { ObjectDetail detail = makeObjectDetail(entry.getKey(), entry.getValue()); details.add(detail); } object.setDetail(details); } if (auditableResource.getSensitivity() != null) { CodingDt coding = object.getSensitivity().addCoding(); coding.setSystem(auditableResource.getSensitivity().getSystemElement().getValue()); coding.setCode(auditableResource.getSensitivity().getCodeElement().getValue()); coding.setDisplay(auditableResource.getSensitivity().getDisplayElement().getValue()); } return object; } else { log.debug("Resource is not auditable"); } } else { log.debug("No auditor configured for resource type " + resourceType); } return null; // not something we care to audit }
[ "protected", "ObjectElement", "getObjectElement", "(", "IResource", "resource", ",", "SecurityEventObjectLifecycleEnum", "lifecycle", ",", "byte", "[", "]", "query", ")", "throws", "InstantiationException", ",", "IllegalAccessException", "{", "String", "resourceType", "="...
If the resource is considered an auditable resource containing PHI, create an ObjectElement, otherwise return null @param resource the resource to be audited @param lifecycle the SecurityEventObjectLifecycleEnum of the request @param query the byte encoded query string of the request @return an ObjectElement populated with information about the resource @throws IllegalAccessException if the auditor for this resource cannot be instantiated @throws InstantiationException if the auditor for this resource cannot be instantiated
[ "If", "the", "resource", "is", "considered", "an", "auditable", "resource", "containing", "PHI", "create", "an", "ObjectElement", "otherwise", "return", "null" ]
train
https://github.com/jamesagnew/hapi-fhir/blob/150a84d52fe691b7f48fcb28247c4bddb7aec352/hapi-fhir-structures-dstu/src/main/java/ca/uhn/fhir/rest/server/interceptor/AuditingInterceptor.java#L280-L321
lessthanoptimal/BoofCV
main/boofcv-geo/src/main/java/boofcv/alg/geo/f/EssentialNister5.java
EssentialNister5.process
public boolean process( List<AssociatedPair> points , FastQueue<DMatrixRMaj> solutions ) { if( points.size() != 5 ) throw new IllegalArgumentException("Exactly 5 points are required, not "+points.size()); solutions.reset(); // Computes the 4-vector span which contains E. See equations 7-9 computeSpan(points); // Construct a linear system based on the 10 constraint equations. See equations 5,6, and 10 . helper.setNullSpace(X,Y,Z,W); helper.setupA1(A1); helper.setupA2(A2); // instead of Gauss-Jordan elimination LU decomposition is used to solve the system solver.setA(A1); solver.solve(A2, C); // construct the z-polynomial matrix. Equations 11-14 helper.setDeterminantVectors(C); helper.extractPolynomial(poly.getCoefficients()); if( !findRoots.process(poly) ) return false; for( Complex_F64 c : findRoots.getRoots() ) { if( !c.isReal() ) continue; solveForXandY(c.real); DMatrixRMaj E = solutions.grow(); for( int i = 0; i < 9; i++ ) { E.data[i] = x*X[i] + y*Y[i] + z*Z[i] + W[i]; } } return true; }
java
public boolean process( List<AssociatedPair> points , FastQueue<DMatrixRMaj> solutions ) { if( points.size() != 5 ) throw new IllegalArgumentException("Exactly 5 points are required, not "+points.size()); solutions.reset(); // Computes the 4-vector span which contains E. See equations 7-9 computeSpan(points); // Construct a linear system based on the 10 constraint equations. See equations 5,6, and 10 . helper.setNullSpace(X,Y,Z,W); helper.setupA1(A1); helper.setupA2(A2); // instead of Gauss-Jordan elimination LU decomposition is used to solve the system solver.setA(A1); solver.solve(A2, C); // construct the z-polynomial matrix. Equations 11-14 helper.setDeterminantVectors(C); helper.extractPolynomial(poly.getCoefficients()); if( !findRoots.process(poly) ) return false; for( Complex_F64 c : findRoots.getRoots() ) { if( !c.isReal() ) continue; solveForXandY(c.real); DMatrixRMaj E = solutions.grow(); for( int i = 0; i < 9; i++ ) { E.data[i] = x*X[i] + y*Y[i] + z*Z[i] + W[i]; } } return true; }
[ "public", "boolean", "process", "(", "List", "<", "AssociatedPair", ">", "points", ",", "FastQueue", "<", "DMatrixRMaj", ">", "solutions", ")", "{", "if", "(", "points", ".", "size", "(", ")", "!=", "5", ")", "throw", "new", "IllegalArgumentException", "("...
Computes the essential matrix from point correspondences. @param points Input: List of points correspondences in normalized image coordinates @param solutions Output: Storage for the found solutions. . @return true for success or false if a fault has been detected
[ "Computes", "the", "essential", "matrix", "from", "point", "correspondences", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/f/EssentialNister5.java#L104-L142
googleapis/google-cloud-java
google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/deprecated/Disk.java
Disk.createSnapshot
public Operation createSnapshot(String snapshot, String description, OperationOption... options) { SnapshotInfo snapshotInfo = SnapshotInfo.newBuilder(SnapshotId.of(snapshot), getDiskId()) .setDescription(description) .build(); return compute.create(snapshotInfo, options); }
java
public Operation createSnapshot(String snapshot, String description, OperationOption... options) { SnapshotInfo snapshotInfo = SnapshotInfo.newBuilder(SnapshotId.of(snapshot), getDiskId()) .setDescription(description) .build(); return compute.create(snapshotInfo, options); }
[ "public", "Operation", "createSnapshot", "(", "String", "snapshot", ",", "String", "description", ",", "OperationOption", "...", "options", ")", "{", "SnapshotInfo", "snapshotInfo", "=", "SnapshotInfo", ".", "newBuilder", "(", "SnapshotId", ".", "of", "(", "snapsh...
Creates a snapshot for this disk given the snapshot's name and description. @return a zone operation for snapshot creation @throws ComputeException upon failure
[ "Creates", "a", "snapshot", "for", "this", "disk", "given", "the", "snapshot", "s", "name", "and", "description", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/deprecated/Disk.java#L179-L185