repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
18
194
func_name
stringlengths
6
111
whole_func_string
stringlengths
80
3.8k
language
stringclasses
1 value
func_code_string
stringlengths
80
3.8k
func_code_tokens
listlengths
20
697
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
listlengths
1
434
split_name
stringclasses
1 value
func_code_url
stringlengths
111
308
jenkinsci/jenkins
core/src/main/java/hudson/model/View.java
View.doConfigSubmit
@RequirePOST public final synchronized void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException { checkPermission(CONFIGURE); submit(req); description = Util.nullify(req.getParameter("description")); filterExecutors = req.getParameter("filterExecutors") != null; filterQueue = req.getParameter("filterQueue") != null; rename(req.getParameter("name")); getProperties().rebuild(req, req.getSubmittedForm(), getApplicablePropertyDescriptors()); save(); FormApply.success("../" + Util.rawEncode(name)).generateResponse(req,rsp,this); }
java
@RequirePOST public final synchronized void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException { checkPermission(CONFIGURE); submit(req); description = Util.nullify(req.getParameter("description")); filterExecutors = req.getParameter("filterExecutors") != null; filterQueue = req.getParameter("filterQueue") != null; rename(req.getParameter("name")); getProperties().rebuild(req, req.getSubmittedForm(), getApplicablePropertyDescriptors()); save(); FormApply.success("../" + Util.rawEncode(name)).generateResponse(req,rsp,this); }
[ "@", "RequirePOST", "public", "final", "synchronized", "void", "doConfigSubmit", "(", "StaplerRequest", "req", ",", "StaplerResponse", "rsp", ")", "throws", "IOException", ",", "ServletException", ",", "FormException", "{", "checkPermission", "(", "CONFIGURE", ")", ...
Accepts submission from the configuration page. Subtypes should override the {@link #submit(StaplerRequest)} method.
[ "Accepts", "submission", "from", "the", "configuration", "page", "." ]
train
https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/model/View.java#L983-L1000
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/ClassUtils.java
ClassUtils.getCanonicalName
public static String getCanonicalName(final Class<?> cls, final String valueIfNull) { if (cls == null) { return valueIfNull; } final String canonicalName = cls.getCanonicalName(); return canonicalName == null ? valueIfNull : canonicalName; }
java
public static String getCanonicalName(final Class<?> cls, final String valueIfNull) { if (cls == null) { return valueIfNull; } final String canonicalName = cls.getCanonicalName(); return canonicalName == null ? valueIfNull : canonicalName; }
[ "public", "static", "String", "getCanonicalName", "(", "final", "Class", "<", "?", ">", "cls", ",", "final", "String", "valueIfNull", ")", "{", "if", "(", "cls", "==", "null", ")", "{", "return", "valueIfNull", ";", "}", "final", "String", "canonicalName",...
<p>Gets the canonical name for a {@code Class}.</p> @param cls the class for which to get the canonical class name; may be null @param valueIfNull the return value if null @return the canonical name of the class, or {@code valueIfNull} @since 3.7 @see Class#getCanonicalName()
[ "<p", ">", "Gets", "the", "canonical", "name", "for", "a", "{", "@code", "Class", "}", ".", "<", "/", "p", ">" ]
train
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/ClassUtils.java#L1220-L1226
googleapis/google-cloud-java
google-cloud-clients/google-cloud-datalabeling/src/main/java/com/google/cloud/datalabeling/v1beta1/DataLabelingServiceClient.java
DataLabelingServiceClient.listInstructions
public final ListInstructionsPagedResponse listInstructions(String parent, String filter) { PROJECT_PATH_TEMPLATE.validate(parent, "listInstructions"); ListInstructionsRequest request = ListInstructionsRequest.newBuilder().setParent(parent).setFilter(filter).build(); return listInstructions(request); }
java
public final ListInstructionsPagedResponse listInstructions(String parent, String filter) { PROJECT_PATH_TEMPLATE.validate(parent, "listInstructions"); ListInstructionsRequest request = ListInstructionsRequest.newBuilder().setParent(parent).setFilter(filter).build(); return listInstructions(request); }
[ "public", "final", "ListInstructionsPagedResponse", "listInstructions", "(", "String", "parent", ",", "String", "filter", ")", "{", "PROJECT_PATH_TEMPLATE", ".", "validate", "(", "parent", ",", "\"listInstructions\"", ")", ";", "ListInstructionsRequest", "request", "=",...
Lists instructions for a project. Pagination is supported. <p>Sample code: <pre><code> try (DataLabelingServiceClient dataLabelingServiceClient = DataLabelingServiceClient.create()) { String formattedParent = DataLabelingServiceClient.formatProjectName("[PROJECT]"); String filter = ""; for (Instruction element : dataLabelingServiceClient.listInstructions(formattedParent, filter).iterateAll()) { // doThingsWith(element); } } </code></pre> @param parent Required. Instruction resource parent, format: projects/{project_id} @param filter Optional. Filter is not supported at this moment. @throws com.google.api.gax.rpc.ApiException if the remote call fails
[ "Lists", "instructions", "for", "a", "project", ".", "Pagination", "is", "supported", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-datalabeling/src/main/java/com/google/cloud/datalabeling/v1beta1/DataLabelingServiceClient.java#L2604-L2609
wmdietl/jsr308-langtools
src/share/classes/com/sun/tools/doclets/internal/toolkit/builders/ProfileSummaryBuilder.java
ProfileSummaryBuilder.buildExceptionSummary
public void buildExceptionSummary(XMLNode node, Content packageSummaryContentTree) { String exceptionTableSummary = configuration.getText("doclet.Member_Table_Summary", configuration.getText("doclet.Exception_Summary"), configuration.getText("doclet.exceptions")); String[] exceptionTableHeader = new String[] { configuration.getText("doclet.Exception"), configuration.getText("doclet.Description") }; ClassDoc[] exceptions = pkg.exceptions(); if (exceptions.length > 0) { profileWriter.addClassesSummary( exceptions, configuration.getText("doclet.Exception_Summary"), exceptionTableSummary, exceptionTableHeader, packageSummaryContentTree); } }
java
public void buildExceptionSummary(XMLNode node, Content packageSummaryContentTree) { String exceptionTableSummary = configuration.getText("doclet.Member_Table_Summary", configuration.getText("doclet.Exception_Summary"), configuration.getText("doclet.exceptions")); String[] exceptionTableHeader = new String[] { configuration.getText("doclet.Exception"), configuration.getText("doclet.Description") }; ClassDoc[] exceptions = pkg.exceptions(); if (exceptions.length > 0) { profileWriter.addClassesSummary( exceptions, configuration.getText("doclet.Exception_Summary"), exceptionTableSummary, exceptionTableHeader, packageSummaryContentTree); } }
[ "public", "void", "buildExceptionSummary", "(", "XMLNode", "node", ",", "Content", "packageSummaryContentTree", ")", "{", "String", "exceptionTableSummary", "=", "configuration", ".", "getText", "(", "\"doclet.Member_Table_Summary\"", ",", "configuration", ".", "getText",...
Build the summary for the exceptions in the package. @param node the XML element that specifies which components to document @param packageSummaryContentTree the tree to which the exception summary will be added
[ "Build", "the", "summary", "for", "the", "exceptions", "in", "the", "package", "." ]
train
https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/com/sun/tools/doclets/internal/toolkit/builders/ProfileSummaryBuilder.java#L260-L276
OpenLiberty/open-liberty
dev/com.ibm.websphere.javaee.jsf.2.2/src/javax/faces/component/UIViewRoot.java
UIViewRoot._process
private boolean _process(FacesContext context, PhaseId phaseId, PhaseProcessor processor) { RuntimeException processingException = null; try { if (!notifyListeners(context, phaseId, getBeforePhaseListener(), true)) { try { if (processor != null) { processor.process(context, this); } broadcastEvents(context, phaseId); } catch (RuntimeException re) { // catch any Exception that occures while processing the phase // to ensure invocation of the afterPhase methods processingException = re; } } } finally { if (context.getRenderResponse() || context.getResponseComplete()) { clearEvents(); } } boolean retVal = notifyListeners(context, phaseId, getAfterPhaseListener(), false); if (processingException == null) { return retVal; } else { throw processingException; } }
java
private boolean _process(FacesContext context, PhaseId phaseId, PhaseProcessor processor) { RuntimeException processingException = null; try { if (!notifyListeners(context, phaseId, getBeforePhaseListener(), true)) { try { if (processor != null) { processor.process(context, this); } broadcastEvents(context, phaseId); } catch (RuntimeException re) { // catch any Exception that occures while processing the phase // to ensure invocation of the afterPhase methods processingException = re; } } } finally { if (context.getRenderResponse() || context.getResponseComplete()) { clearEvents(); } } boolean retVal = notifyListeners(context, phaseId, getAfterPhaseListener(), false); if (processingException == null) { return retVal; } else { throw processingException; } }
[ "private", "boolean", "_process", "(", "FacesContext", "context", ",", "PhaseId", "phaseId", ",", "PhaseProcessor", "processor", ")", "{", "RuntimeException", "processingException", "=", "null", ";", "try", "{", "if", "(", "!", "notifyListeners", "(", "context", ...
Process the specified phase by calling PhaseListener.beforePhase for every phase listeners defined on this view root, then calling the process method of the processor, broadcasting relevant events and finally notifying the afterPhase method of every phase listeners registered on this view root. @param context @param phaseId @param processor @param broadcast @return
[ "Process", "the", "specified", "phase", "by", "calling", "PhaseListener", ".", "beforePhase", "for", "every", "phase", "listeners", "defined", "on", "this", "view", "root", "then", "calling", "the", "process", "method", "of", "the", "processor", "broadcasting", ...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.websphere.javaee.jsf.2.2/src/javax/faces/component/UIViewRoot.java#L1644-L1685
liferay/com-liferay-commerce
commerce-payment-service/src/main/java/com/liferay/commerce/payment/service/persistence/impl/CommercePaymentMethodGroupRelPersistenceImpl.java
CommercePaymentMethodGroupRelPersistenceImpl.findAll
@Override public List<CommercePaymentMethodGroupRel> findAll(int start, int end) { return findAll(start, end, null); }
java
@Override public List<CommercePaymentMethodGroupRel> findAll(int start, int end) { return findAll(start, end, null); }
[ "@", "Override", "public", "List", "<", "CommercePaymentMethodGroupRel", ">", "findAll", "(", "int", "start", ",", "int", "end", ")", "{", "return", "findAll", "(", "start", ",", "end", ",", "null", ")", ";", "}" ]
Returns a range of all the commerce payment method group rels. <p> Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommercePaymentMethodGroupRelModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. </p> @param start the lower bound of the range of commerce payment method group rels @param end the upper bound of the range of commerce payment method group rels (not inclusive) @return the range of commerce payment method group rels
[ "Returns", "a", "range", "of", "all", "the", "commerce", "payment", "method", "group", "rels", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-payment-service/src/main/java/com/liferay/commerce/payment/service/persistence/impl/CommercePaymentMethodGroupRelPersistenceImpl.java#L2057-L2060
Impetus/Kundera
src/jpa-engine/core/src/main/java/com/impetus/kundera/query/KunderaQuery.java
KunderaQuery.addUpdateClause
public void addUpdateClause(final String property, final String value) { UpdateClause updateClause = new UpdateClause(property.trim(), value.trim()); updateClauseQueue.add(updateClause); addTypedParameter( value.trim().startsWith("?") ? Type.INDEXED : value.trim().startsWith(":") ? Type.NAMED : null, property, updateClause); }
java
public void addUpdateClause(final String property, final String value) { UpdateClause updateClause = new UpdateClause(property.trim(), value.trim()); updateClauseQueue.add(updateClause); addTypedParameter( value.trim().startsWith("?") ? Type.INDEXED : value.trim().startsWith(":") ? Type.NAMED : null, property, updateClause); }
[ "public", "void", "addUpdateClause", "(", "final", "String", "property", ",", "final", "String", "value", ")", "{", "UpdateClause", "updateClause", "=", "new", "UpdateClause", "(", "property", ".", "trim", "(", ")", ",", "value", ".", "trim", "(", ")", ")"...
Adds the update clause. @param property the property @param value the value
[ "Adds", "the", "update", "clause", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/jpa-engine/core/src/main/java/com/impetus/kundera/query/KunderaQuery.java#L1304-L1310
i-net-software/jlessc
src/com/inet/lib/less/ColorUtils.java
ColorUtils.hsva
static double hsva( double hue, double saturation, double value, double alpha ) { hue = ((hue % 360) / 360) * 360; int i = (int)Math.floor( (hue / 60) % 6 ); double f = (hue / 60) - i; double[] vs = { value, value * (1 - saturation), value * (1 - f * saturation), value * (1 - (1 - f) * saturation) }; return rgba( vs[HSVA_PERM[i][0]] * 255, vs[HSVA_PERM[i][1]] * 255, vs[HSVA_PERM[i][2]] * 255, alpha ); }
java
static double hsva( double hue, double saturation, double value, double alpha ) { hue = ((hue % 360) / 360) * 360; int i = (int)Math.floor( (hue / 60) % 6 ); double f = (hue / 60) - i; double[] vs = { value, value * (1 - saturation), value * (1 - f * saturation), value * (1 - (1 - f) * saturation) }; return rgba( vs[HSVA_PERM[i][0]] * 255, vs[HSVA_PERM[i][1]] * 255, vs[HSVA_PERM[i][2]] * 255, alpha ); }
[ "static", "double", "hsva", "(", "double", "hue", ",", "double", "saturation", ",", "double", "value", ",", "double", "alpha", ")", "{", "hue", "=", "(", "(", "hue", "%", "360", ")", "/", "360", ")", "*", "360", ";", "int", "i", "=", "(", "int", ...
Create a color value. @param hue hue value @param saturation saturation @param value the value @param alpha alpha @return a color value as long
[ "Create", "a", "color", "value", "." ]
train
https://github.com/i-net-software/jlessc/blob/15b13e1637f6cc2e4d72df021e23ee0ca8d5e629/src/com/inet/lib/less/ColorUtils.java#L366-L375
sshtools/j2ssh-maverick
j2ssh-maverick/src/main/java/com/sshtools/sftp/SftpClient.java
SftpClient.lcd
public void lcd(String path) throws SftpStatusException { File actual; if (!isLocalAbsolutePath(path)) { actual = new File(lcwd, path); } else { actual = new File(path); } if (!actual.isDirectory()) { throw new SftpStatusException(SftpStatusException.SSH_FX_FAILURE, path + " is not a directory"); } try { lcwd = actual.getCanonicalPath(); } catch (IOException ex) { throw new SftpStatusException(SftpStatusException.SSH_FX_FAILURE, "Failed to canonicalize path " + path); } }
java
public void lcd(String path) throws SftpStatusException { File actual; if (!isLocalAbsolutePath(path)) { actual = new File(lcwd, path); } else { actual = new File(path); } if (!actual.isDirectory()) { throw new SftpStatusException(SftpStatusException.SSH_FX_FAILURE, path + " is not a directory"); } try { lcwd = actual.getCanonicalPath(); } catch (IOException ex) { throw new SftpStatusException(SftpStatusException.SSH_FX_FAILURE, "Failed to canonicalize path " + path); } }
[ "public", "void", "lcd", "(", "String", "path", ")", "throws", "SftpStatusException", "{", "File", "actual", ";", "if", "(", "!", "isLocalAbsolutePath", "(", "path", ")", ")", "{", "actual", "=", "new", "File", "(", "lcwd", ",", "path", ")", ";", "}", ...
<p> Changes the local working directory. </p> @param path the path to the new working directory @throws SftpStatusException
[ "<p", ">", "Changes", "the", "local", "working", "directory", ".", "<", "/", "p", ">" ]
train
https://github.com/sshtools/j2ssh-maverick/blob/ce11ceaf0aa0b129b54327a6891973e1e34689f7/j2ssh-maverick/src/main/java/com/sshtools/sftp/SftpClient.java#L747-L767
grpc/grpc-java
core/src/main/java/io/grpc/internal/TransportFrameUtil.java
TransportFrameUtil.endsWith
private static boolean endsWith(byte[] subject, byte[] suffix) { int start = subject.length - suffix.length; if (start < 0) { return false; } for (int i = start; i < subject.length; i++) { if (subject[i] != suffix[i - start]) { return false; } } return true; }
java
private static boolean endsWith(byte[] subject, byte[] suffix) { int start = subject.length - suffix.length; if (start < 0) { return false; } for (int i = start; i < subject.length; i++) { if (subject[i] != suffix[i - start]) { return false; } } return true; }
[ "private", "static", "boolean", "endsWith", "(", "byte", "[", "]", "subject", ",", "byte", "[", "]", "suffix", ")", "{", "int", "start", "=", "subject", ".", "length", "-", "suffix", ".", "length", ";", "if", "(", "start", "<", "0", ")", "{", "retu...
Returns {@code true} if {@code subject} ends with {@code suffix}.
[ "Returns", "{" ]
train
https://github.com/grpc/grpc-java/blob/973885457f9609de232d2553b82c67f6c3ff57bf/core/src/main/java/io/grpc/internal/TransportFrameUtil.java#L153-L164
fuinorg/srcgen4javassist
src/main/java/org/fuin/srcgen4javassist/SgAnnotation.java
SgAnnotation.addArgument
public final void addArgument(final String name, final Object value) { if (name == null) { throw new IllegalArgumentException("The argument 'name' cannot be null!"); } if (value == null) { throw new IllegalArgumentException("The argument 'value' cannot be null!"); } arguments.put(name.trim(), value); }
java
public final void addArgument(final String name, final Object value) { if (name == null) { throw new IllegalArgumentException("The argument 'name' cannot be null!"); } if (value == null) { throw new IllegalArgumentException("The argument 'value' cannot be null!"); } arguments.put(name.trim(), value); }
[ "public", "final", "void", "addArgument", "(", "final", "String", "name", ",", "final", "Object", "value", ")", "{", "if", "(", "name", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"The argument 'name' cannot be null!\"", ")", ";", ...
Adds an argument. @param name Name of the argument - Cannot be null. @param value Value of the argument - Cannot be null.
[ "Adds", "an", "argument", "." ]
train
https://github.com/fuinorg/srcgen4javassist/blob/355828113cfce3cdd3d69ba242c5bdfc7d899f2f/src/main/java/org/fuin/srcgen4javassist/SgAnnotation.java#L114-L122
lessthanoptimal/ejml
main/ejml-ddense/src/org/ejml/dense/row/SpecializedOps_DDRM.java
SpecializedOps_DDRM.diffNormP1
public static double diffNormP1(DMatrixD1 a , DMatrixD1 b ) { if( a.numRows != b.numRows || a.numCols != b.numCols ) { throw new IllegalArgumentException("Both matrices must have the same shape."); } final int size = a.getNumElements(); double total=0; for( int i = 0; i < size; i++ ) { total += Math.abs(b.get(i) - a.get(i)); } return total; }
java
public static double diffNormP1(DMatrixD1 a , DMatrixD1 b ) { if( a.numRows != b.numRows || a.numCols != b.numCols ) { throw new IllegalArgumentException("Both matrices must have the same shape."); } final int size = a.getNumElements(); double total=0; for( int i = 0; i < size; i++ ) { total += Math.abs(b.get(i) - a.get(i)); } return total; }
[ "public", "static", "double", "diffNormP1", "(", "DMatrixD1", "a", ",", "DMatrixD1", "b", ")", "{", "if", "(", "a", ".", "numRows", "!=", "b", ".", "numRows", "||", "a", ".", "numCols", "!=", "b", ".", "numCols", ")", "{", "throw", "new", "IllegalArg...
<p> Computes the p=1 p-norm of the difference between the two Matrices:<br> <br> &sum;<sub>i=1:m</sub> &sum;<sub>j=1:n</sub> | a<sub>ij</sub> - b<sub>ij</sub>| <br> <br> where |x| is the absolute value of x. </p> <p> This is often used as a cost function. </p> @param a m by n matrix. Not modified. @param b m by n matrix. Not modified. @return The p=1 p-norm of the difference matrix.
[ "<p", ">", "Computes", "the", "p", "=", "1", "p", "-", "norm", "of", "the", "difference", "between", "the", "two", "Matrices", ":", "<br", ">", "<br", ">", "&sum", ";", "<sub", ">", "i", "=", "1", ":", "m<", "/", "sub", ">", "&sum", ";", "<sub"...
train
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/row/SpecializedOps_DDRM.java#L258-L271
Stratio/cassandra-lucene-index
builder/src/main/java/com/stratio/cassandra/lucene/builder/Builder.java
Builder.geoDistance
public static GeoDistanceCondition geoDistance(String field, double latitude, double longitude, String maxDistance) { return new GeoDistanceCondition(field, latitude, longitude, maxDistance); }
java
public static GeoDistanceCondition geoDistance(String field, double latitude, double longitude, String maxDistance) { return new GeoDistanceCondition(field, latitude, longitude, maxDistance); }
[ "public", "static", "GeoDistanceCondition", "geoDistance", "(", "String", "field", ",", "double", "latitude", ",", "double", "longitude", ",", "String", "maxDistance", ")", "{", "return", "new", "GeoDistanceCondition", "(", "field", ",", "latitude", ",", "longitud...
Returns a new {@link GeoDistanceCondition} with the specified field reference point. @param field the name of the field to be matched @param latitude the latitude of the reference point @param longitude the longitude of the reference point @param maxDistance the max allowed distance @return a new geo distance condition
[ "Returns", "a", "new", "{", "@link", "GeoDistanceCondition", "}", "with", "the", "specified", "field", "reference", "point", "." ]
train
https://github.com/Stratio/cassandra-lucene-index/blob/a94a4d9af6c25d40e1108729974c35c27c54441c/builder/src/main/java/com/stratio/cassandra/lucene/builder/Builder.java#L456-L461
pressgang-ccms/PressGangCCMSContentSpecProcessor
src/main/java/org/jboss/pressgang/ccms/contentspec/processor/ContentSpecProcessor.java
ContentSpecProcessor.doesCommonContentMatch
protected boolean doesCommonContentMatch(final CommonContent commonContent, final CSNodeWrapper node, boolean matchContent) { if (!node.getNodeType().equals(CommonConstants.CS_NODE_COMMON_CONTENT)) return false; // If the unique id is not from the parser, in which case it will start with a number than use the unique id to compare if (commonContent.getUniqueId() != null && commonContent.getUniqueId().matches("^\\d.*")) { return commonContent.getUniqueId().equals(Integer.toString(node.getId())); } else if (matchContent) { return StringUtilities.similarDamerauLevenshtein(commonContent.getTitle(), node.getTitle()) >= ProcessorConstants.MIN_MATCH_SIMILARITY; } else { // Check the parent has the same name if (commonContent.getParent() != null) { return commonContent.getParent().getTitle().equals(node.getParent().getTitle()); } return true; } }
java
protected boolean doesCommonContentMatch(final CommonContent commonContent, final CSNodeWrapper node, boolean matchContent) { if (!node.getNodeType().equals(CommonConstants.CS_NODE_COMMON_CONTENT)) return false; // If the unique id is not from the parser, in which case it will start with a number than use the unique id to compare if (commonContent.getUniqueId() != null && commonContent.getUniqueId().matches("^\\d.*")) { return commonContent.getUniqueId().equals(Integer.toString(node.getId())); } else if (matchContent) { return StringUtilities.similarDamerauLevenshtein(commonContent.getTitle(), node.getTitle()) >= ProcessorConstants.MIN_MATCH_SIMILARITY; } else { // Check the parent has the same name if (commonContent.getParent() != null) { return commonContent.getParent().getTitle().equals(node.getParent().getTitle()); } return true; } }
[ "protected", "boolean", "doesCommonContentMatch", "(", "final", "CommonContent", "commonContent", ",", "final", "CSNodeWrapper", "node", ",", "boolean", "matchContent", ")", "{", "if", "(", "!", "node", ".", "getNodeType", "(", ")", ".", "equals", "(", "CommonCo...
Checks to see if a ContentSpec Common Content matches a Content Spec Entity Common Content. @param commonContent The ContentSpec common content object. @param node The Content Spec Entity common content. @param matchContent If the contents of the common content have to match to a reasonable extent. @return True if the common content is determined to match otherwise false.
[ "Checks", "to", "see", "if", "a", "ContentSpec", "Common", "Content", "matches", "a", "Content", "Spec", "Entity", "Common", "Content", "." ]
train
https://github.com/pressgang-ccms/PressGangCCMSContentSpecProcessor/blob/85ffac047c4ede0f972364ab1f03f7d61a4de5f1/src/main/java/org/jboss/pressgang/ccms/contentspec/processor/ContentSpecProcessor.java#L2280-L2297
aws/aws-sdk-java
aws-java-sdk-core/src/main/java/com/amazonaws/auth/AWS4Signer.java
AWS4Signer.newSigningKey
protected byte[] newSigningKey(AWSCredentials credentials, String dateStamp, String regionName, String serviceName) { byte[] kSecret = ("AWS4" + credentials.getAWSSecretKey()) .getBytes(Charset.forName("UTF-8")); byte[] kDate = sign(dateStamp, kSecret, SigningAlgorithm.HmacSHA256); byte[] kRegion = sign(regionName, kDate, SigningAlgorithm.HmacSHA256); byte[] kService = sign(serviceName, kRegion, SigningAlgorithm.HmacSHA256); return sign(AWS4_TERMINATOR, kService, SigningAlgorithm.HmacSHA256); }
java
protected byte[] newSigningKey(AWSCredentials credentials, String dateStamp, String regionName, String serviceName) { byte[] kSecret = ("AWS4" + credentials.getAWSSecretKey()) .getBytes(Charset.forName("UTF-8")); byte[] kDate = sign(dateStamp, kSecret, SigningAlgorithm.HmacSHA256); byte[] kRegion = sign(regionName, kDate, SigningAlgorithm.HmacSHA256); byte[] kService = sign(serviceName, kRegion, SigningAlgorithm.HmacSHA256); return sign(AWS4_TERMINATOR, kService, SigningAlgorithm.HmacSHA256); }
[ "protected", "byte", "[", "]", "newSigningKey", "(", "AWSCredentials", "credentials", ",", "String", "dateStamp", ",", "String", "regionName", ",", "String", "serviceName", ")", "{", "byte", "[", "]", "kSecret", "=", "(", "\"AWS4\"", "+", "credentials", ".", ...
Generates a new signing key from the given parameters and returns it.
[ "Generates", "a", "new", "signing", "key", "from", "the", "given", "parameters", "and", "returns", "it", "." ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-core/src/main/java/com/amazonaws/auth/AWS4Signer.java#L623-L632
Appendium/objectlabkit
utils/src/main/java/net/objectlab/kit/util/BigDecimalUtil.java
BigDecimalUtil.ifNotNull
public static boolean ifNotNull(final BigDecimal bd, final Consumer<BigDecimal> consumer) { if (bd != null) { consumer.accept(bd); return true; } return false; }
java
public static boolean ifNotNull(final BigDecimal bd, final Consumer<BigDecimal> consumer) { if (bd != null) { consumer.accept(bd); return true; } return false; }
[ "public", "static", "boolean", "ifNotNull", "(", "final", "BigDecimal", "bd", ",", "final", "Consumer", "<", "BigDecimal", ">", "consumer", ")", "{", "if", "(", "bd", "!=", "null", ")", "{", "consumer", ".", "accept", "(", "bd", ")", ";", "return", "tr...
If the BigDecimal is not null call the consumer (depends on JDK8+) @param bd the BigDecimal @param consumer of the value, called if not null @return true if consumed @since 1.4.0
[ "If", "the", "BigDecimal", "is", "not", "null", "call", "the", "consumer", "(", "depends", "on", "JDK8", "+", ")" ]
train
https://github.com/Appendium/objectlabkit/blob/cd649bce7a32e4e926520e62cb765f3b1d451594/utils/src/main/java/net/objectlab/kit/util/BigDecimalUtil.java#L62-L68
teatrove/teatrove
trove/src/main/java/org/teatrove/trove/classfile/MethodUtils.java
MethodUtils.findMethod
private static Method findMethod(Class<?> clazz, Method method) { try { return clazz.getMethod(method.getName(), method.getParameterTypes()); } catch (NoSuchMethodException e) { return null; } }
java
private static Method findMethod(Class<?> clazz, Method method) { try { return clazz.getMethod(method.getName(), method.getParameterTypes()); } catch (NoSuchMethodException e) { return null; } }
[ "private", "static", "Method", "findMethod", "(", "Class", "<", "?", ">", "clazz", ",", "Method", "method", ")", "{", "try", "{", "return", "clazz", ".", "getMethod", "(", "method", ".", "getName", "(", ")", ",", "method", ".", "getParameterTypes", "(", ...
Find the specified method on the given class. If not specified, then <code>null</code> is returned. Otherwise, the associated method is returned. The specified method definition does not need to be from the specified class. This method is usually used to check a method defined in an interface or superclass on another class within the hierarchy. @param clazz The class to check @param method The method definition @return The associated method if existant, otherwise <code>null</code>
[ "Find", "the", "specified", "method", "on", "the", "given", "class", ".", "If", "not", "specified", "then", "<code", ">", "null<", "/", "code", ">", "is", "returned", ".", "Otherwise", "the", "associated", "method", "is", "returned", ".", "The", "specified...
train
https://github.com/teatrove/teatrove/blob/7039bdd4da6817ff8c737f7e4e07bac7e3ad8bea/trove/src/main/java/org/teatrove/trove/classfile/MethodUtils.java#L184-L192
openbase/jul
extension/protobuf/src/main/java/org/openbase/jul/extension/protobuf/ProtoBufBuilderProcessor.java
ProtoBufBuilderProcessor.addDefaultInstanceToRepeatedField
public static Message.Builder addDefaultInstanceToRepeatedField(final Descriptors.FieldDescriptor repeatedFieldDescriptor, final Message.Builder builder) throws CouldNotPerformException { if (repeatedFieldDescriptor == null) { throw new NotAvailableException("repeatedFieldDescriptor"); } return addDefaultInstanceToRepeatedField(repeatedFieldDescriptor.getName(), builder); }
java
public static Message.Builder addDefaultInstanceToRepeatedField(final Descriptors.FieldDescriptor repeatedFieldDescriptor, final Message.Builder builder) throws CouldNotPerformException { if (repeatedFieldDescriptor == null) { throw new NotAvailableException("repeatedFieldDescriptor"); } return addDefaultInstanceToRepeatedField(repeatedFieldDescriptor.getName(), builder); }
[ "public", "static", "Message", ".", "Builder", "addDefaultInstanceToRepeatedField", "(", "final", "Descriptors", ".", "FieldDescriptor", "repeatedFieldDescriptor", ",", "final", "Message", ".", "Builder", "builder", ")", "throws", "CouldNotPerformException", "{", "if", ...
Method adds a new default message instance to the repeated field and return it's builder instance. @param repeatedFieldDescriptor The field descriptor of the repeated field. @param builder The builder instance of the message which contains the repeated field. @return The builder instance of the new added message is returned. @throws CouldNotPerformException
[ "Method", "adds", "a", "new", "default", "message", "instance", "to", "the", "repeated", "field", "and", "return", "it", "s", "builder", "instance", "." ]
train
https://github.com/openbase/jul/blob/662e98c3a853085e475be54c3be3deb72193c72d/extension/protobuf/src/main/java/org/openbase/jul/extension/protobuf/ProtoBufBuilderProcessor.java#L124-L129
schallee/alib4j
core/src/main/java/net/darkmist/alib/res/PkgRes.java
PkgRes.getString
public String getString(String name) { InputStream in = null; if(name == null) throw new NullPointerException("name is null"); try { if((in = loader.getResourceAsStream(prefix + name))==null) throw new ResourceException("Unable to find resource for " + name); return IOUtils.toString(in); } catch(IOException e) { throw new ResourceException("IOException reading resource " + name, e); } finally { Closer.close(in,logger,"resource InputStream for " + name); } }
java
public String getString(String name) { InputStream in = null; if(name == null) throw new NullPointerException("name is null"); try { if((in = loader.getResourceAsStream(prefix + name))==null) throw new ResourceException("Unable to find resource for " + name); return IOUtils.toString(in); } catch(IOException e) { throw new ResourceException("IOException reading resource " + name, e); } finally { Closer.close(in,logger,"resource InputStream for " + name); } }
[ "public", "String", "getString", "(", "String", "name", ")", "{", "InputStream", "in", "=", "null", ";", "if", "(", "name", "==", "null", ")", "throw", "new", "NullPointerException", "(", "\"name is null\"", ")", ";", "try", "{", "if", "(", "(", "in", ...
Gets a resource as a String @param name The name of the resource. @return The contents of the resource converted to a string with the default encoding. @throws NullPointerException if name is null. ResourceException if the resource cannot be found or there is a error reading it.
[ "Gets", "a", "resource", "as", "a", "String" ]
train
https://github.com/schallee/alib4j/blob/0e0718aee574bbb62268e1cf58e99286529ce529/core/src/main/java/net/darkmist/alib/res/PkgRes.java#L328-L348
zxing/zxing
core/src/main/java/com/google/zxing/qrcode/encoder/MatrixUtil.java
MatrixUtil.calculateBCHCode
static int calculateBCHCode(int value, int poly) { if (poly == 0) { throw new IllegalArgumentException("0 polynomial"); } // If poly is "1 1111 0010 0101" (version info poly), msbSetInPoly is 13. We'll subtract 1 // from 13 to make it 12. int msbSetInPoly = findMSBSet(poly); value <<= msbSetInPoly - 1; // Do the division business using exclusive-or operations. while (findMSBSet(value) >= msbSetInPoly) { value ^= poly << (findMSBSet(value) - msbSetInPoly); } // Now the "value" is the remainder (i.e. the BCH code) return value; }
java
static int calculateBCHCode(int value, int poly) { if (poly == 0) { throw new IllegalArgumentException("0 polynomial"); } // If poly is "1 1111 0010 0101" (version info poly), msbSetInPoly is 13. We'll subtract 1 // from 13 to make it 12. int msbSetInPoly = findMSBSet(poly); value <<= msbSetInPoly - 1; // Do the division business using exclusive-or operations. while (findMSBSet(value) >= msbSetInPoly) { value ^= poly << (findMSBSet(value) - msbSetInPoly); } // Now the "value" is the remainder (i.e. the BCH code) return value; }
[ "static", "int", "calculateBCHCode", "(", "int", "value", ",", "int", "poly", ")", "{", "if", "(", "poly", "==", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"0 polynomial\"", ")", ";", "}", "// If poly is \"1 1111 0010 0101\" (version info po...
operations. We don't care if coefficients are positive or negative.
[ "operations", ".", "We", "don", "t", "care", "if", "coefficients", "are", "positive", "or", "negative", "." ]
train
https://github.com/zxing/zxing/blob/653ac2a3beb11481eff82e7d5f2bab8a745f7fac/core/src/main/java/com/google/zxing/qrcode/encoder/MatrixUtil.java#L303-L317
sdl/odata
odata_api/src/main/java/com/sdl/odata/util/edm/EntityDataModelUtil.java
EntityDataModelUtil.isSingletonEntity
public static boolean isSingletonEntity(EntityDataModel entityDataModel, Object entity) throws ODataEdmException { // Get the entity type EntityType entityType = getAndCheckEntityType(entityDataModel, entity.getClass()); boolean isSingletonEntity = false; for (Singleton singleton : entityDataModel.getEntityContainer().getSingletons()) { if (singleton.getTypeName().equals(entityType.getFullyQualifiedName())) { isSingletonEntity = true; break; } } return isSingletonEntity; }
java
public static boolean isSingletonEntity(EntityDataModel entityDataModel, Object entity) throws ODataEdmException { // Get the entity type EntityType entityType = getAndCheckEntityType(entityDataModel, entity.getClass()); boolean isSingletonEntity = false; for (Singleton singleton : entityDataModel.getEntityContainer().getSingletons()) { if (singleton.getTypeName().equals(entityType.getFullyQualifiedName())) { isSingletonEntity = true; break; } } return isSingletonEntity; }
[ "public", "static", "boolean", "isSingletonEntity", "(", "EntityDataModel", "entityDataModel", ",", "Object", "entity", ")", "throws", "ODataEdmException", "{", "// Get the entity type", "EntityType", "entityType", "=", "getAndCheckEntityType", "(", "entityDataModel", ",", ...
Check if the given entity is a Singleton entity. @param entityDataModel The Entity Data Model. @param entity The given entity. @return true if singleton, false if not @throws ODataEdmException if unable to determine if entity is singleton
[ "Check", "if", "the", "given", "entity", "is", "a", "Singleton", "entity", "." ]
train
https://github.com/sdl/odata/blob/eb747d73e9af0f4e59a25b82ed656e526a7e2189/odata_api/src/main/java/com/sdl/odata/util/edm/EntityDataModelUtil.java#L520-L533
threerings/gwt-utils
src/main/java/com/threerings/gwt/ui/WidgetUtil.java
WidgetUtil.createTransparentFlashContainer
public static HTML createTransparentFlashContainer ( String ident, String movie, int width, int height, String flashVars) { FlashObject obj = new FlashObject(ident, movie, width, height, flashVars); obj.transparent = true; return createContainer(obj); }
java
public static HTML createTransparentFlashContainer ( String ident, String movie, int width, int height, String flashVars) { FlashObject obj = new FlashObject(ident, movie, width, height, flashVars); obj.transparent = true; return createContainer(obj); }
[ "public", "static", "HTML", "createTransparentFlashContainer", "(", "String", "ident", ",", "String", "movie", ",", "int", "width", ",", "int", "height", ",", "String", "flashVars", ")", "{", "FlashObject", "obj", "=", "new", "FlashObject", "(", "ident", ",", ...
Creates the HTML to display a transparent Flash movie for the browser on which we're running. @param flashVars a pre-URLEncoded string containing flash variables, or null. http://www.adobe.com/cfusion/knowledgebase/index.cfm?id=tn_16417
[ "Creates", "the", "HTML", "to", "display", "a", "transparent", "Flash", "movie", "for", "the", "browser", "on", "which", "we", "re", "running", "." ]
train
https://github.com/threerings/gwt-utils/blob/31b31a23b667f2a9c683160d77646db259f2aae5/src/main/java/com/threerings/gwt/ui/WidgetUtil.java#L113-L119
apache/incubator-gobblin
gobblin-api/src/main/java/org/apache/gobblin/dataset/DatasetDescriptor.java
DatasetDescriptor.fromDataMap
@Deprecated public static DatasetDescriptor fromDataMap(Map<String, String> dataMap) { DatasetDescriptor descriptor = new DatasetDescriptor(dataMap.get(PLATFORM_KEY), dataMap.get(NAME_KEY)); dataMap.forEach((key, value) -> { if (!key.equals(PLATFORM_KEY) && !key.equals(NAME_KEY)) { descriptor.addMetadata(key, value); } }); return descriptor; }
java
@Deprecated public static DatasetDescriptor fromDataMap(Map<String, String> dataMap) { DatasetDescriptor descriptor = new DatasetDescriptor(dataMap.get(PLATFORM_KEY), dataMap.get(NAME_KEY)); dataMap.forEach((key, value) -> { if (!key.equals(PLATFORM_KEY) && !key.equals(NAME_KEY)) { descriptor.addMetadata(key, value); } }); return descriptor; }
[ "@", "Deprecated", "public", "static", "DatasetDescriptor", "fromDataMap", "(", "Map", "<", "String", ",", "String", ">", "dataMap", ")", "{", "DatasetDescriptor", "descriptor", "=", "new", "DatasetDescriptor", "(", "dataMap", ".", "get", "(", "PLATFORM_KEY", ")...
Deserialize a {@link DatasetDescriptor} from a string map @deprecated use {@link Descriptor#deserialize(String)}
[ "Deserialize", "a", "{", "@link", "DatasetDescriptor", "}", "from", "a", "string", "map" ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-api/src/main/java/org/apache/gobblin/dataset/DatasetDescriptor.java#L116-L125
elki-project/elki
addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/gui/overview/OverviewPlot.java
OverviewPlot.embedOrThumbnail
private Visualization embedOrThumbnail(final int thumbsize, PlotItem it, VisualizationTask task, Element parent) { final Visualization vis; if(!single) { vis = task.getFactory().makeVisualizationOrThumbnail(context, task, plot, it.w, it.h, it.proj, thumbsize); } else { vis = task.getFactory().makeVisualization(context, task, plot, it.w, it.h, it.proj); } if(vis == null || vis.getLayer() == null) { LOG.warning("Visualization returned empty layer: " + vis); return vis; } if(task.has(RenderFlag.NO_EXPORT)) { vis.getLayer().setAttribute(SVGPlot.NO_EXPORT_ATTRIBUTE, SVGPlot.NO_EXPORT_ATTRIBUTE); } parent.appendChild(vis.getLayer()); return vis; }
java
private Visualization embedOrThumbnail(final int thumbsize, PlotItem it, VisualizationTask task, Element parent) { final Visualization vis; if(!single) { vis = task.getFactory().makeVisualizationOrThumbnail(context, task, plot, it.w, it.h, it.proj, thumbsize); } else { vis = task.getFactory().makeVisualization(context, task, plot, it.w, it.h, it.proj); } if(vis == null || vis.getLayer() == null) { LOG.warning("Visualization returned empty layer: " + vis); return vis; } if(task.has(RenderFlag.NO_EXPORT)) { vis.getLayer().setAttribute(SVGPlot.NO_EXPORT_ATTRIBUTE, SVGPlot.NO_EXPORT_ATTRIBUTE); } parent.appendChild(vis.getLayer()); return vis; }
[ "private", "Visualization", "embedOrThumbnail", "(", "final", "int", "thumbsize", ",", "PlotItem", "it", ",", "VisualizationTask", "task", ",", "Element", "parent", ")", "{", "final", "Visualization", "vis", ";", "if", "(", "!", "single", ")", "{", "vis", "=...
Produce thumbnail for a visualizer. @param thumbsize Thumbnail size @param it Plot item @param task Task @param parent Parent element to draw to
[ "Produce", "thumbnail", "for", "a", "visualizer", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/gui/overview/OverviewPlot.java#L401-L418
atomix/atomix
core/src/main/java/io/atomix/core/impl/CoreTransactionService.java
CoreTransactionService.recoverTransaction
private void recoverTransaction(TransactionId transactionId, TransactionInfo transactionInfo) { switch (transactionInfo.state) { case PREPARING: completePreparingTransaction(transactionId); break; case COMMITTING: completeCommittingTransaction(transactionId); break; case ROLLING_BACK: completeRollingBackTransaction(transactionId); break; default: break; } }
java
private void recoverTransaction(TransactionId transactionId, TransactionInfo transactionInfo) { switch (transactionInfo.state) { case PREPARING: completePreparingTransaction(transactionId); break; case COMMITTING: completeCommittingTransaction(transactionId); break; case ROLLING_BACK: completeRollingBackTransaction(transactionId); break; default: break; } }
[ "private", "void", "recoverTransaction", "(", "TransactionId", "transactionId", ",", "TransactionInfo", "transactionInfo", ")", "{", "switch", "(", "transactionInfo", ".", "state", ")", "{", "case", "PREPARING", ":", "completePreparingTransaction", "(", "transactionId",...
Recovers and completes the given transaction. @param transactionId the transaction identifier @param transactionInfo the transaction info
[ "Recovers", "and", "completes", "the", "given", "transaction", "." ]
train
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/core/src/main/java/io/atomix/core/impl/CoreTransactionService.java#L212-L226
grails/grails-core
grails-core/src/main/groovy/grails/util/GrailsClassUtils.java
GrailsClassUtils.getPropertyOrStaticPropertyOrFieldValue
public static Object getPropertyOrStaticPropertyOrFieldValue(Object obj, String name) throws BeansException { BeanWrapper ref = new BeanWrapperImpl(obj); return getPropertyOrStaticPropertyOrFieldValue(ref, obj, name); }
java
public static Object getPropertyOrStaticPropertyOrFieldValue(Object obj, String name) throws BeansException { BeanWrapper ref = new BeanWrapperImpl(obj); return getPropertyOrStaticPropertyOrFieldValue(ref, obj, name); }
[ "public", "static", "Object", "getPropertyOrStaticPropertyOrFieldValue", "(", "Object", "obj", ",", "String", "name", ")", "throws", "BeansException", "{", "BeanWrapper", "ref", "=", "new", "BeanWrapperImpl", "(", "obj", ")", ";", "return", "getPropertyOrStaticPropert...
<p>Looks for a property of the reference instance with a given name.</p> <p>If found its value is returned. We follow the Java bean conventions with augmentation for groovy support and static fields/properties. We will therefore match, in this order: </p> <ol> <li>Standard public bean property (with getter or just public field, using normal introspection) <li>Public static property with getter method <li>Public static field </ol> @return property value or null if no property found
[ "<p", ">", "Looks", "for", "a", "property", "of", "the", "reference", "instance", "with", "a", "given", "name", ".", "<", "/", "p", ">", "<p", ">", "If", "found", "its", "value", "is", "returned", ".", "We", "follow", "the", "Java", "bean", "conventi...
train
https://github.com/grails/grails-core/blob/c0b08aa995b0297143b75d05642abba8cb7b4122/grails-core/src/main/groovy/grails/util/GrailsClassUtils.java#L626-L629
Azure/azure-sdk-for-java
network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/ApplicationGatewaysInner.java
ApplicationGatewaysInner.backendHealthAsync
public Observable<ApplicationGatewayBackendHealthInner> backendHealthAsync(String resourceGroupName, String applicationGatewayName, String expand) { return backendHealthWithServiceResponseAsync(resourceGroupName, applicationGatewayName, expand).map(new Func1<ServiceResponse<ApplicationGatewayBackendHealthInner>, ApplicationGatewayBackendHealthInner>() { @Override public ApplicationGatewayBackendHealthInner call(ServiceResponse<ApplicationGatewayBackendHealthInner> response) { return response.body(); } }); }
java
public Observable<ApplicationGatewayBackendHealthInner> backendHealthAsync(String resourceGroupName, String applicationGatewayName, String expand) { return backendHealthWithServiceResponseAsync(resourceGroupName, applicationGatewayName, expand).map(new Func1<ServiceResponse<ApplicationGatewayBackendHealthInner>, ApplicationGatewayBackendHealthInner>() { @Override public ApplicationGatewayBackendHealthInner call(ServiceResponse<ApplicationGatewayBackendHealthInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "ApplicationGatewayBackendHealthInner", ">", "backendHealthAsync", "(", "String", "resourceGroupName", ",", "String", "applicationGatewayName", ",", "String", "expand", ")", "{", "return", "backendHealthWithServiceResponseAsync", "(", "resourceGro...
Gets the backend health of the specified application gateway in a resource group. @param resourceGroupName The name of the resource group. @param applicationGatewayName The name of the application gateway. @param expand Expands BackendAddressPool and BackendHttpSettings referenced in backend health. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request
[ "Gets", "the", "backend", "health", "of", "the", "specified", "application", "gateway", "in", "a", "resource", "group", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/ApplicationGatewaysInner.java#L1500-L1507
groovy/groovy-core
src/main/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java
StaticTypeCheckingVisitor.getGenericsResolvedTypeOfFieldOrProperty
private ClassNode getGenericsResolvedTypeOfFieldOrProperty(AnnotatedNode an, ClassNode type) { if (!type.isUsingGenerics()) return type; Map<String, GenericsType> connections = new HashMap(); //TODO: inner classes mean a different this-type. This is ignored here! extractGenericsConnections(connections, typeCheckingContext.getEnclosingClassNode(), an.getDeclaringClass()); type= applyGenericsContext(connections, type); return type; }
java
private ClassNode getGenericsResolvedTypeOfFieldOrProperty(AnnotatedNode an, ClassNode type) { if (!type.isUsingGenerics()) return type; Map<String, GenericsType> connections = new HashMap(); //TODO: inner classes mean a different this-type. This is ignored here! extractGenericsConnections(connections, typeCheckingContext.getEnclosingClassNode(), an.getDeclaringClass()); type= applyGenericsContext(connections, type); return type; }
[ "private", "ClassNode", "getGenericsResolvedTypeOfFieldOrProperty", "(", "AnnotatedNode", "an", ",", "ClassNode", "type", ")", "{", "if", "(", "!", "type", ".", "isUsingGenerics", "(", ")", ")", "return", "type", ";", "Map", "<", "String", ",", "GenericsType", ...
resolves a Field or Property node generics by using the current class and the declaring class to extract the right meaning of the generics symbols @param an a FieldNode or PropertyNode @param type the origin type @return the new ClassNode with corrected generics
[ "resolves", "a", "Field", "or", "Property", "node", "generics", "by", "using", "the", "current", "class", "and", "the", "declaring", "class", "to", "extract", "the", "right", "meaning", "of", "the", "generics", "symbols" ]
train
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java#L4000-L4007
derari/cthul
xml/src/main/java/org/cthul/resolve/UriMappingResolver.java
UriMappingResolver.addResource
public UriMappingResolver addResource(String uri, String resource) { uriMap.put(uri, resource); return this; }
java
public UriMappingResolver addResource(String uri, String resource) { uriMap.put(uri, resource); return this; }
[ "public", "UriMappingResolver", "addResource", "(", "String", "uri", ",", "String", "resource", ")", "{", "uriMap", ".", "put", "(", "uri", ",", "resource", ")", ";", "return", "this", ";", "}" ]
Adds a single resource that can be looked-up by its uri. @param uri @param resource @return this
[ "Adds", "a", "single", "resource", "that", "can", "be", "looked", "-", "up", "by", "its", "uri", "." ]
train
https://github.com/derari/cthul/blob/74a31e3cb6a94f5f25cc5253d1dbd42e19a17ebc/xml/src/main/java/org/cthul/resolve/UriMappingResolver.java#L86-L89
lessthanoptimal/BoofCV
main/boofcv-ip/src/main/java/boofcv/alg/distort/mls/ImageDeformPointMLS_F32.java
ImageDeformPointMLS_F32.addControl
public int addControl( float x , float y ) { Control c = controls.grow(); c.q.set(x,y); setUndistorted(controls.size()-1,x,y); return controls.size()-1; }
java
public int addControl( float x , float y ) { Control c = controls.grow(); c.q.set(x,y); setUndistorted(controls.size()-1,x,y); return controls.size()-1; }
[ "public", "int", "addControl", "(", "float", "x", ",", "float", "y", ")", "{", "Control", "c", "=", "controls", ".", "grow", "(", ")", ";", "c", ".", "q", ".", "set", "(", "x", ",", "y", ")", ";", "setUndistorted", "(", "controls", ".", "size", ...
Adds a new control point at the specified location. Initially the distorted and undistorted location will be set to the same @param x coordinate x-axis in image pixels @param y coordinate y-axis in image pixels @return Index of control point
[ "Adds", "a", "new", "control", "point", "at", "the", "specified", "location", ".", "Initially", "the", "distorted", "and", "undistorted", "location", "will", "be", "set", "to", "the", "same" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/alg/distort/mls/ImageDeformPointMLS_F32.java#L137-L142
http-builder-ng/http-builder-ng
http-builder-ng-core/src/main/java/groovyx/net/http/HttpBuilder.java
HttpBuilder.patchAsync
public CompletableFuture<Object> patchAsync(@DelegatesTo(HttpConfig.class) final Closure closure) { return CompletableFuture.supplyAsync(() -> patch(closure), getExecutor()); }
java
public CompletableFuture<Object> patchAsync(@DelegatesTo(HttpConfig.class) final Closure closure) { return CompletableFuture.supplyAsync(() -> patch(closure), getExecutor()); }
[ "public", "CompletableFuture", "<", "Object", ">", "patchAsync", "(", "@", "DelegatesTo", "(", "HttpConfig", ".", "class", ")", "final", "Closure", "closure", ")", "{", "return", "CompletableFuture", ".", "supplyAsync", "(", "(", ")", "->", "patch", "(", "cl...
Executes an asynchronous PATCH request on the configured URI (asynchronous alias to the `patch(Closure)` method), with additional configuration provided by the configuration closure. [source,groovy] ---- def http = HttpBuilder.configure { request.uri = 'http://localhost:10101' } CompletableFuture future = http.patchAsync(){ request.uri.path = '/something' } def result = future.get() ---- The configuration `closure` allows additional configuration for this request based on the {@link HttpConfig} interface. @param closure the additional configuration closure (delegated to {@link HttpConfig}) @return the resulting content
[ "Executes", "an", "asynchronous", "PATCH", "request", "on", "the", "configured", "URI", "(", "asynchronous", "alias", "to", "the", "patch", "(", "Closure", ")", "method", ")", "with", "additional", "configuration", "provided", "by", "the", "configuration", "clos...
train
https://github.com/http-builder-ng/http-builder-ng/blob/865f37732c102c748d3db8b905199dac9222a525/http-builder-ng-core/src/main/java/groovyx/net/http/HttpBuilder.java#L1665-L1667
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/concurrent/Helpers.java
Helpers.collectionToString
static String collectionToString(Collection<?> c) { final Object[] a = c.toArray(); final int size = a.length; if (size == 0) return "[]"; int charLength = 0; // Replace every array element with its string representation for (int i = 0; i < size; i++) { Object e = a[i]; // Extreme compatibility with AbstractCollection.toString() String s = (e == c) ? "(this Collection)" : objectToString(e); a[i] = s; charLength += s.length(); } return toString(a, size, charLength); }
java
static String collectionToString(Collection<?> c) { final Object[] a = c.toArray(); final int size = a.length; if (size == 0) return "[]"; int charLength = 0; // Replace every array element with its string representation for (int i = 0; i < size; i++) { Object e = a[i]; // Extreme compatibility with AbstractCollection.toString() String s = (e == c) ? "(this Collection)" : objectToString(e); a[i] = s; charLength += s.length(); } return toString(a, size, charLength); }
[ "static", "String", "collectionToString", "(", "Collection", "<", "?", ">", "c", ")", "{", "final", "Object", "[", "]", "a", "=", "c", ".", "toArray", "(", ")", ";", "final", "int", "size", "=", "a", ".", "length", ";", "if", "(", "size", "==", "...
An implementation of Collection.toString() suitable for classes with locks. Instead of holding a lock for the entire duration of toString(), or acquiring a lock for each call to Iterator.next(), we hold the lock only during the call to toArray() (less disruptive to other threads accessing the collection) and follows the maxim "Never call foreign code while holding a lock".
[ "An", "implementation", "of", "Collection", ".", "toString", "()", "suitable", "for", "classes", "with", "locks", ".", "Instead", "of", "holding", "a", "lock", "for", "the", "entire", "duration", "of", "toString", "()", "or", "acquiring", "a", "lock", "for",...
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/concurrent/Helpers.java#L52-L69
grails/grails-core
grails-core/src/main/groovy/org/grails/plugins/BasePluginFilter.java
BasePluginFilter.isDependentOn
protected boolean isDependentOn(GrailsPlugin plugin, String pluginName) { // check if toCompare depends on the current plugin String[] dependencyNames = plugin.getDependencyNames(); for (int i = 0; i < dependencyNames.length; i++) { final String dependencyName = dependencyNames[i]; if (pluginName.equals(dependencyName)) { return true; // we've establish that p does depend on plugin, so we can // break from this loop } } return false; }
java
protected boolean isDependentOn(GrailsPlugin plugin, String pluginName) { // check if toCompare depends on the current plugin String[] dependencyNames = plugin.getDependencyNames(); for (int i = 0; i < dependencyNames.length; i++) { final String dependencyName = dependencyNames[i]; if (pluginName.equals(dependencyName)) { return true; // we've establish that p does depend on plugin, so we can // break from this loop } } return false; }
[ "protected", "boolean", "isDependentOn", "(", "GrailsPlugin", "plugin", ",", "String", "pluginName", ")", "{", "// check if toCompare depends on the current plugin", "String", "[", "]", "dependencyNames", "=", "plugin", ".", "getDependencyNames", "(", ")", ";", "for", ...
Checks whether a plugin is dependent on another plugin with the specified name @param plugin the plugin to compare @param pluginName the name to compare against @return true if <code>plugin</code> depends on <code>pluginName</code>
[ "Checks", "whether", "a", "plugin", "is", "dependent", "on", "another", "plugin", "with", "the", "specified", "name" ]
train
https://github.com/grails/grails-core/blob/c0b08aa995b0297143b75d05642abba8cb7b4122/grails-core/src/main/groovy/org/grails/plugins/BasePluginFilter.java#L134-L150
CenturyLinkCloud/mdw
mdw-services/src/com/centurylink/mdw/listener/ListenerHelper.java
ListenerHelper.createErrorResponse
public Response createErrorResponse(String req, Map<String,String> metaInfo, ServiceException ex) { Request request = new Request(0L); request.setContent(req); Response response = new Response(); String contentType = metaInfo.get(Listener.METAINFO_CONTENT_TYPE); if (contentType == null && req != null && !req.isEmpty()) contentType = req.trim().startsWith("{") ? Listener.CONTENT_TYPE_JSON : Listener.CONTENT_TYPE_XML; if (contentType == null) contentType = Listener.CONTENT_TYPE_XML; // compatibility metaInfo.put(Listener.METAINFO_HTTP_STATUS_CODE, String.valueOf(ex.getCode())); StatusMessage statusMsg = new StatusMessage(); statusMsg.setCode(ex.getCode()); statusMsg.setMessage(ex.getMessage()); response.setStatusCode(statusMsg.getCode()); response.setStatusMessage(statusMsg.getMessage()); response.setPath(ServicePaths.getInboundResponsePath(metaInfo)); if (contentType.equals(Listener.CONTENT_TYPE_JSON)) { response.setContent(statusMsg.getJsonString()); } else { response.setContent(statusMsg.getXml()); } return response; }
java
public Response createErrorResponse(String req, Map<String,String> metaInfo, ServiceException ex) { Request request = new Request(0L); request.setContent(req); Response response = new Response(); String contentType = metaInfo.get(Listener.METAINFO_CONTENT_TYPE); if (contentType == null && req != null && !req.isEmpty()) contentType = req.trim().startsWith("{") ? Listener.CONTENT_TYPE_JSON : Listener.CONTENT_TYPE_XML; if (contentType == null) contentType = Listener.CONTENT_TYPE_XML; // compatibility metaInfo.put(Listener.METAINFO_HTTP_STATUS_CODE, String.valueOf(ex.getCode())); StatusMessage statusMsg = new StatusMessage(); statusMsg.setCode(ex.getCode()); statusMsg.setMessage(ex.getMessage()); response.setStatusCode(statusMsg.getCode()); response.setStatusMessage(statusMsg.getMessage()); response.setPath(ServicePaths.getInboundResponsePath(metaInfo)); if (contentType.equals(Listener.CONTENT_TYPE_JSON)) { response.setContent(statusMsg.getJsonString()); } else { response.setContent(statusMsg.getXml()); } return response; }
[ "public", "Response", "createErrorResponse", "(", "String", "req", ",", "Map", "<", "String", ",", "String", ">", "metaInfo", ",", "ServiceException", "ex", ")", "{", "Request", "request", "=", "new", "Request", "(", "0L", ")", ";", "request", ".", "setCon...
Create a default error message. To customized this response use a ServiceMonitor.
[ "Create", "a", "default", "error", "message", ".", "To", "customized", "this", "response", "use", "a", "ServiceMonitor", "." ]
train
https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-services/src/com/centurylink/mdw/listener/ListenerHelper.java#L629-L655
andkulikov/Transitions-Everywhere
library(1.x)/src/main/java/com/transitionseverywhere/Visibility.java
Visibility.onAppear
@Nullable public Animator onAppear(@NonNull ViewGroup sceneRoot, @Nullable TransitionValues startValues, int startVisibility, @Nullable TransitionValues endValues, int endVisibility) { if ((mMode & MODE_IN) != MODE_IN || endValues == null) { return null; } if (startValues == null) { VisibilityInfo parentVisibilityInfo = null; View endParent = (View) endValues.view.getParent(); TransitionValues startParentValues = getMatchedTransitionValues(endParent, false); TransitionValues endParentValues = getTransitionValues(endParent, false); parentVisibilityInfo = getVisibilityChangeInfo(startParentValues, endParentValues); if (parentVisibilityInfo.visibilityChange) { return null; } } final boolean isForcedVisibility = mForcedStartVisibility != -1 || mForcedEndVisibility != -1; if (isForcedVisibility) { // Make sure that we reverse the effect of onDisappear's setTransitionAlpha(0) Object savedAlpha = endValues.view.getTag(R.id.transitionAlpha); if (savedAlpha instanceof Float) { endValues.view.setAlpha((Float) savedAlpha); endValues.view.setTag(R.id.transitionAlpha, null); } } return onAppear(sceneRoot, endValues.view, startValues, endValues); }
java
@Nullable public Animator onAppear(@NonNull ViewGroup sceneRoot, @Nullable TransitionValues startValues, int startVisibility, @Nullable TransitionValues endValues, int endVisibility) { if ((mMode & MODE_IN) != MODE_IN || endValues == null) { return null; } if (startValues == null) { VisibilityInfo parentVisibilityInfo = null; View endParent = (View) endValues.view.getParent(); TransitionValues startParentValues = getMatchedTransitionValues(endParent, false); TransitionValues endParentValues = getTransitionValues(endParent, false); parentVisibilityInfo = getVisibilityChangeInfo(startParentValues, endParentValues); if (parentVisibilityInfo.visibilityChange) { return null; } } final boolean isForcedVisibility = mForcedStartVisibility != -1 || mForcedEndVisibility != -1; if (isForcedVisibility) { // Make sure that we reverse the effect of onDisappear's setTransitionAlpha(0) Object savedAlpha = endValues.view.getTag(R.id.transitionAlpha); if (savedAlpha instanceof Float) { endValues.view.setAlpha((Float) savedAlpha); endValues.view.setTag(R.id.transitionAlpha, null); } } return onAppear(sceneRoot, endValues.view, startValues, endValues); }
[ "@", "Nullable", "public", "Animator", "onAppear", "(", "@", "NonNull", "ViewGroup", "sceneRoot", ",", "@", "Nullable", "TransitionValues", "startValues", ",", "int", "startVisibility", ",", "@", "Nullable", "TransitionValues", "endValues", ",", "int", "endVisibilit...
The default implementation of this method calls {@link #onAppear(ViewGroup, View, TransitionValues, TransitionValues)}. Subclasses should override this method or {@link #onAppear(ViewGroup, View, TransitionValues, TransitionValues)}. if they need to create an Animator when targets appear. The method should only be called by the Visibility class; it is not intended to be called from external classes. @param sceneRoot The root of the transition hierarchy @param startValues The target values in the start scene @param startVisibility The target visibility in the start scene @param endValues The target values in the end scene @param endVisibility The target visibility in the end scene @return An Animator to be started at the appropriate time in the overall transition for this scene change. A null value means no animation should be run.
[ "The", "default", "implementation", "of", "this", "method", "calls", "{", "@link", "#onAppear", "(", "ViewGroup", "View", "TransitionValues", "TransitionValues", ")", "}", ".", "Subclasses", "should", "override", "this", "method", "or", "{", "@link", "#onAppear", ...
train
https://github.com/andkulikov/Transitions-Everywhere/blob/828efe5f152a2f05e2bfeee6254b74ad2269d4f1/library(1.x)/src/main/java/com/transitionseverywhere/Visibility.java#L299-L329
emfjson/emfjson-jackson
src/main/java/org/emfjson/jackson/databind/ser/ResourceSerializer.java
ResourceSerializer.serialize
@Override public void serialize(Resource value, JsonGenerator jg, SerializerProvider provider) throws IOException { if (value.getContents().size() == 1) { serializeOne(value.getContents().get(0), jg, provider); } else { jg.writeStartArray(); for (EObject o : value.getContents()) { serializeOne(o, jg, provider); } jg.writeEndArray(); } }
java
@Override public void serialize(Resource value, JsonGenerator jg, SerializerProvider provider) throws IOException { if (value.getContents().size() == 1) { serializeOne(value.getContents().get(0), jg, provider); } else { jg.writeStartArray(); for (EObject o : value.getContents()) { serializeOne(o, jg, provider); } jg.writeEndArray(); } }
[ "@", "Override", "public", "void", "serialize", "(", "Resource", "value", ",", "JsonGenerator", "jg", ",", "SerializerProvider", "provider", ")", "throws", "IOException", "{", "if", "(", "value", ".", "getContents", "(", ")", ".", "size", "(", ")", "==", "...
private final EcoreTypeFactory typeFactory = new EcoreTypeFactory();
[ "private", "final", "EcoreTypeFactory", "typeFactory", "=", "new", "EcoreTypeFactory", "()", ";" ]
train
https://github.com/emfjson/emfjson-jackson/blob/5f4488d1b07d499003351606cf76ee0c4ac39964/src/main/java/org/emfjson/jackson/databind/ser/ResourceSerializer.java#L27-L38
http-builder-ng/http-builder-ng
http-builder-ng-core/src/main/java/groovyx/net/http/optional/Html.java
Html.jsoupParse
public static Object jsoupParse(final ChainedHttpConfig config, final FromServer fromServer) { try { return Jsoup.parse(fromServer.getInputStream(), fromServer.getCharset().name(), fromServer.getUri().toString()); } catch (IOException e) { throw new TransportingException(e); } }
java
public static Object jsoupParse(final ChainedHttpConfig config, final FromServer fromServer) { try { return Jsoup.parse(fromServer.getInputStream(), fromServer.getCharset().name(), fromServer.getUri().toString()); } catch (IOException e) { throw new TransportingException(e); } }
[ "public", "static", "Object", "jsoupParse", "(", "final", "ChainedHttpConfig", "config", ",", "final", "FromServer", "fromServer", ")", "{", "try", "{", "return", "Jsoup", ".", "parse", "(", "fromServer", ".", "getInputStream", "(", ")", ",", "fromServer", "."...
Method that provides an HTML parser for response configuration (uses JSoup). @param config the chained configuration @param fromServer the server response adapter @return the parsed HTML content (a {@link Document} object)
[ "Method", "that", "provides", "an", "HTML", "parser", "for", "response", "configuration", "(", "uses", "JSoup", ")", "." ]
train
https://github.com/http-builder-ng/http-builder-ng/blob/865f37732c102c748d3db8b905199dac9222a525/http-builder-ng-core/src/main/java/groovyx/net/http/optional/Html.java#L73-L79
ops4j/org.ops4j.pax.logging
pax-logging-api/src/main/java/org/apache/logging/log4j/message/ParameterFormatter.java
ParameterFormatter.countArgumentPlaceholders3
static int countArgumentPlaceholders3(final char[] messagePattern, final int length, final int[] indices) { int result = 0; boolean isEscaped = false; for (int i = 0; i < length - 1; i++) { final char curChar = messagePattern[i]; if (curChar == ESCAPE_CHAR) { isEscaped = !isEscaped; } else if (curChar == DELIM_START) { if (!isEscaped && messagePattern[i + 1] == DELIM_STOP) { indices[result] = i; result++; i++; } isEscaped = false; } else { isEscaped = false; } } return result; }
java
static int countArgumentPlaceholders3(final char[] messagePattern, final int length, final int[] indices) { int result = 0; boolean isEscaped = false; for (int i = 0; i < length - 1; i++) { final char curChar = messagePattern[i]; if (curChar == ESCAPE_CHAR) { isEscaped = !isEscaped; } else if (curChar == DELIM_START) { if (!isEscaped && messagePattern[i + 1] == DELIM_STOP) { indices[result] = i; result++; i++; } isEscaped = false; } else { isEscaped = false; } } return result; }
[ "static", "int", "countArgumentPlaceholders3", "(", "final", "char", "[", "]", "messagePattern", ",", "final", "int", "length", ",", "final", "int", "[", "]", "indices", ")", "{", "int", "result", "=", "0", ";", "boolean", "isEscaped", "=", "false", ";", ...
Counts the number of unescaped placeholders in the given messagePattern. @param messagePattern the message pattern to be analyzed. @return the number of unescaped placeholders.
[ "Counts", "the", "number", "of", "unescaped", "placeholders", "in", "the", "given", "messagePattern", "." ]
train
https://github.com/ops4j/org.ops4j.pax.logging/blob/493de4e1db4fe9f981f3dd78b8e40e5bf2b2e59d/pax-logging-api/src/main/java/org/apache/logging/log4j/message/ParameterFormatter.java#L137-L156
OpenLiberty/open-liberty
dev/com.ibm.ws.crypto.ltpakeyutil/src/com/ibm/ws/crypto/ltpakeyutil/LTPAKeyFileUtilityImpl.java
LTPAKeyFileUtilityImpl.generateLTPAKeys
protected final Properties generateLTPAKeys(byte[] keyPasswordBytes, final String realm) throws Exception { Properties expProps = null; try { KeyEncryptor encryptor = new KeyEncryptor(keyPasswordBytes); LTPAKeyPair pair = LTPADigSignature.generateLTPAKeyPair(); byte[] publicKey = pair.getPublic().getEncoded(); byte[] privateKey = pair.getPrivate().getEncoded(); byte[] encryptedPrivateKey = encryptor.encrypt(privateKey); byte[] sharedKey = LTPACrypto.generate3DESKey(); // key length is 24 for 3DES byte[] encryptedSharedKey = encryptor.encrypt(sharedKey); String tmpShared = Base64Coder.base64EncodeToString(encryptedSharedKey); String tmpPrivate = Base64Coder.base64EncodeToString(encryptedPrivateKey); String tmpPublic = Base64Coder.base64EncodeToString(publicKey); expProps = new Properties(); expProps.put(KEYIMPORT_SECRETKEY, tmpShared); expProps.put(KEYIMPORT_PRIVATEKEY, tmpPrivate); expProps.put(KEYIMPORT_PUBLICKEY, tmpPublic); expProps.put(KEYIMPORT_REALM, realm); expProps.put(CREATION_HOST_PROPERTY, "localhost"); expProps.put(LTPA_VERSION_PROPERTY, "1.0"); expProps.put(CREATION_DATE_PROPERTY, (new java.util.Date()).toString()); } catch (Exception e) { throw e; } return expProps; }
java
protected final Properties generateLTPAKeys(byte[] keyPasswordBytes, final String realm) throws Exception { Properties expProps = null; try { KeyEncryptor encryptor = new KeyEncryptor(keyPasswordBytes); LTPAKeyPair pair = LTPADigSignature.generateLTPAKeyPair(); byte[] publicKey = pair.getPublic().getEncoded(); byte[] privateKey = pair.getPrivate().getEncoded(); byte[] encryptedPrivateKey = encryptor.encrypt(privateKey); byte[] sharedKey = LTPACrypto.generate3DESKey(); // key length is 24 for 3DES byte[] encryptedSharedKey = encryptor.encrypt(sharedKey); String tmpShared = Base64Coder.base64EncodeToString(encryptedSharedKey); String tmpPrivate = Base64Coder.base64EncodeToString(encryptedPrivateKey); String tmpPublic = Base64Coder.base64EncodeToString(publicKey); expProps = new Properties(); expProps.put(KEYIMPORT_SECRETKEY, tmpShared); expProps.put(KEYIMPORT_PRIVATEKEY, tmpPrivate); expProps.put(KEYIMPORT_PUBLICKEY, tmpPublic); expProps.put(KEYIMPORT_REALM, realm); expProps.put(CREATION_HOST_PROPERTY, "localhost"); expProps.put(LTPA_VERSION_PROPERTY, "1.0"); expProps.put(CREATION_DATE_PROPERTY, (new java.util.Date()).toString()); } catch (Exception e) { throw e; } return expProps; }
[ "protected", "final", "Properties", "generateLTPAKeys", "(", "byte", "[", "]", "keyPasswordBytes", ",", "final", "String", "realm", ")", "throws", "Exception", "{", "Properties", "expProps", "=", "null", ";", "try", "{", "KeyEncryptor", "encryptor", "=", "new", ...
Generates the LTPA keys and stores them into a Properties object. @param keyPasswordBytes @param realm @return @throws Exception
[ "Generates", "the", "LTPA", "keys", "and", "stores", "them", "into", "a", "Properties", "object", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.crypto.ltpakeyutil/src/com/ibm/ws/crypto/ltpakeyutil/LTPAKeyFileUtilityImpl.java#L45-L76
liferay/com-liferay-commerce
commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CPDefinitionInventoryPersistenceImpl.java
CPDefinitionInventoryPersistenceImpl.findAll
@Override public List<CPDefinitionInventory> findAll(int start, int end) { return findAll(start, end, null); }
java
@Override public List<CPDefinitionInventory> findAll(int start, int end) { return findAll(start, end, null); }
[ "@", "Override", "public", "List", "<", "CPDefinitionInventory", ">", "findAll", "(", "int", "start", ",", "int", "end", ")", "{", "return", "findAll", "(", "start", ",", "end", ",", "null", ")", ";", "}" ]
Returns a range of all the cp definition inventories. <p> Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CPDefinitionInventoryModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. </p> @param start the lower bound of the range of cp definition inventories @param end the upper bound of the range of cp definition inventories (not inclusive) @return the range of cp definition inventories
[ "Returns", "a", "range", "of", "all", "the", "cp", "definition", "inventories", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CPDefinitionInventoryPersistenceImpl.java#L2347-L2350
GenesysPureEngage/provisioning-client-java
src/main/java/com/genesys/internal/provisioning/api/OperationsApi.java
OperationsApi.getUsersAsync
public ApiAsyncSuccessResponse getUsersAsync(String aioId, Integer limit, Integer offset, String order, String sortBy, String filterName, String filterParameters, String roles, String skills, Boolean userEnabled, String userValid) throws ApiException { ApiResponse<ApiAsyncSuccessResponse> resp = getUsersAsyncWithHttpInfo(aioId, limit, offset, order, sortBy, filterName, filterParameters, roles, skills, userEnabled, userValid); return resp.getData(); }
java
public ApiAsyncSuccessResponse getUsersAsync(String aioId, Integer limit, Integer offset, String order, String sortBy, String filterName, String filterParameters, String roles, String skills, Boolean userEnabled, String userValid) throws ApiException { ApiResponse<ApiAsyncSuccessResponse> resp = getUsersAsyncWithHttpInfo(aioId, limit, offset, order, sortBy, filterName, filterParameters, roles, skills, userEnabled, userValid); return resp.getData(); }
[ "public", "ApiAsyncSuccessResponse", "getUsersAsync", "(", "String", "aioId", ",", "Integer", "limit", ",", "Integer", "offset", ",", "String", "order", ",", "String", "sortBy", ",", "String", "filterName", ",", "String", "filterParameters", ",", "String", "roles"...
Get users. 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) @return ApiAsyncSuccessResponse @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
[ "Get", "users", ".", "Get", "[", "CfgPerson", "]", "(", "https", ":", "//", "docs", ".", "genesys", ".", "com", "/", "Documentation", "/", "PSDK", "/", "latest", "/", "ConfigLayerRef", "/", "CfgPerson", ")", "objects", "based", "on", "the", "specified", ...
train
https://github.com/GenesysPureEngage/provisioning-client-java/blob/1ad594c3767cec83052168e350994f922a26f75e/src/main/java/com/genesys/internal/provisioning/api/OperationsApi.java#L651-L654
apache/groovy
subprojects/groovy-xml/src/main/java/groovy/util/XmlParser.java
XmlParser.createNode
protected Node createNode(Node parent, Object name, Map attributes) { return new Node(parent, name, attributes); }
java
protected Node createNode(Node parent, Object name, Map attributes) { return new Node(parent, name, attributes); }
[ "protected", "Node", "createNode", "(", "Node", "parent", ",", "Object", "name", ",", "Map", "attributes", ")", "{", "return", "new", "Node", "(", "parent", ",", "name", ",", "attributes", ")", ";", "}" ]
Creates a new node with the given parent, name, and attributes. The default implementation returns an instance of <code>groovy.util.Node</code>. @param parent the parent node, or null if the node being created is the root node @param name an Object representing the name of the node (typically an instance of {@link QName}) @param attributes a Map of attribute names to attribute values @return a new Node instance representing the current node
[ "Creates", "a", "new", "node", "with", "the", "given", "parent", "name", "and", "attributes", ".", "The", "default", "implementation", "returns", "an", "instance", "of", "<code", ">", "groovy", ".", "util", ".", "Node<", "/", "code", ">", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-xml/src/main/java/groovy/util/XmlParser.java#L473-L475
googleapis/cloud-bigtable-client
bigtable-client-core-parent/bigtable-client-core/src/main/java/com/google/cloud/bigtable/grpc/BigtableSession.java
BigtableSession.createChannelPool
public static ManagedChannel createChannelPool(final String host, final BigtableOptions options) throws IOException, GeneralSecurityException { return createChannelPool(host, options, 1); }
java
public static ManagedChannel createChannelPool(final String host, final BigtableOptions options) throws IOException, GeneralSecurityException { return createChannelPool(host, options, 1); }
[ "public", "static", "ManagedChannel", "createChannelPool", "(", "final", "String", "host", ",", "final", "BigtableOptions", "options", ")", "throws", "IOException", ",", "GeneralSecurityException", "{", "return", "createChannelPool", "(", "host", ",", "options", ",", ...
Create a new {@link com.google.cloud.bigtable.grpc.io.ChannelPool}, with auth headers. @param host a {@link String} object. @param options a {@link BigtableOptions} object. @return a {@link ChannelPool} object. @throws IOException if any. @throws GeneralSecurityException
[ "Create", "a", "new", "{", "@link", "com", ".", "google", ".", "cloud", ".", "bigtable", ".", "grpc", ".", "io", ".", "ChannelPool", "}", "with", "auth", "headers", "." ]
train
https://github.com/googleapis/cloud-bigtable-client/blob/53543f36e4d6f9ed1963640d91a35be2a2047656/bigtable-client-core-parent/bigtable-client-core/src/main/java/com/google/cloud/bigtable/grpc/BigtableSession.java#L563-L566
apache/incubator-druid
processing/src/main/java/org/apache/druid/segment/serde/ComplexMetricSerde.java
ComplexMetricSerde.getSerializer
public GenericColumnSerializer getSerializer(SegmentWriteOutMedium segmentWriteOutMedium, String column) { return ComplexColumnSerializer.create(segmentWriteOutMedium, column, this.getObjectStrategy()); }
java
public GenericColumnSerializer getSerializer(SegmentWriteOutMedium segmentWriteOutMedium, String column) { return ComplexColumnSerializer.create(segmentWriteOutMedium, column, this.getObjectStrategy()); }
[ "public", "GenericColumnSerializer", "getSerializer", "(", "SegmentWriteOutMedium", "segmentWriteOutMedium", ",", "String", "column", ")", "{", "return", "ComplexColumnSerializer", ".", "create", "(", "segmentWriteOutMedium", ",", "column", ",", "this", ".", "getObjectStr...
This method provides the ability for a ComplexMetricSerde to control its own serialization. For large column (i.e columns greater than {@link Integer#MAX_VALUE}) use {@link LargeColumnSupportedComplexColumnSerializer} @return an instance of GenericColumnSerializer used for serialization.
[ "This", "method", "provides", "the", "ability", "for", "a", "ComplexMetricSerde", "to", "control", "its", "own", "serialization", ".", "For", "large", "column", "(", "i", ".", "e", "columns", "greater", "than", "{", "@link", "Integer#MAX_VALUE", "}", ")", "u...
train
https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/processing/src/main/java/org/apache/druid/segment/serde/ComplexMetricSerde.java#L120-L123
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/classification/Evaluation.java
Evaluation.falsePositiveRate
public double falsePositiveRate(int classLabel, double edgeCase) { double fpCount = falsePositives.getCount(classLabel); double tnCount = trueNegatives.getCount(classLabel); return EvaluationUtils.falsePositiveRate((long) fpCount, (long) tnCount, edgeCase); }
java
public double falsePositiveRate(int classLabel, double edgeCase) { double fpCount = falsePositives.getCount(classLabel); double tnCount = trueNegatives.getCount(classLabel); return EvaluationUtils.falsePositiveRate((long) fpCount, (long) tnCount, edgeCase); }
[ "public", "double", "falsePositiveRate", "(", "int", "classLabel", ",", "double", "edgeCase", ")", "{", "double", "fpCount", "=", "falsePositives", ".", "getCount", "(", "classLabel", ")", ";", "double", "tnCount", "=", "trueNegatives", ".", "getCount", "(", "...
Returns the false positive rate for a given label @param classLabel the label @param edgeCase What to output in case of 0/0 @return fpr as a double
[ "Returns", "the", "false", "positive", "rate", "for", "a", "given", "label" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/classification/Evaluation.java#L1048-L1053
Wolfgang-Schuetzelhofer/jcypher
src/main/java/iot/jcypher/database/DBAccessFactory.java
DBAccessFactory.createDBAccess
public static IDBAccess createDBAccess(DBType dbType, Properties properties) { return createDBAccess(dbType, properties, null, null, null); }
java
public static IDBAccess createDBAccess(DBType dbType, Properties properties) { return createDBAccess(dbType, properties, null, null, null); }
[ "public", "static", "IDBAccess", "createDBAccess", "(", "DBType", "dbType", ",", "Properties", "properties", ")", "{", "return", "createDBAccess", "(", "dbType", ",", "properties", ",", "null", ",", "null", ",", "null", ")", ";", "}" ]
create an IDBAccess (an accessor) for a specific database. @param dbType the type of database to access. Can be <br/>DBType.REMOTE or DBType.EMBEDDED or DBType.IN_MEMORY @param properties to configure the database connection. <br/>The appropriate database access class will pick the properties it needs. <br/>See also: DBProperties interface for required and optional properties. @return an instance of IDBAccess
[ "create", "an", "IDBAccess", "(", "an", "accessor", ")", "for", "a", "specific", "database", "." ]
train
https://github.com/Wolfgang-Schuetzelhofer/jcypher/blob/0f36914b4d6993a004cc235bb18dd3e02a59d253/src/main/java/iot/jcypher/database/DBAccessFactory.java#L61-L63
elki-project/elki
elki-core-util/src/main/java/de/lmu/ifi/dbs/elki/utilities/ClassGenericsUtil.java
ClassGenericsUtil.parameterizeOrAbort
@SuppressWarnings("unchecked") public static <C> C parameterizeOrAbort(Class<?> c, Parameterization config) { try { C ret = tryInstantiate((Class<C>) c, c, config); if(ret == null) { throw new AbortException("Could not instantiate class. Check parameters."); } return ret; } catch(Exception e) { if(config.hasErrors()) { for(ParameterException err : config.getErrors()) { LOG.warning(err.toString()); } } throw e instanceof AbortException ? (AbortException) e : new AbortException("Instantiation failed", e); } }
java
@SuppressWarnings("unchecked") public static <C> C parameterizeOrAbort(Class<?> c, Parameterization config) { try { C ret = tryInstantiate((Class<C>) c, c, config); if(ret == null) { throw new AbortException("Could not instantiate class. Check parameters."); } return ret; } catch(Exception e) { if(config.hasErrors()) { for(ParameterException err : config.getErrors()) { LOG.warning(err.toString()); } } throw e instanceof AbortException ? (AbortException) e : new AbortException("Instantiation failed", e); } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "<", "C", ">", "C", "parameterizeOrAbort", "(", "Class", "<", "?", ">", "c", ",", "Parameterization", "config", ")", "{", "try", "{", "C", "ret", "=", "tryInstantiate", "(", "(", "Cl...
Force parameterization method. <p> Please use this only in "runner" classes such as unit tests, since the error handling is not very flexible. @param <C> Type @param c Class to instantiate @param config Parameters @return Instance or throw an AbortException
[ "Force", "parameterization", "method", ".", "<p", ">", "Please", "use", "this", "only", "in", "runner", "classes", "such", "as", "unit", "tests", "since", "the", "error", "handling", "is", "not", "very", "flexible", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-util/src/main/java/de/lmu/ifi/dbs/elki/utilities/ClassGenericsUtil.java#L200-L217
jtablesaw/tablesaw
core/src/main/java/tech/tablesaw/api/Table.java
Table.doWithRowPairs
public void doWithRowPairs(Consumer<RowPair> pairConsumer) { if (isEmpty()) { return; } Row row1 = new Row(this); Row row2 = new Row(this); RowPair pair = new RowPair(row1, row2); int max = rowCount(); for (int i = 1; i < max; i++) { row1.at(i - 1); row2.at(i); pairConsumer.accept(pair); } }
java
public void doWithRowPairs(Consumer<RowPair> pairConsumer) { if (isEmpty()) { return; } Row row1 = new Row(this); Row row2 = new Row(this); RowPair pair = new RowPair(row1, row2); int max = rowCount(); for (int i = 1; i < max; i++) { row1.at(i - 1); row2.at(i); pairConsumer.accept(pair); } }
[ "public", "void", "doWithRowPairs", "(", "Consumer", "<", "RowPair", ">", "pairConsumer", ")", "{", "if", "(", "isEmpty", "(", ")", ")", "{", "return", ";", "}", "Row", "row1", "=", "new", "Row", "(", "this", ")", ";", "Row", "row2", "=", "new", "R...
Applies the function in {@code pairConsumer} to each consecutive pairs of rows in the table
[ "Applies", "the", "function", "in", "{" ]
train
https://github.com/jtablesaw/tablesaw/blob/68a75b4098ac677e9486df5572cf13ec39f9f701/core/src/main/java/tech/tablesaw/api/Table.java#L1065-L1078
apache/incubator-gobblin
gobblin-service/src/main/java/org/apache/gobblin/service/modules/orchestration/Orchestrator.java
Orchestrator.canRun
private boolean canRun(String flowName, String flowGroup, boolean allowConcurrentExecution) { if (allowConcurrentExecution) { return true; } else { return !flowStatusGenerator.isFlowRunning(flowName, flowGroup); } }
java
private boolean canRun(String flowName, String flowGroup, boolean allowConcurrentExecution) { if (allowConcurrentExecution) { return true; } else { return !flowStatusGenerator.isFlowRunning(flowName, flowGroup); } }
[ "private", "boolean", "canRun", "(", "String", "flowName", ",", "String", "flowGroup", ",", "boolean", "allowConcurrentExecution", ")", "{", "if", "(", "allowConcurrentExecution", ")", "{", "return", "true", ";", "}", "else", "{", "return", "!", "flowStatusGener...
Check if the flow instance is allowed to run. @param flowName @param flowGroup @param allowConcurrentExecution @return true if the {@link FlowSpec} allows concurrent executions or if no other instance of the flow is currently RUNNING.
[ "Check", "if", "the", "flow", "instance", "is", "allowed", "to", "run", "." ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-service/src/main/java/org/apache/gobblin/service/modules/orchestration/Orchestrator.java#L315-L321
liferay/com-liferay-commerce
commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceWarehousePersistenceImpl.java
CommerceWarehousePersistenceImpl.findByGroupId
@Override public List<CommerceWarehouse> findByGroupId(long groupId, int start, int end) { return findByGroupId(groupId, start, end, null); }
java
@Override public List<CommerceWarehouse> findByGroupId(long groupId, int start, int end) { return findByGroupId(groupId, start, end, null); }
[ "@", "Override", "public", "List", "<", "CommerceWarehouse", ">", "findByGroupId", "(", "long", "groupId", ",", "int", "start", ",", "int", "end", ")", "{", "return", "findByGroupId", "(", "groupId", ",", "start", ",", "end", ",", "null", ")", ";", "}" ]
Returns a range of all the commerce warehouses where groupId = &#63;. <p> Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommerceWarehouseModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. </p> @param groupId the group ID @param start the lower bound of the range of commerce warehouses @param end the upper bound of the range of commerce warehouses (not inclusive) @return the range of matching commerce warehouses
[ "Returns", "a", "range", "of", "all", "the", "commerce", "warehouses", "where", "groupId", "=", "&#63", ";", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceWarehousePersistenceImpl.java#L141-L145
etnetera/seb
src/main/java/cz/etnetera/seb/listener/SebListener.java
SebListener.saveFile
protected void saveFile(SebEvent event, byte[] bytes, String name, String extension) { event.saveFile(bytes, getListenerFileName(name), extension); }
java
protected void saveFile(SebEvent event, byte[] bytes, String name, String extension) { event.saveFile(bytes, getListenerFileName(name), extension); }
[ "protected", "void", "saveFile", "(", "SebEvent", "event", ",", "byte", "[", "]", "bytes", ",", "String", "name", ",", "String", "extension", ")", "{", "event", ".", "saveFile", "(", "bytes", ",", "getListenerFileName", "(", "name", ")", ",", "extension", ...
Save bytes into output file with given name and extension. @param event @param bytes @param name @param extension
[ "Save", "bytes", "into", "output", "file", "with", "given", "name", "and", "extension", "." ]
train
https://github.com/etnetera/seb/blob/6aed29c7726db12f440c60cfd253de229064ed04/src/main/java/cz/etnetera/seb/listener/SebListener.java#L449-L451
apache/incubator-druid
core/src/main/java/org/apache/druid/java/util/common/lifecycle/Lifecycle.java
Lifecycle.addManagedInstance
public <T> T addManagedInstance(T o, Stage stage) { addHandler(new AnnotationBasedHandler(o), stage); return o; }
java
public <T> T addManagedInstance(T o, Stage stage) { addHandler(new AnnotationBasedHandler(o), stage); return o; }
[ "public", "<", "T", ">", "T", "addManagedInstance", "(", "T", "o", ",", "Stage", "stage", ")", "{", "addHandler", "(", "new", "AnnotationBasedHandler", "(", "o", ")", ",", "stage", ")", ";", "return", "o", ";", "}" ]
Adds a "managed" instance (annotated with {@link LifecycleStart} and {@link LifecycleStop}) to the Lifecycle. If the lifecycle has already been started, it throws an {@link ISE} @param o The object to add to the lifecycle @param stage The stage to add the lifecycle at @throws ISE {@link Lifecycle#addHandler(Handler, Stage)}
[ "Adds", "a", "managed", "instance", "(", "annotated", "with", "{", "@link", "LifecycleStart", "}", "and", "{", "@link", "LifecycleStop", "}", ")", "to", "the", "Lifecycle", ".", "If", "the", "lifecycle", "has", "already", "been", "started", "it", "throws", ...
train
https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/core/src/main/java/org/apache/druid/java/util/common/lifecycle/Lifecycle.java#L139-L143
cdapio/tigon
tigon-yarn/src/main/java/co/cask/tigon/internal/io/FieldAccessorGenerator.java
FieldAccessorGenerator.invokeReflection
private void invokeReflection(Method method, String signature) { GeneratorAdapter mg = new GeneratorAdapter(Opcodes.ACC_PUBLIC, method, signature, new Type[0], classWriter); /** * try { * // Call method * } catch (IllegalAccessException e) { * throw Throwables.propagate(e); * } */ Label beginTry = mg.newLabel(); Label endTry = mg.newLabel(); Label catchHandle = mg.newLabel(); mg.visitTryCatchBlock(beginTry, endTry, catchHandle, Type.getInternalName(IllegalAccessException.class)); mg.mark(beginTry); mg.loadThis(); mg.getField(Type.getObjectType(className), "field", Type.getType(Field.class)); mg.loadArgs(); mg.invokeVirtual(Type.getType(Field.class), method); mg.mark(endTry); mg.returnValue(); mg.mark(catchHandle); int exception = mg.newLocal(Type.getType(IllegalAccessException.class)); mg.storeLocal(exception); mg.loadLocal(exception); mg.invokeStatic(Type.getType(Throwables.class), getMethod(RuntimeException.class, "propagate", Throwable.class)); mg.throwException(); mg.endMethod(); }
java
private void invokeReflection(Method method, String signature) { GeneratorAdapter mg = new GeneratorAdapter(Opcodes.ACC_PUBLIC, method, signature, new Type[0], classWriter); /** * try { * // Call method * } catch (IllegalAccessException e) { * throw Throwables.propagate(e); * } */ Label beginTry = mg.newLabel(); Label endTry = mg.newLabel(); Label catchHandle = mg.newLabel(); mg.visitTryCatchBlock(beginTry, endTry, catchHandle, Type.getInternalName(IllegalAccessException.class)); mg.mark(beginTry); mg.loadThis(); mg.getField(Type.getObjectType(className), "field", Type.getType(Field.class)); mg.loadArgs(); mg.invokeVirtual(Type.getType(Field.class), method); mg.mark(endTry); mg.returnValue(); mg.mark(catchHandle); int exception = mg.newLocal(Type.getType(IllegalAccessException.class)); mg.storeLocal(exception); mg.loadLocal(exception); mg.invokeStatic(Type.getType(Throwables.class), getMethod(RuntimeException.class, "propagate", Throwable.class)); mg.throwException(); mg.endMethod(); }
[ "private", "void", "invokeReflection", "(", "Method", "method", ",", "String", "signature", ")", "{", "GeneratorAdapter", "mg", "=", "new", "GeneratorAdapter", "(", "Opcodes", ".", "ACC_PUBLIC", ",", "method", ",", "signature", ",", "new", "Type", "[", "0", ...
Generates the try-catch block that wrap around the given reflection method call. @param method The method to be called within the try-catch block.
[ "Generates", "the", "try", "-", "catch", "block", "that", "wrap", "around", "the", "given", "reflection", "method", "call", "." ]
train
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-yarn/src/main/java/co/cask/tigon/internal/io/FieldAccessorGenerator.java#L193-L222
threerings/nenya
core/src/main/java/com/threerings/miso/client/MisoScenePanel.java
MisoScenePanel.getTipIcon
protected Icon getTipIcon (SceneObject scobj, String action) { ObjectActionHandler oah = ObjectActionHandler.lookup(action); return (oah == null) ? null : oah.getTipIcon(action); }
java
protected Icon getTipIcon (SceneObject scobj, String action) { ObjectActionHandler oah = ObjectActionHandler.lookup(action); return (oah == null) ? null : oah.getTipIcon(action); }
[ "protected", "Icon", "getTipIcon", "(", "SceneObject", "scobj", ",", "String", "action", ")", "{", "ObjectActionHandler", "oah", "=", "ObjectActionHandler", ".", "lookup", "(", "action", ")", ";", "return", "(", "oah", "==", "null", ")", "?", "null", ":", ...
Provides an icon for this tooltip, the default looks up an object action handler for the action and requests the icon from it.
[ "Provides", "an", "icon", "for", "this", "tooltip", "the", "default", "looks", "up", "an", "object", "action", "handler", "for", "the", "action", "and", "requests", "the", "icon", "from", "it", "." ]
train
https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/miso/client/MisoScenePanel.java#L1093-L1097
Azure/azure-sdk-for-java
keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java
KeyVaultClientBaseImpl.restoreKeyAsync
public ServiceFuture<KeyBundle> restoreKeyAsync(String vaultBaseUrl, byte[] keyBundleBackup, final ServiceCallback<KeyBundle> serviceCallback) { return ServiceFuture.fromResponse(restoreKeyWithServiceResponseAsync(vaultBaseUrl, keyBundleBackup), serviceCallback); }
java
public ServiceFuture<KeyBundle> restoreKeyAsync(String vaultBaseUrl, byte[] keyBundleBackup, final ServiceCallback<KeyBundle> serviceCallback) { return ServiceFuture.fromResponse(restoreKeyWithServiceResponseAsync(vaultBaseUrl, keyBundleBackup), serviceCallback); }
[ "public", "ServiceFuture", "<", "KeyBundle", ">", "restoreKeyAsync", "(", "String", "vaultBaseUrl", ",", "byte", "[", "]", "keyBundleBackup", ",", "final", "ServiceCallback", "<", "KeyBundle", ">", "serviceCallback", ")", "{", "return", "ServiceFuture", ".", "from...
Restores a backed up key to a vault. Imports a previously backed up key into Azure Key Vault, restoring the key, its key identifier, attributes and access control policies. The RESTORE operation may be used to import a previously backed up key. Individual versions of a key cannot be restored. The key is restored in its entirety with the same key name as it had when it was backed up. If the key name is not available in the target Key Vault, the RESTORE operation will be rejected. While the key name is retained during restore, the final key identifier will change if the key is restored to a different vault. Restore will restore all versions and preserve version identifiers. The RESTORE operation is subject to security constraints: The target Key Vault must be owned by the same Microsoft Azure Subscription as the source Key Vault The user must have RESTORE permission in the target Key Vault. This operation requires the keys/restore permission. @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. @param keyBundleBackup The backup blob associated with a key bundle. @param serviceCallback the async ServiceCallback to handle successful and failed responses. @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceFuture} object
[ "Restores", "a", "backed", "up", "key", "to", "a", "vault", ".", "Imports", "a", "previously", "backed", "up", "key", "into", "Azure", "Key", "Vault", "restoring", "the", "key", "its", "key", "identifier", "attributes", "and", "access", "control", "policies"...
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#L2067-L2069
wellner/jcarafe
jcarafe-core/src/main/java/org/mitre/jcarafe/jarafe/JarafeMEDecoder.java
JarafeMEDecoder.classifyInstanceDistribution
public List<StringDoublePair> classifyInstanceDistribution(List<String> features) { List<scala.Tuple2<String,Double>> r = maxEnt.decodeInstanceAsDistribution(features); List<StringDoublePair> res = new ArrayList<StringDoublePair>(); for (scala.Tuple2<String,Double> el : r) { res.add(new StringDoublePair(el._1, el._2)); } return res; }
java
public List<StringDoublePair> classifyInstanceDistribution(List<String> features) { List<scala.Tuple2<String,Double>> r = maxEnt.decodeInstanceAsDistribution(features); List<StringDoublePair> res = new ArrayList<StringDoublePair>(); for (scala.Tuple2<String,Double> el : r) { res.add(new StringDoublePair(el._1, el._2)); } return res; }
[ "public", "List", "<", "StringDoublePair", ">", "classifyInstanceDistribution", "(", "List", "<", "String", ">", "features", ")", "{", "List", "<", "scala", ".", "Tuple2", "<", "String", ",", "Double", ">", ">", "r", "=", "maxEnt", ".", "decodeInstanceAsDist...
/* @param features - A list of strings representing the features for a classification instance @return labelposteriorpair list - A list of pairs that include each label and a posterior probability mass
[ "/", "*" ]
train
https://github.com/wellner/jcarafe/blob/ab8b0a83dbf600fe80c27711815c90bd3055b217/jcarafe-core/src/main/java/org/mitre/jcarafe/jarafe/JarafeMEDecoder.java#L51-L58
Falydoor/limesurvey-rc
src/main/java/com/github/falydoor/limesurveyrc/LimesurveyRC.java
LimesurveyRC.getQuestions
public Stream<LsQuestion> getQuestions(int surveyId) throws LimesurveyRCException { return getGroups(surveyId).flatMap(group -> { try { return getQuestionsFromGroup(surveyId, group.getId()); } catch (LimesurveyRCException e) { LOGGER.error("Unable to get questions from group " + group.getId(), e); } return Stream.empty(); }); }
java
public Stream<LsQuestion> getQuestions(int surveyId) throws LimesurveyRCException { return getGroups(surveyId).flatMap(group -> { try { return getQuestionsFromGroup(surveyId, group.getId()); } catch (LimesurveyRCException e) { LOGGER.error("Unable to get questions from group " + group.getId(), e); } return Stream.empty(); }); }
[ "public", "Stream", "<", "LsQuestion", ">", "getQuestions", "(", "int", "surveyId", ")", "throws", "LimesurveyRCException", "{", "return", "getGroups", "(", "surveyId", ")", ".", "flatMap", "(", "group", "->", "{", "try", "{", "return", "getQuestionsFromGroup", ...
Gets questions from a survey. The questions are ordered using the "group_order" field from the groups and then the "question_order" field from the questions @param surveyId the survey id of the survey you want to get the questions @return a stream of questions in an ordered order @throws LimesurveyRCException the limesurvey rc exception
[ "Gets", "questions", "from", "a", "survey", ".", "The", "questions", "are", "ordered", "using", "the", "group_order", "field", "from", "the", "groups", "and", "then", "the", "question_order", "field", "from", "the", "questions" ]
train
https://github.com/Falydoor/limesurvey-rc/blob/b8d573389086395e46a0bdeeddeef4d1c2c0a488/src/main/java/com/github/falydoor/limesurveyrc/LimesurveyRC.java#L204-L213
alkacon/opencms-core
src/org/opencms/workplace/editors/directedit/CmsDirectEditDefaultProvider.java
CmsDirectEditDefaultProvider.startDirectEditDisabled
public String startDirectEditDisabled(CmsDirectEditParams params, CmsDirectEditResourceInfo resourceInfo) { String editId = getNextDirectEditId(); StringBuffer result = new StringBuffer(256); result.append("<!-- EDIT BLOCK START (DISABLED): "); result.append(params.m_resourceName); result.append(" ["); result.append(resourceInfo.getResource().getState()); result.append("] "); if (!resourceInfo.getLock().isUnlocked()) { result.append(" locked "); result.append(resourceInfo.getLock().getProject().getName()); } result.append(" -->\n"); result.append("<script type=\"text/javascript\">\n"); result.append("registerButtonOcms(\"").append(editId).append("\");\n"); result.append("</script>\n"); result.append("<div class=\"ocms_de_bt\" id=\"buttons_").append(editId).append("\">\n"); result.append("<span onmouseover=\"activateOcms(\'").append(editId).append( "\');\" onmouseout=\"deactivateOcms(\'").append(editId).append("\');\">\n"); result.append("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" id=\"table_").append(editId).append( "\"><tr>\n"); result.append("<td class=\"ocms_de\"><span class=\"ocms_disabled\">"); if (m_editButtonStyle == 1) { result.append("<span class=\"ocms_combobutton\" style=\"background-image: url(\'").append( CmsWorkplace.getSkinUri()).append("buttons/directedit_in.png\');\">&nbsp;").append( m_messages.key(Messages.GUI_EDITOR_FRONTEND_BUTTON_LOCKED_0)).append("</span>"); } else if (m_editButtonStyle == 2) { result.append("<span class=\"ocms_combobutton\" style=\"padding-left: 4px;\">").append( m_messages.key(Messages.GUI_EDITOR_FRONTEND_BUTTON_LOCKED_0)).append("</span>"); } else { result.append("<img border=\"0\" src=\"").append(CmsWorkplace.getSkinUri()).append( "buttons/directedit_in.png\" title=\"").append( m_messages.key(Messages.GUI_EDITOR_FRONTEND_BUTTON_LOCKED_0)).append("\" alt=\"\"/>"); } result.append("</span></td>\n"); result.append("</tr></table>\n"); result.append("</span>\n"); result.append("</div>\n"); result.append("<div id=\"").append(editId).append("\" class=\"ocms_de_norm\">\n"); return result.toString(); }
java
public String startDirectEditDisabled(CmsDirectEditParams params, CmsDirectEditResourceInfo resourceInfo) { String editId = getNextDirectEditId(); StringBuffer result = new StringBuffer(256); result.append("<!-- EDIT BLOCK START (DISABLED): "); result.append(params.m_resourceName); result.append(" ["); result.append(resourceInfo.getResource().getState()); result.append("] "); if (!resourceInfo.getLock().isUnlocked()) { result.append(" locked "); result.append(resourceInfo.getLock().getProject().getName()); } result.append(" -->\n"); result.append("<script type=\"text/javascript\">\n"); result.append("registerButtonOcms(\"").append(editId).append("\");\n"); result.append("</script>\n"); result.append("<div class=\"ocms_de_bt\" id=\"buttons_").append(editId).append("\">\n"); result.append("<span onmouseover=\"activateOcms(\'").append(editId).append( "\');\" onmouseout=\"deactivateOcms(\'").append(editId).append("\');\">\n"); result.append("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" id=\"table_").append(editId).append( "\"><tr>\n"); result.append("<td class=\"ocms_de\"><span class=\"ocms_disabled\">"); if (m_editButtonStyle == 1) { result.append("<span class=\"ocms_combobutton\" style=\"background-image: url(\'").append( CmsWorkplace.getSkinUri()).append("buttons/directedit_in.png\');\">&nbsp;").append( m_messages.key(Messages.GUI_EDITOR_FRONTEND_BUTTON_LOCKED_0)).append("</span>"); } else if (m_editButtonStyle == 2) { result.append("<span class=\"ocms_combobutton\" style=\"padding-left: 4px;\">").append( m_messages.key(Messages.GUI_EDITOR_FRONTEND_BUTTON_LOCKED_0)).append("</span>"); } else { result.append("<img border=\"0\" src=\"").append(CmsWorkplace.getSkinUri()).append( "buttons/directedit_in.png\" title=\"").append( m_messages.key(Messages.GUI_EDITOR_FRONTEND_BUTTON_LOCKED_0)).append("\" alt=\"\"/>"); } result.append("</span></td>\n"); result.append("</tr></table>\n"); result.append("</span>\n"); result.append("</div>\n"); result.append("<div id=\"").append(editId).append("\" class=\"ocms_de_norm\">\n"); return result.toString(); }
[ "public", "String", "startDirectEditDisabled", "(", "CmsDirectEditParams", "params", ",", "CmsDirectEditResourceInfo", "resourceInfo", ")", "{", "String", "editId", "=", "getNextDirectEditId", "(", ")", ";", "StringBuffer", "result", "=", "new", "StringBuffer", "(", "...
Returns the start HTML for a disabled direct edit button.<p> @param params the direct edit parameters @param resourceInfo contains information about the resource to edit @return the start HTML for a disabled direct edit button
[ "Returns", "the", "start", "HTML", "for", "a", "disabled", "direct", "edit", "button", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/workplace/editors/directedit/CmsDirectEditDefaultProvider.java#L213-L257
aws/aws-sdk-java
aws-java-sdk-cognitoidp/src/main/java/com/amazonaws/services/cognitoidp/model/AdminInitiateAuthRequest.java
AdminInitiateAuthRequest.withClientMetadata
public AdminInitiateAuthRequest withClientMetadata(java.util.Map<String, String> clientMetadata) { setClientMetadata(clientMetadata); return this; }
java
public AdminInitiateAuthRequest withClientMetadata(java.util.Map<String, String> clientMetadata) { setClientMetadata(clientMetadata); return this; }
[ "public", "AdminInitiateAuthRequest", "withClientMetadata", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "clientMetadata", ")", "{", "setClientMetadata", "(", "clientMetadata", ")", ";", "return", "this", ";", "}" ]
<p> This is a random key-value pair map which can contain any key and will be passed to your PreAuthentication Lambda trigger as-is. It can be used to implement additional validations around authentication. </p> @param clientMetadata This is a random key-value pair map which can contain any key and will be passed to your PreAuthentication Lambda trigger as-is. It can be used to implement additional validations around authentication. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "This", "is", "a", "random", "key", "-", "value", "pair", "map", "which", "can", "contain", "any", "key", "and", "will", "be", "passed", "to", "your", "PreAuthentication", "Lambda", "trigger", "as", "-", "is", ".", "It", "can", "be", "used",...
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-cognitoidp/src/main/java/com/amazonaws/services/cognitoidp/model/AdminInitiateAuthRequest.java#L1107-L1110
IBM/ibm-cos-sdk-java
ibm-cos-java-sdk-kms/src/main/java/com/ibm/cloud/objectstorage/services/kms/model/ReEncryptRequest.java
ReEncryptRequest.setDestinationEncryptionContext
public void setDestinationEncryptionContext(java.util.Map<String, String> destinationEncryptionContext) { this.destinationEncryptionContext = destinationEncryptionContext == null ? null : new com.ibm.cloud.objectstorage.internal.SdkInternalMap<String, String>( destinationEncryptionContext); }
java
public void setDestinationEncryptionContext(java.util.Map<String, String> destinationEncryptionContext) { this.destinationEncryptionContext = destinationEncryptionContext == null ? null : new com.ibm.cloud.objectstorage.internal.SdkInternalMap<String, String>( destinationEncryptionContext); }
[ "public", "void", "setDestinationEncryptionContext", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "destinationEncryptionContext", ")", "{", "this", ".", "destinationEncryptionContext", "=", "destinationEncryptionContext", "==", "null", "?",...
<p> Encryption context to use when the data is reencrypted. </p> @param destinationEncryptionContext Encryption context to use when the data is reencrypted.
[ "<p", ">", "Encryption", "context", "to", "use", "when", "the", "data", "is", "reencrypted", ".", "<", "/", "p", ">" ]
train
https://github.com/IBM/ibm-cos-sdk-java/blob/d0bb2dd754c328a05e7dba8dc42e28b271b6daf2/ibm-cos-java-sdk-kms/src/main/java/com/ibm/cloud/objectstorage/services/kms/model/ReEncryptRequest.java#L421-L424
classgraph/classgraph
src/main/java/nonapi/io/github/classgraph/json/ClassFieldCache.java
ClassFieldCache.get
ClassFields get(final Class<?> cls) { ClassFields classFields = classToClassFields.get(cls); if (classFields == null) { classToClassFields.put(cls, classFields = new ClassFields(cls, resolveTypes, onlySerializePublicFields, this)); } return classFields; }
java
ClassFields get(final Class<?> cls) { ClassFields classFields = classToClassFields.get(cls); if (classFields == null) { classToClassFields.put(cls, classFields = new ClassFields(cls, resolveTypes, onlySerializePublicFields, this)); } return classFields; }
[ "ClassFields", "get", "(", "final", "Class", "<", "?", ">", "cls", ")", "{", "ClassFields", "classFields", "=", "classToClassFields", ".", "get", "(", "cls", ")", ";", "if", "(", "classFields", "==", "null", ")", "{", "classToClassFields", ".", "put", "(...
For a given resolved type, find the visible and accessible fields, resolve the types of any generically typed fields, and return the resolved fields. @param cls the cls @return the class fields
[ "For", "a", "given", "resolved", "type", "find", "the", "visible", "and", "accessible", "fields", "resolve", "the", "types", "of", "any", "generically", "typed", "fields", "and", "return", "the", "resolved", "fields", "." ]
train
https://github.com/classgraph/classgraph/blob/c8c8b2ca1eb76339f69193fdac33d735c864215c/src/main/java/nonapi/io/github/classgraph/json/ClassFieldCache.java#L131-L138
artikcloud/artikcloud-java
src/main/java/cloud/artik/api/DevicesSharesApi.java
DevicesSharesApi.getSharingForDevice
public DeviceSharing getSharingForDevice(String deviceId, String shareId) throws ApiException { ApiResponse<DeviceSharing> resp = getSharingForDeviceWithHttpInfo(deviceId, shareId); return resp.getData(); }
java
public DeviceSharing getSharingForDevice(String deviceId, String shareId) throws ApiException { ApiResponse<DeviceSharing> resp = getSharingForDeviceWithHttpInfo(deviceId, shareId); return resp.getData(); }
[ "public", "DeviceSharing", "getSharingForDevice", "(", "String", "deviceId", ",", "String", "shareId", ")", "throws", "ApiException", "{", "ApiResponse", "<", "DeviceSharing", ">", "resp", "=", "getSharingForDeviceWithHttpInfo", "(", "deviceId", ",", "shareId", ")", ...
Get specific share of the given device id Get specific share of the given device id @param deviceId Device ID. (required) @param shareId Share ID. (required) @return DeviceSharing @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
[ "Get", "specific", "share", "of", "the", "given", "device", "id", "Get", "specific", "share", "of", "the", "given", "device", "id" ]
train
https://github.com/artikcloud/artikcloud-java/blob/412f447573e7796ab4f685c0bdd5eb76185a365c/src/main/java/cloud/artik/api/DevicesSharesApi.java#L518-L521
playn/playn
core/src/playn/core/Scale.java
Scale.getScaledResources
public List<ScaledResource> getScaledResources(String path) { List<ScaledResource> rsrcs = new ArrayList<ScaledResource>(); rsrcs.add(new ScaledResource(this, computePath(path, factor))); for (float rscale = MathUtil.iceil(factor); rscale > 1; rscale -= 1) { if (rscale != factor) rsrcs.add( new ScaledResource(new Scale(rscale), computePath(path, rscale))); } rsrcs.add(new ScaledResource(ONE, path)); return rsrcs; }
java
public List<ScaledResource> getScaledResources(String path) { List<ScaledResource> rsrcs = new ArrayList<ScaledResource>(); rsrcs.add(new ScaledResource(this, computePath(path, factor))); for (float rscale = MathUtil.iceil(factor); rscale > 1; rscale -= 1) { if (rscale != factor) rsrcs.add( new ScaledResource(new Scale(rscale), computePath(path, rscale))); } rsrcs.add(new ScaledResource(ONE, path)); return rsrcs; }
[ "public", "List", "<", "ScaledResource", ">", "getScaledResources", "(", "String", "path", ")", "{", "List", "<", "ScaledResource", ">", "rsrcs", "=", "new", "ArrayList", "<", "ScaledResource", ">", "(", ")", ";", "rsrcs", ".", "add", "(", "new", "ScaledRe...
Returns an ordered series of scaled resources to try when loading an asset. The native resolution will be tried first, then that will be rounded up to the nearest whole integer and stepped down through all whole integers to {@code 1}. If the native scale factor is {@code 2}, this will yield {@code 2, 1}. If the native scale factor is {@code 4}, this will yield {@code 4, 3, 2, 1}. Android devices often have fractional scale factors, which demonstrates the rounding up then back down approach: a native scale factor of {@code 2.5} would yield {@code 2.5, 3, 2, 1}.
[ "Returns", "an", "ordered", "series", "of", "scaled", "resources", "to", "try", "when", "loading", "an", "asset", ".", "The", "native", "resolution", "will", "be", "tried", "first", "then", "that", "will", "be", "rounded", "up", "to", "the", "nearest", "wh...
train
https://github.com/playn/playn/blob/7e7a9d048ba6afe550dc0cdeaca3e1d5b0d01c66/core/src/playn/core/Scale.java#L116-L125
mygreen/xlsmapper
src/main/java/com/gh/mygreen/xlsmapper/validation/SheetErrorFormatter.java
SheetErrorFormatter.getMessage
private String getMessage(final String[] codes, final Optional<String> defaultMessage) { for(String code : codes) { try { final Optional<String> message = messageResolver.getMessage(code); if(message.isPresent()) { return message.get(); } } catch(Throwable e) { continue; } } if(defaultMessage.isPresent()) { return defaultMessage.get(); } throw new RuntimeException(String.format("not found message code [%s].", Utils.join(codes, ","))); }
java
private String getMessage(final String[] codes, final Optional<String> defaultMessage) { for(String code : codes) { try { final Optional<String> message = messageResolver.getMessage(code); if(message.isPresent()) { return message.get(); } } catch(Throwable e) { continue; } } if(defaultMessage.isPresent()) { return defaultMessage.get(); } throw new RuntimeException(String.format("not found message code [%s].", Utils.join(codes, ","))); }
[ "private", "String", "getMessage", "(", "final", "String", "[", "]", "codes", ",", "final", "Optional", "<", "String", ">", "defaultMessage", ")", "{", "for", "(", "String", "code", ":", "codes", ")", "{", "try", "{", "final", "Optional", "<", "String", ...
指定した引数の候補からメッセージを取得する。 @param codes メッセージコードの候補 @param defaultMessage メッセージコードが見つからない場合のメッセージ @return メッセージ @throws RuntimeException メッセージコード 'codes' で指定したメッセージキーが見つからない場合。
[ "指定した引数の候補からメッセージを取得する。" ]
train
https://github.com/mygreen/xlsmapper/blob/a0c6b25c622e5f3a50b199ef685d2ee46ad5483c/src/main/java/com/gh/mygreen/xlsmapper/validation/SheetErrorFormatter.java#L146-L164
OpenLiberty/open-liberty
dev/com.ibm.ws.messaging.common/src/com/ibm/ws/sib/mfp/impl/JsHdrsImpl.java
JsHdrsImpl.getMessageHandle
public SIMessageHandle getMessageHandle() { // If the transient is not set, build the handle from the values in the message and cache it. if (cachedMessageHandle == null) { byte[] b = (byte[]) jmo.getField(JsHdrAccess.SYSTEMMESSAGESOURCEUUID); if (b != null) { cachedMessageHandle = new JsMessageHandleImpl(new SIBUuid8(b), (Long) jmo.getField(JsHdrAccess.SYSTEMMESSAGEVALUE)); } else { cachedMessageHandle = new JsMessageHandleImpl(null, (Long) jmo.getField(JsHdrAccess.SYSTEMMESSAGEVALUE)); } } // Return the (possibly newly) cached value return cachedMessageHandle; }
java
public SIMessageHandle getMessageHandle() { // If the transient is not set, build the handle from the values in the message and cache it. if (cachedMessageHandle == null) { byte[] b = (byte[]) jmo.getField(JsHdrAccess.SYSTEMMESSAGESOURCEUUID); if (b != null) { cachedMessageHandle = new JsMessageHandleImpl(new SIBUuid8(b), (Long) jmo.getField(JsHdrAccess.SYSTEMMESSAGEVALUE)); } else { cachedMessageHandle = new JsMessageHandleImpl(null, (Long) jmo.getField(JsHdrAccess.SYSTEMMESSAGEVALUE)); } } // Return the (possibly newly) cached value return cachedMessageHandle; }
[ "public", "SIMessageHandle", "getMessageHandle", "(", ")", "{", "// If the transient is not set, build the handle from the values in the message and cache it.", "if", "(", "cachedMessageHandle", "==", "null", ")", "{", "byte", "[", "]", "b", "=", "(", "byte", "[", "]", ...
Get the message handle which uniquely identifies this message. @return An SIMessageHandle which identifies this message.
[ "Get", "the", "message", "handle", "which", "uniquely", "identifies", "this", "message", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.common/src/com/ibm/ws/sib/mfp/impl/JsHdrsImpl.java#L658-L671
ansell/csvsum
src/main/java/com/github/ansell/csv/sum/JSONSummariser.java
JSONSummariser.parseForSummarise
private static List<String> parseForSummarise(final Reader input, final ObjectMapper inputMapper, final JDefaultDict<String, AtomicInteger> emptyCounts, final JDefaultDict<String, AtomicInteger> nonEmptyCounts, final JDefaultDict<String, AtomicBoolean> possibleIntegerFields, final JDefaultDict<String, AtomicBoolean> possibleDoubleFields, final JDefaultDict<String, JDefaultDict<String, AtomicInteger>> valueCounts, final AtomicInteger rowCount, Map<String, String> defaultValues, JsonPointer basePath, Map<String, Optional<JsonPointer>> fieldRelativePaths) throws IOException, CSVStreamException { final long startTime = System.currentTimeMillis(); final TriFunction<JsonNode, List<String>, List<String>, List<String>> summariseFunction = JSONSummariser .getSummaryFunctionWithStartTime(emptyCounts, nonEmptyCounts, possibleIntegerFields, possibleDoubleFields, valueCounts, rowCount, startTime); return parseForSummarise(input, inputMapper, defaultValues, summariseFunction, basePath, fieldRelativePaths); }
java
private static List<String> parseForSummarise(final Reader input, final ObjectMapper inputMapper, final JDefaultDict<String, AtomicInteger> emptyCounts, final JDefaultDict<String, AtomicInteger> nonEmptyCounts, final JDefaultDict<String, AtomicBoolean> possibleIntegerFields, final JDefaultDict<String, AtomicBoolean> possibleDoubleFields, final JDefaultDict<String, JDefaultDict<String, AtomicInteger>> valueCounts, final AtomicInteger rowCount, Map<String, String> defaultValues, JsonPointer basePath, Map<String, Optional<JsonPointer>> fieldRelativePaths) throws IOException, CSVStreamException { final long startTime = System.currentTimeMillis(); final TriFunction<JsonNode, List<String>, List<String>, List<String>> summariseFunction = JSONSummariser .getSummaryFunctionWithStartTime(emptyCounts, nonEmptyCounts, possibleIntegerFields, possibleDoubleFields, valueCounts, rowCount, startTime); return parseForSummarise(input, inputMapper, defaultValues, summariseFunction, basePath, fieldRelativePaths); }
[ "private", "static", "List", "<", "String", ">", "parseForSummarise", "(", "final", "Reader", "input", ",", "final", "ObjectMapper", "inputMapper", ",", "final", "JDefaultDict", "<", "String", ",", "AtomicInteger", ">", "emptyCounts", ",", "final", "JDefaultDict",...
Parse the given inputs to in-memory maps to allow for summarisation. @param input The {@link Reader} containing the inputs to be summarised. @param inputMapper The {@link ObjectMapper} to use to parse the file into memory @param emptyCounts A {@link JDefaultDict} to be populated with empty counts for each field @param nonEmptyCounts A {@link JDefaultDict} to be populated with non-empty counts for each field @param possibleIntegerFields A {@link JDefaultDict} to be populated with false if a non-integer value is detected in a field @param possibleDoubleFields A {@link JDefaultDict} to be populated with false if a non-double value is detected in a field @param valueCounts A {@link JDefaultDict} to be populated with false if a non-integer value is detected in a field @param rowCount An {@link AtomicInteger} used to track the total number of rows processed. @param defaultValues A Map that is either empty, signifying there are no default values known, or exactly the same length as each row in the CSV file being parsed. If the values for a field are empty/missing, and a non-null, non-empty value appears in this list, it will be substituted in when calculating the statistics. @param basePath The path to go to before checking the field paths (only supports a single point of entry at this point in time). Set to "/" to start at the top of the document. If the basePath points to an array, each of the array elements are matched separately with the fieldRelativePaths. If it points to an object, the object is directly matched to obtain a single result row. Otherwise an exception is thrown. @param fieldRelativePaths The relative paths underneath the basePath to select field values from. @return The list of headers that were either overridden or found in the file @throws IOException If there is an error reading from the file @throws CSVStreamException If there is a problem processing the JSON content
[ "Parse", "the", "given", "inputs", "to", "in", "-", "memory", "maps", "to", "allow", "for", "summarisation", "." ]
train
https://github.com/ansell/csvsum/blob/6916f4d9ca48ceb940c668778626a3c9ce26587a/src/main/java/com/github/ansell/csv/sum/JSONSummariser.java#L360-L373
TNG/JGiven
jgiven-core/src/main/java/com/tngtech/jgiven/attachment/Attachment.java
Attachment.fromTextFile
@Deprecated public static Attachment fromTextFile( File file, MediaType mediaType, Charset charSet ) throws IOException { return fromText( Files.toString( file, charSet ), mediaType ); }
java
@Deprecated public static Attachment fromTextFile( File file, MediaType mediaType, Charset charSet ) throws IOException { return fromText( Files.toString( file, charSet ), mediaType ); }
[ "@", "Deprecated", "public", "static", "Attachment", "fromTextFile", "(", "File", "file", ",", "MediaType", "mediaType", ",", "Charset", "charSet", ")", "throws", "IOException", "{", "return", "fromText", "(", "Files", ".", "toString", "(", "file", ",", "charS...
Creates a non-binary attachment from the given file. @throws IOException if an I/O error occurs @throws java.lang.IllegalArgumentException if mediaType is binary @deprecated use fromTextFile without charSet with a mediaType that has a specified charSet
[ "Creates", "a", "non", "-", "binary", "attachment", "from", "the", "given", "file", "." ]
train
https://github.com/TNG/JGiven/blob/1a69248fc6d7eb380cdc4542e3be273842889748/jgiven-core/src/main/java/com/tngtech/jgiven/attachment/Attachment.java#L201-L204
kochedykov/jlibmodbus
src/com/intelligt/modbus/jlibmodbus/master/ModbusMaster.java
ModbusMaster.writeSingleCoil
final public void writeSingleCoil(int serverAddress, int startAddress, boolean flag) throws ModbusProtocolException, ModbusNumberException, ModbusIOException { processRequest(ModbusRequestBuilder.getInstance().buildWriteSingleCoil(serverAddress, startAddress, flag)); }
java
final public void writeSingleCoil(int serverAddress, int startAddress, boolean flag) throws ModbusProtocolException, ModbusNumberException, ModbusIOException { processRequest(ModbusRequestBuilder.getInstance().buildWriteSingleCoil(serverAddress, startAddress, flag)); }
[ "final", "public", "void", "writeSingleCoil", "(", "int", "serverAddress", ",", "int", "startAddress", ",", "boolean", "flag", ")", "throws", "ModbusProtocolException", ",", "ModbusNumberException", ",", "ModbusIOException", "{", "processRequest", "(", "ModbusRequestBui...
This function code is used to write a single output to either ON or OFF in a remote device. The requested ON/OFF state is specified by a constant in the request data field. A value of TRUE requests the output to be ON. A value of FALSE requests it to be OFF. The Request PDU specifies the address of the coil to be forced. Coils are addressed starting at zero. Therefore coil numbered 1 is addressed as 0. @param serverAddress a slave address @param startAddress the address of the coil to be forced @param flag the request data field @throws ModbusProtocolException if modbus-exception is received @throws ModbusNumberException if response is invalid @throws ModbusIOException if remote slave is unavailable
[ "This", "function", "code", "is", "used", "to", "write", "a", "single", "output", "to", "either", "ON", "or", "OFF", "in", "a", "remote", "device", ".", "The", "requested", "ON", "/", "OFF", "state", "is", "specified", "by", "a", "constant", "in", "the...
train
https://github.com/kochedykov/jlibmodbus/blob/197cb39e2649e61a6fe3cb7dc91a701d847e14be/src/com/intelligt/modbus/jlibmodbus/master/ModbusMaster.java#L283-L286
alipay/sofa-rpc
core/api/src/main/java/com/alipay/sofa/rpc/common/RpcConfigs.java
RpcConfigs.getBooleanValue
public static boolean getBooleanValue(String primaryKey, String secondaryKey) { Object val = CFG.get(primaryKey); if (val == null) { val = CFG.get(secondaryKey); if (val == null) { throw new SofaRpcRuntimeException("Not found key: " + primaryKey + "/" + secondaryKey); } } return Boolean.valueOf(val.toString()); }
java
public static boolean getBooleanValue(String primaryKey, String secondaryKey) { Object val = CFG.get(primaryKey); if (val == null) { val = CFG.get(secondaryKey); if (val == null) { throw new SofaRpcRuntimeException("Not found key: " + primaryKey + "/" + secondaryKey); } } return Boolean.valueOf(val.toString()); }
[ "public", "static", "boolean", "getBooleanValue", "(", "String", "primaryKey", ",", "String", "secondaryKey", ")", "{", "Object", "val", "=", "CFG", ".", "get", "(", "primaryKey", ")", ";", "if", "(", "val", "==", "null", ")", "{", "val", "=", "CFG", "...
Gets boolean value. @param primaryKey the primary key @param secondaryKey the secondary key @return the boolean value
[ "Gets", "boolean", "value", "." ]
train
https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/core/api/src/main/java/com/alipay/sofa/rpc/common/RpcConfigs.java#L184-L193
networknt/light-4j
dump/src/main/java/com/networknt/dump/BodyDumper.java
BodyDumper.putDumpInfoTo
@Override protected void putDumpInfoTo(Map<String, Object> result) { if(StringUtils.isNotBlank(this.bodyContent)) { result.put(DumpConstants.BODY, this.bodyContent); } }
java
@Override protected void putDumpInfoTo(Map<String, Object> result) { if(StringUtils.isNotBlank(this.bodyContent)) { result.put(DumpConstants.BODY, this.bodyContent); } }
[ "@", "Override", "protected", "void", "putDumpInfoTo", "(", "Map", "<", "String", ",", "Object", ">", "result", ")", "{", "if", "(", "StringUtils", ".", "isNotBlank", "(", "this", ".", "bodyContent", ")", ")", "{", "result", ".", "put", "(", "DumpConstan...
put bodyContent to result @param result a Map<String, Object> you want to put dumping info to.
[ "put", "bodyContent", "to", "result" ]
train
https://github.com/networknt/light-4j/blob/2a60257c60663684c8f6dc8b5ea3cf184e534db6/dump/src/main/java/com/networknt/dump/BodyDumper.java#L51-L56
jglobus/JGlobus
ssl-proxies/src/main/java/org/globus/gsi/gridmap/GridMap.java
GridMap.checkUser
public boolean checkUser(String globusID, String userID) { if (globusID == null) { throw new IllegalArgumentException(i18n.getMessage("glousIdNull")); } if (userID == null) { throw new IllegalArgumentException(i18n.getMessage("userIdNull")); } if (this.map == null) { return false; } GridMapEntry entry = (GridMapEntry)this.map.get(normalizeDN(globusID)); return (entry == null) ? false : entry.containsUserID(userID); }
java
public boolean checkUser(String globusID, String userID) { if (globusID == null) { throw new IllegalArgumentException(i18n.getMessage("glousIdNull")); } if (userID == null) { throw new IllegalArgumentException(i18n.getMessage("userIdNull")); } if (this.map == null) { return false; } GridMapEntry entry = (GridMapEntry)this.map.get(normalizeDN(globusID)); return (entry == null) ? false : entry.containsUserID(userID); }
[ "public", "boolean", "checkUser", "(", "String", "globusID", ",", "String", "userID", ")", "{", "if", "(", "globusID", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "i18n", ".", "getMessage", "(", "\"glousIdNull\"", ")", ")", ";", ...
Checks if a given globus ID is associated with given local user account. @param globusID globus ID @param userID userID @return true if globus ID is associated with given local user account, false, otherwise.
[ "Checks", "if", "a", "given", "globus", "ID", "is", "associated", "with", "given", "local", "user", "account", "." ]
train
https://github.com/jglobus/JGlobus/blob/e14f6f6636544fd84298f9cec749d626ea971930/ssl-proxies/src/main/java/org/globus/gsi/gridmap/GridMap.java#L310-L324
kennycason/kumo
kumo-core/src/main/java/com/kennycason/kumo/ParallelLayeredWordCloud.java
ParallelLayeredWordCloud.writeToFile
public void writeToFile(final String outputFileName, final boolean blockThread, final boolean shutdownExecutor) { if (blockThread) { waitForFuturesToBlockCurrentThread(); } super.writeToFile(outputFileName); if (shutdownExecutor) { this.shutdown(); } }
java
public void writeToFile(final String outputFileName, final boolean blockThread, final boolean shutdownExecutor) { if (blockThread) { waitForFuturesToBlockCurrentThread(); } super.writeToFile(outputFileName); if (shutdownExecutor) { this.shutdown(); } }
[ "public", "void", "writeToFile", "(", "final", "String", "outputFileName", ",", "final", "boolean", "blockThread", ",", "final", "boolean", "shutdownExecutor", ")", "{", "if", "(", "blockThread", ")", "{", "waitForFuturesToBlockCurrentThread", "(", ")", ";", "}", ...
Writes the wordcloud to an imagefile. @param outputFileName some file like "test.png" @param blockThread should the current thread be blocked @param shutdownExecutor should the executor be shutdown afterwards. if <code>false</code> this PLWC can still be used to build other layers. if <code>true</code> this will become a blocking Thread no matter what was specified in blockThread.
[ "Writes", "the", "wordcloud", "to", "an", "imagefile", "." ]
train
https://github.com/kennycason/kumo/blob/bc577f468f162dbaf61c327a2d4f1989c61c57a0/kumo-core/src/main/java/com/kennycason/kumo/ParallelLayeredWordCloud.java#L89-L98
JodaOrg/joda-time
src/main/java/org/joda/time/tz/DateTimeZoneBuilder.java
DateTimeZoneBuilder.addCutover
public DateTimeZoneBuilder addCutover(int year, char mode, int monthOfYear, int dayOfMonth, int dayOfWeek, boolean advanceDayOfWeek, int millisOfDay) { if (iRuleSets.size() > 0) { OfYear ofYear = new OfYear (mode, monthOfYear, dayOfMonth, dayOfWeek, advanceDayOfWeek, millisOfDay); RuleSet lastRuleSet = iRuleSets.get(iRuleSets.size() - 1); lastRuleSet.setUpperLimit(year, ofYear); } iRuleSets.add(new RuleSet()); return this; }
java
public DateTimeZoneBuilder addCutover(int year, char mode, int monthOfYear, int dayOfMonth, int dayOfWeek, boolean advanceDayOfWeek, int millisOfDay) { if (iRuleSets.size() > 0) { OfYear ofYear = new OfYear (mode, monthOfYear, dayOfMonth, dayOfWeek, advanceDayOfWeek, millisOfDay); RuleSet lastRuleSet = iRuleSets.get(iRuleSets.size() - 1); lastRuleSet.setUpperLimit(year, ofYear); } iRuleSets.add(new RuleSet()); return this; }
[ "public", "DateTimeZoneBuilder", "addCutover", "(", "int", "year", ",", "char", "mode", ",", "int", "monthOfYear", ",", "int", "dayOfMonth", ",", "int", "dayOfWeek", ",", "boolean", "advanceDayOfWeek", ",", "int", "millisOfDay", ")", "{", "if", "(", "iRuleSets...
Adds a cutover for added rules. The standard offset at the cutover defaults to 0. Call setStandardOffset afterwards to change it. @param year the year of cutover @param mode 'u' - cutover is measured against UTC, 'w' - against wall offset, 's' - against standard offset @param monthOfYear the month from 1 (January) to 12 (December) @param dayOfMonth if negative, set to ((last day of month) - ~dayOfMonth). For example, if -1, set to last day of month @param dayOfWeek from 1 (Monday) to 7 (Sunday), if 0 then ignore @param advanceDayOfWeek if dayOfMonth does not fall on dayOfWeek, advance to dayOfWeek when true, retreat when false. @param millisOfDay additional precision for specifying time of day of cutover
[ "Adds", "a", "cutover", "for", "added", "rules", ".", "The", "standard", "offset", "at", "the", "cutover", "defaults", "to", "0", ".", "Call", "setStandardOffset", "afterwards", "to", "change", "it", "." ]
train
https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/tz/DateTimeZoneBuilder.java#L245-L261
molgenis/molgenis
molgenis-one-click-importer/src/main/java/org/molgenis/oneclickimporter/service/impl/AttributeTypeServiceImpl.java
AttributeTypeServiceImpl.isBroader
private boolean isBroader(AttributeType enrichedTypeGuess, AttributeType columnTypeGuess) { if (columnTypeGuess == null && enrichedTypeGuess != null || columnTypeGuess == null) { return true; } switch (columnTypeGuess) { case INT: return enrichedTypeGuess.equals(INT) || enrichedTypeGuess.equals(LONG) || enrichedTypeGuess.equals(DECIMAL) || enrichedTypeGuess.equals(STRING) || enrichedTypeGuess.equals(TEXT); case DECIMAL: return enrichedTypeGuess.equals(DECIMAL) || enrichedTypeGuess.equals(DATE) || enrichedTypeGuess.equals(DATE_TIME) || enrichedTypeGuess.equals(STRING) || enrichedTypeGuess.equals(TEXT); case LONG: return enrichedTypeGuess.equals(LONG) || enrichedTypeGuess.equals(DECIMAL) || enrichedTypeGuess.equals(DATE) || enrichedTypeGuess.equals(DATE_TIME) || enrichedTypeGuess.equals(STRING) || enrichedTypeGuess.equals(TEXT); case BOOL: return enrichedTypeGuess.equals(STRING) || enrichedTypeGuess.equals(TEXT); case STRING: return enrichedTypeGuess.equals(STRING) || enrichedTypeGuess.equals(TEXT); case DATE_TIME: return enrichedTypeGuess.equals(STRING) || enrichedTypeGuess.equals(TEXT); case DATE: return enrichedTypeGuess.equals(STRING) || enrichedTypeGuess.equals(TEXT); default: return false; } }
java
private boolean isBroader(AttributeType enrichedTypeGuess, AttributeType columnTypeGuess) { if (columnTypeGuess == null && enrichedTypeGuess != null || columnTypeGuess == null) { return true; } switch (columnTypeGuess) { case INT: return enrichedTypeGuess.equals(INT) || enrichedTypeGuess.equals(LONG) || enrichedTypeGuess.equals(DECIMAL) || enrichedTypeGuess.equals(STRING) || enrichedTypeGuess.equals(TEXT); case DECIMAL: return enrichedTypeGuess.equals(DECIMAL) || enrichedTypeGuess.equals(DATE) || enrichedTypeGuess.equals(DATE_TIME) || enrichedTypeGuess.equals(STRING) || enrichedTypeGuess.equals(TEXT); case LONG: return enrichedTypeGuess.equals(LONG) || enrichedTypeGuess.equals(DECIMAL) || enrichedTypeGuess.equals(DATE) || enrichedTypeGuess.equals(DATE_TIME) || enrichedTypeGuess.equals(STRING) || enrichedTypeGuess.equals(TEXT); case BOOL: return enrichedTypeGuess.equals(STRING) || enrichedTypeGuess.equals(TEXT); case STRING: return enrichedTypeGuess.equals(STRING) || enrichedTypeGuess.equals(TEXT); case DATE_TIME: return enrichedTypeGuess.equals(STRING) || enrichedTypeGuess.equals(TEXT); case DATE: return enrichedTypeGuess.equals(STRING) || enrichedTypeGuess.equals(TEXT); default: return false; } }
[ "private", "boolean", "isBroader", "(", "AttributeType", "enrichedTypeGuess", ",", "AttributeType", "columnTypeGuess", ")", "{", "if", "(", "columnTypeGuess", "==", "null", "&&", "enrichedTypeGuess", "!=", "null", "||", "columnTypeGuess", "==", "null", ")", "{", "...
Check if the new enriched type is broader the the previously found type @return
[ "Check", "if", "the", "new", "enriched", "type", "is", "broader", "the", "the", "previously", "found", "type" ]
train
https://github.com/molgenis/molgenis/blob/b4d0d6b27e6f6c8d7505a3863dc03b589601f987/molgenis-one-click-importer/src/main/java/org/molgenis/oneclickimporter/service/impl/AttributeTypeServiceImpl.java#L62-L99
nyla-solutions/nyla
nyla.solutions.core/src/main/java/nyla/solutions/core/util/Organizer.java
Organizer.addAll
public static <T> void addAll(Collection<T> aFrom, Collection<T> aTo) { if (aFrom == null || aTo == null) return; // do nothing T object = null; for (Iterator<T> i = aFrom.iterator(); i.hasNext();) { object = i.next(); if (object != null) { aTo.add(object); } } }
java
public static <T> void addAll(Collection<T> aFrom, Collection<T> aTo) { if (aFrom == null || aTo == null) return; // do nothing T object = null; for (Iterator<T> i = aFrom.iterator(); i.hasNext();) { object = i.next(); if (object != null) { aTo.add(object); } } }
[ "public", "static", "<", "T", ">", "void", "addAll", "(", "Collection", "<", "T", ">", "aFrom", ",", "Collection", "<", "T", ">", "aTo", ")", "{", "if", "(", "aFrom", "==", "null", "||", "aTo", "==", "null", ")", "return", ";", "// do nothing\r", "...
All object to a given collection @param <T> the type class @param aFrom the collection to add from @param aTo the collection to add to.
[ "All", "object", "to", "a", "given", "collection" ]
train
https://github.com/nyla-solutions/nyla/blob/38d5b843c76eae9762bbca20453ed0f0ad8412a9/nyla.solutions.core/src/main/java/nyla/solutions/core/util/Organizer.java#L694-L708
xiancloud/xian
xian-oauth20/xian-apifestOauth20/src/main/java/com/apifest/oauth20/Authenticator.java
Authenticator.revokeToken
public Single<Boolean> revokeToken(FullHttpRequest req) throws OAuthException { RevokeTokenRequest revokeRequest = new RevokeTokenRequest(req); revokeRequest.checkMandatoryParams(); String clientId = revokeRequest.getClientId(); // check valid client_id, status does not matter as token of inactive client app could be revoked too return isExistingClient(clientId).flatMap(existed -> { if (!existed) throw new OAuthException(ResponseBuilder.INVALID_CLIENT_ID, HttpResponseStatus.BAD_REQUEST); else { String token = revokeRequest.getAccessToken(); return db.findAccessToken(token) .map(Optional::of) .switchIfEmpty(Single.just(Optional.empty())) .flatMap(accessToken -> { if (accessToken.isPresent()) { if (accessToken.get().tokenExpired()) { LOG.info(String.format("Access token {%s} has already expired, nothing need to do.", token)); return Single.just(true); } if (clientId.equals(accessToken.get().getClientId())) { return db.removeAccessToken(accessToken.get().getToken()) .andThen(Single.just(true) .doOnSuccess(ignored -> LOG.info(String.format("access token {%s} set status invalid", token)))); } else { LOG.info(String.format("access token {%s} is not obtained for that client {%s}", token, clientId)); return Single.just(false); } } else { LOG.info(String.format("access token {%s} not found", token)); return Single.just(false); } }) ; } }); }
java
public Single<Boolean> revokeToken(FullHttpRequest req) throws OAuthException { RevokeTokenRequest revokeRequest = new RevokeTokenRequest(req); revokeRequest.checkMandatoryParams(); String clientId = revokeRequest.getClientId(); // check valid client_id, status does not matter as token of inactive client app could be revoked too return isExistingClient(clientId).flatMap(existed -> { if (!existed) throw new OAuthException(ResponseBuilder.INVALID_CLIENT_ID, HttpResponseStatus.BAD_REQUEST); else { String token = revokeRequest.getAccessToken(); return db.findAccessToken(token) .map(Optional::of) .switchIfEmpty(Single.just(Optional.empty())) .flatMap(accessToken -> { if (accessToken.isPresent()) { if (accessToken.get().tokenExpired()) { LOG.info(String.format("Access token {%s} has already expired, nothing need to do.", token)); return Single.just(true); } if (clientId.equals(accessToken.get().getClientId())) { return db.removeAccessToken(accessToken.get().getToken()) .andThen(Single.just(true) .doOnSuccess(ignored -> LOG.info(String.format("access token {%s} set status invalid", token)))); } else { LOG.info(String.format("access token {%s} is not obtained for that client {%s}", token, clientId)); return Single.just(false); } } else { LOG.info(String.format("access token {%s} not found", token)); return Single.just(false); } }) ; } }); }
[ "public", "Single", "<", "Boolean", ">", "revokeToken", "(", "FullHttpRequest", "req", ")", "throws", "OAuthException", "{", "RevokeTokenRequest", "revokeRequest", "=", "new", "RevokeTokenRequest", "(", "req", ")", ";", "revokeRequest", ".", "checkMandatoryParams", ...
revoke the given token. revoke = 撤销 @param req the requested token to be revoked @return OAuthException if the given client id does not exist. true if the token exists and has been revoked, false if the token does not exist.
[ "revoke", "the", "given", "token", ".", "revoke", "=", "撤销" ]
train
https://github.com/xiancloud/xian/blob/1948e088545553d2745b2c86d8b5a64988bb850e/xian-oauth20/xian-apifestOauth20/src/main/java/com/apifest/oauth20/Authenticator.java#L439-L473
kuali/ojb-1.0.4
src/java/org/apache/ojb/broker/core/PersistenceBrokerImpl.java
PersistenceBrokerImpl.getIteratorFromQuery
protected OJBIterator getIteratorFromQuery(Query query, ClassDescriptor cld) throws PersistenceBrokerException { RsIteratorFactory factory = RsIteratorFactoryImpl.getInstance(); OJBIterator result = getRsIteratorFromQuery(query, cld, factory); if (query.usePaging()) { result = new PagingIterator(result, query.getStartAtIndex(), query.getEndAtIndex()); } return result; }
java
protected OJBIterator getIteratorFromQuery(Query query, ClassDescriptor cld) throws PersistenceBrokerException { RsIteratorFactory factory = RsIteratorFactoryImpl.getInstance(); OJBIterator result = getRsIteratorFromQuery(query, cld, factory); if (query.usePaging()) { result = new PagingIterator(result, query.getStartAtIndex(), query.getEndAtIndex()); } return result; }
[ "protected", "OJBIterator", "getIteratorFromQuery", "(", "Query", "query", ",", "ClassDescriptor", "cld", ")", "throws", "PersistenceBrokerException", "{", "RsIteratorFactory", "factory", "=", "RsIteratorFactoryImpl", ".", "getInstance", "(", ")", ";", "OJBIterator", "r...
Get an extent aware Iterator based on the Query @param query @param cld the ClassDescriptor @return OJBIterator
[ "Get", "an", "extent", "aware", "Iterator", "based", "on", "the", "Query" ]
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/core/PersistenceBrokerImpl.java#L1665-L1675
hankcs/HanLP
src/main/java/com/hankcs/hanlp/collection/MDAG/MDAG.java
MDAG.calculateMinimizationProcessingStartIndex
private int calculateMinimizationProcessingStartIndex(String prevStr, String currStr) { int mpsIndex; if (!currStr.startsWith(prevStr)) { //Loop through the corresponding indices of both Strings in search of the first index containing differing characters. //The _transition path of the substring of prevStr from this point will need to be submitted for minimization processing. //The substring before this point, however, does not, since currStr will simply be extending the right languages of the //nodes on its _transition path. int shortestStringLength = Math.min(prevStr.length(), currStr.length()); for (mpsIndex = 0; mpsIndex < shortestStringLength && prevStr.charAt(mpsIndex) == currStr.charAt(mpsIndex); mpsIndex++) { } ; ///// } else mpsIndex = -1; //If the prevStr is a prefix of currStr, then currStr simply extends the right language of the _transition path of prevStr. return mpsIndex; }
java
private int calculateMinimizationProcessingStartIndex(String prevStr, String currStr) { int mpsIndex; if (!currStr.startsWith(prevStr)) { //Loop through the corresponding indices of both Strings in search of the first index containing differing characters. //The _transition path of the substring of prevStr from this point will need to be submitted for minimization processing. //The substring before this point, however, does not, since currStr will simply be extending the right languages of the //nodes on its _transition path. int shortestStringLength = Math.min(prevStr.length(), currStr.length()); for (mpsIndex = 0; mpsIndex < shortestStringLength && prevStr.charAt(mpsIndex) == currStr.charAt(mpsIndex); mpsIndex++) { } ; ///// } else mpsIndex = -1; //If the prevStr is a prefix of currStr, then currStr simply extends the right language of the _transition path of prevStr. return mpsIndex; }
[ "private", "int", "calculateMinimizationProcessingStartIndex", "(", "String", "prevStr", ",", "String", "currStr", ")", "{", "int", "mpsIndex", ";", "if", "(", "!", "currStr", ".", "startsWith", "(", "prevStr", ")", ")", "{", "//Loop through the corresponding indice...
计算最小化的执行位置,其实是prevStr和currStr的第一个分叉点<br> Determines the start index of the substring in the String most recently added to the MDAG that corresponds to the _transition path that will be next up for minimization processing. <p/> The "minimization processing start index" is defined as the index in {@code prevStr} which starts the substring corresponding to the _transition path that doesn't have its right language extended by {@code currStr}. The _transition path of the substring before this point is not considered for minimization in order to limit the amount of times the equivalence classes of its nodes will need to be reassigned during the processing of Strings which share prefixes. @param prevStr the String most recently added to the MDAG @param currStr the String next to be added to the MDAG @return an int of the index in {@code prevStr} that starts the substring corresponding to the _transition path next up for minimization processing
[ "计算最小化的执行位置,其实是prevStr和currStr的第一个分叉点<br", ">", "Determines", "the", "start", "index", "of", "the", "substring", "in", "the", "String", "most", "recently", "added", "to", "the", "MDAG", "that", "corresponds", "to", "the", "_transition", "path", "that", "will", "be...
train
https://github.com/hankcs/HanLP/blob/a538d0722ab2e4980a9dcd9ea40324fc3ddba7ce/src/main/java/com/hankcs/hanlp/collection/MDAG/MDAG.java#L430-L451
kuali/ojb-1.0.4
src/java/org/apache/ojb/broker/util/ClassHelper.java
ClassHelper.getField
public static Field getField(Class clazz, String fieldName) { try { return clazz.getField(fieldName); } catch (Exception ignored) {} return null; }
java
public static Field getField(Class clazz, String fieldName) { try { return clazz.getField(fieldName); } catch (Exception ignored) {} return null; }
[ "public", "static", "Field", "getField", "(", "Class", "clazz", ",", "String", "fieldName", ")", "{", "try", "{", "return", "clazz", ".", "getField", "(", "fieldName", ")", ";", "}", "catch", "(", "Exception", "ignored", ")", "{", "}", "return", "null", ...
Determines the field via reflection look-up. @param clazz The java class to search in @param fieldName The field's name @return The field object or <code>null</code> if no matching field was found
[ "Determines", "the", "field", "via", "reflection", "look", "-", "up", "." ]
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/util/ClassHelper.java#L251-L260
Azure/azure-sdk-for-java
redis/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/redis/v2017_10_01/implementation/RedisInner.java
RedisInner.beginExportDataAsync
public Observable<Void> beginExportDataAsync(String resourceGroupName, String name, ExportRDBParameters parameters) { return beginExportDataWithServiceResponseAsync(resourceGroupName, name, parameters).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); }
java
public Observable<Void> beginExportDataAsync(String resourceGroupName, String name, ExportRDBParameters parameters) { return beginExportDataWithServiceResponseAsync(resourceGroupName, name, parameters).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Void", ">", "beginExportDataAsync", "(", "String", "resourceGroupName", ",", "String", "name", ",", "ExportRDBParameters", "parameters", ")", "{", "return", "beginExportDataWithServiceResponseAsync", "(", "resourceGroupName", ",", "name", "...
Export data from the redis cache to blobs in a container. @param resourceGroupName The name of the resource group. @param name The name of the Redis cache. @param parameters Parameters for Redis export operation. @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceResponse} object if successful.
[ "Export", "data", "from", "the", "redis", "cache", "to", "blobs", "in", "a", "container", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/redis/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/redis/v2017_10_01/implementation/RedisInner.java#L1611-L1618
Whiley/WhileyCompiler
src/main/java/wyil/check/FlowTypeCheck.java
FlowTypeCheck.checkNonEmpty
private void checkNonEmpty(Tuple<Decl.Variable> decls, LifetimeRelation lifetimes) { for (int i = 0; i != decls.size(); ++i) { checkNonEmpty(decls.get(i), lifetimes); } }
java
private void checkNonEmpty(Tuple<Decl.Variable> decls, LifetimeRelation lifetimes) { for (int i = 0; i != decls.size(); ++i) { checkNonEmpty(decls.get(i), lifetimes); } }
[ "private", "void", "checkNonEmpty", "(", "Tuple", "<", "Decl", ".", "Variable", ">", "decls", ",", "LifetimeRelation", "lifetimes", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "!=", "decls", ".", "size", "(", ")", ";", "++", "i", ")", "{"...
Check a given set of variable declarations are not "empty". That is, their declared type is not equivalent to void. @param decls
[ "Check", "a", "given", "set", "of", "variable", "declarations", "are", "not", "empty", ".", "That", "is", "their", "declared", "type", "is", "not", "equivalent", "to", "void", "." ]
train
https://github.com/Whiley/WhileyCompiler/blob/680f8a657d3fc286f8cc422755988b6d74ab3f4c/src/main/java/wyil/check/FlowTypeCheck.java#L1850-L1854
fuzzylite/jfuzzylite
jfuzzylite/src/main/java/com/fuzzylite/defuzzifier/LargestOfMaximum.java
LargestOfMaximum.defuzzify
@Override public double defuzzify(Term term, double minimum, double maximum) { if (!Op.isFinite(minimum + maximum)) { return Double.NaN; } final int resolution = getResolution(); final double dx = (maximum - minimum) / resolution; double x, y; double ymax = -1.0, xlargest = maximum; for (int i = 0; i < resolution; ++i) { x = minimum + (i + 0.5) * dx; y = term.membership(x); if (Op.isGE(y, ymax)) { ymax = y; xlargest = x; } } return xlargest; }
java
@Override public double defuzzify(Term term, double minimum, double maximum) { if (!Op.isFinite(minimum + maximum)) { return Double.NaN; } final int resolution = getResolution(); final double dx = (maximum - minimum) / resolution; double x, y; double ymax = -1.0, xlargest = maximum; for (int i = 0; i < resolution; ++i) { x = minimum + (i + 0.5) * dx; y = term.membership(x); if (Op.isGE(y, ymax)) { ymax = y; xlargest = x; } } return xlargest; }
[ "@", "Override", "public", "double", "defuzzify", "(", "Term", "term", ",", "double", "minimum", ",", "double", "maximum", ")", "{", "if", "(", "!", "Op", ".", "isFinite", "(", "minimum", "+", "maximum", ")", ")", "{", "return", "Double", ".", "NaN", ...
Computes the largest value of the maximum membership function of a fuzzy set. The largest value is computed by integrating over the fuzzy set. The integration algorithm is the midpoint rectangle method (https://en.wikipedia.org/wiki/Rectangle_method). @param term is the fuzzy set @param minimum is the minimum value of the fuzzy set @param maximum is the maximum value of the fuzzy set @return the largest `x`-coordinate of the maximum membership function value in the fuzzy set
[ "Computes", "the", "largest", "value", "of", "the", "maximum", "membership", "function", "of", "a", "fuzzy", "set", ".", "The", "largest", "value", "is", "computed", "by", "integrating", "over", "the", "fuzzy", "set", ".", "The", "integration", "algorithm", ...
train
https://github.com/fuzzylite/jfuzzylite/blob/583ac1928f39512af75de80d560e67448039595a/jfuzzylite/src/main/java/com/fuzzylite/defuzzifier/LargestOfMaximum.java#L55-L75
hypercube1024/firefly
firefly/src/main/java/com/firefly/codec/http2/model/HttpFields.java
HttpFields.putLongField
public void putLongField(HttpHeader name, long value) { String v = Long.toString(value); put(name, v); }
java
public void putLongField(HttpHeader name, long value) { String v = Long.toString(value); put(name, v); }
[ "public", "void", "putLongField", "(", "HttpHeader", "name", ",", "long", "value", ")", "{", "String", "v", "=", "Long", ".", "toString", "(", "value", ")", ";", "put", "(", "name", ",", "v", ")", ";", "}" ]
Sets the value of an long field. @param name the field name @param value the field long value
[ "Sets", "the", "value", "of", "an", "long", "field", "." ]
train
https://github.com/hypercube1024/firefly/blob/ed3fc75b7c54a65b1e7d8141d01b49144bb423a3/firefly/src/main/java/com/firefly/codec/http2/model/HttpFields.java#L651-L654
alipay/sofa-rpc
core/common/src/main/java/com/alipay/sofa/rpc/common/utils/BeanUtils.java
BeanUtils.setProperty
public static <T> void setProperty(Object bean, String name, Class<T> clazz, T value) throws Exception { Method method = ReflectUtils.getPropertySetterMethod(bean.getClass(), name, clazz); if (method.isAccessible()) { method.invoke(bean, value); } else { try { method.setAccessible(true); method.invoke(bean, value); } finally { method.setAccessible(false); } } }
java
public static <T> void setProperty(Object bean, String name, Class<T> clazz, T value) throws Exception { Method method = ReflectUtils.getPropertySetterMethod(bean.getClass(), name, clazz); if (method.isAccessible()) { method.invoke(bean, value); } else { try { method.setAccessible(true); method.invoke(bean, value); } finally { method.setAccessible(false); } } }
[ "public", "static", "<", "T", ">", "void", "setProperty", "(", "Object", "bean", ",", "String", "name", ",", "Class", "<", "T", ">", "clazz", ",", "T", "value", ")", "throws", "Exception", "{", "Method", "method", "=", "ReflectUtils", ".", "getPropertySe...
设置属性 @param bean 对象 @param name 属性名 @param clazz 设置值的类 @param value 属性值 @param <T> 和值对应的类型 @throws Exception 设值异常
[ "设置属性" ]
train
https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/core/common/src/main/java/com/alipay/sofa/rpc/common/utils/BeanUtils.java#L47-L59
audit4j/audit4j-db
src/main/java/org/audit4j/handler/db/ConnectionFactory.java
ConnectionFactory.getDataSourceConnection
Connection getDataSourceConnection() { Connection connection = null; try { connection = dataSource.getConnection(); } catch (SQLException ex) { throw new InitializationException("Could not obtain the db connection: Cannot get connection", ex); } return connection; }
java
Connection getDataSourceConnection() { Connection connection = null; try { connection = dataSource.getConnection(); } catch (SQLException ex) { throw new InitializationException("Could not obtain the db connection: Cannot get connection", ex); } return connection; }
[ "Connection", "getDataSourceConnection", "(", ")", "{", "Connection", "connection", "=", "null", ";", "try", "{", "connection", "=", "dataSource", ".", "getConnection", "(", ")", ";", "}", "catch", "(", "SQLException", "ex", ")", "{", "throw", "new", "Initia...
Gets the data source connection. @return the data source connection @since 2.4.0
[ "Gets", "the", "data", "source", "connection", "." ]
train
https://github.com/audit4j/audit4j-db/blob/bba822a5722533e6f465a9784f2353ae2e5bc01d/src/main/java/org/audit4j/handler/db/ConnectionFactory.java#L143-L151
QSFT/Doradus
doradus-common/src/main/java/com/dell/doradus/management/CronUtils.java
CronUtils.extendRepeating
private static String extendRepeating(String e, String max) { String[] parts = e.split(","); for (int i = 0; i < parts.length; ++i) { if (parts[i].indexOf('-') == -1 && parts[i].indexOf('*') == -1) { int indSlash = parts[i].indexOf('/'); if (indSlash == 0) { parts[i] = "*" + parts[i]; } else if (indSlash > 0) { parts[i] = parts[i].substring(0, indSlash) + "-" + max + parts[i].substring(indSlash); } } } return concat(',', parts); }
java
private static String extendRepeating(String e, String max) { String[] parts = e.split(","); for (int i = 0; i < parts.length; ++i) { if (parts[i].indexOf('-') == -1 && parts[i].indexOf('*') == -1) { int indSlash = parts[i].indexOf('/'); if (indSlash == 0) { parts[i] = "*" + parts[i]; } else if (indSlash > 0) { parts[i] = parts[i].substring(0, indSlash) + "-" + max + parts[i].substring(indSlash); } } } return concat(',', parts); }
[ "private", "static", "String", "extendRepeating", "(", "String", "e", ",", "String", "max", ")", "{", "String", "[", "]", "parts", "=", "e", ".", "split", "(", "\",\"", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "parts", ".", "len...
Converts repeating segments from "short" Quartz form to "extended" SauronSoftware form. For example &quot;0/5&quot; will be converted to &quot;0-59/5&quot;, &quot;/3&quot; will be converted to &quot;*&#47;3&quot; @param e Source item @param max Maximal value in this item ("59" for minutes, "23" for hours, etc.) @return Modified string
[ "Converts", "repeating", "segments", "from", "short", "Quartz", "form", "to", "extended", "SauronSoftware", "form", ".", "For", "example", "&quot", ";", "0", "/", "5&quot", ";", "will", "be", "converted", "to", "&quot", ";", "0", "-", "59", "/", "5&quot", ...
train
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-common/src/main/java/com/dell/doradus/management/CronUtils.java#L198-L211
alkacon/opencms-core
src-gwt/org/opencms/gwt/client/ui/input/A_CmsSelectBox.java
A_CmsSelectBox.onValueSelect
protected void onValueSelect(String value, boolean fireEvents) { String oldValue = m_selectedValue; selectValue(value); if (fireEvents) { if ((oldValue == null) || !oldValue.equals(value)) { // fire value change only if the the value really changed ValueChangeEvent.<String> fire(this, value); } } }
java
protected void onValueSelect(String value, boolean fireEvents) { String oldValue = m_selectedValue; selectValue(value); if (fireEvents) { if ((oldValue == null) || !oldValue.equals(value)) { // fire value change only if the the value really changed ValueChangeEvent.<String> fire(this, value); } } }
[ "protected", "void", "onValueSelect", "(", "String", "value", ",", "boolean", "fireEvents", ")", "{", "String", "oldValue", "=", "m_selectedValue", ";", "selectValue", "(", "value", ")", ";", "if", "(", "fireEvents", ")", "{", "if", "(", "(", "oldValue", "...
Internal handler method which is called when a new value is selected.<p> @param value the new value @param fireEvents true if change events should be fired
[ "Internal", "handler", "method", "which", "is", "called", "when", "a", "new", "value", "is", "selected", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/ui/input/A_CmsSelectBox.java#L640-L650
fuinorg/srcgen4javassist
src/main/java/org/fuin/srcgen4javassist/SgUtils.java
SgUtils.toModifiers
public static int toModifiers(final String modifiers) { if (modifiers == null) { return 0; } final String trimmedModifiers = modifiers.trim(); int modifier = 0; final StringTokenizer tok = new StringTokenizer(trimmedModifiers, " "); while (tok.hasMoreTokens()) { final String mod = tok.nextToken(); modifier = modifier | modifierValueForName(mod); } return modifier; }
java
public static int toModifiers(final String modifiers) { if (modifiers == null) { return 0; } final String trimmedModifiers = modifiers.trim(); int modifier = 0; final StringTokenizer tok = new StringTokenizer(trimmedModifiers, " "); while (tok.hasMoreTokens()) { final String mod = tok.nextToken(); modifier = modifier | modifierValueForName(mod); } return modifier; }
[ "public", "static", "int", "toModifiers", "(", "final", "String", "modifiers", ")", "{", "if", "(", "modifiers", "==", "null", ")", "{", "return", "0", ";", "}", "final", "String", "trimmedModifiers", "=", "modifiers", ".", "trim", "(", ")", ";", "int", ...
Returns a Java "Modifier" value for a list of modifier names. @param modifiers Modifier names separated by spaces. @return Modifiers.
[ "Returns", "a", "Java", "Modifier", "value", "for", "a", "list", "of", "modifier", "names", "." ]
train
https://github.com/fuinorg/srcgen4javassist/blob/355828113cfce3cdd3d69ba242c5bdfc7d899f2f/src/main/java/org/fuin/srcgen4javassist/SgUtils.java#L427-L439
ops4j/org.ops4j.base
ops4j-base-util-collections/src/main/java/org/ops4j/util/collections/PropertiesUtils.java
PropertiesUtils.resolveProperty
public static String resolveProperty( Properties props, String value ) { return PropertyResolver.resolve( props, value ); }
java
public static String resolveProperty( Properties props, String value ) { return PropertyResolver.resolve( props, value ); }
[ "public", "static", "String", "resolveProperty", "(", "Properties", "props", ",", "String", "value", ")", "{", "return", "PropertyResolver", ".", "resolve", "(", "props", ",", "value", ")", ";", "}" ]
Resolve symbols in a supplied value against supplied known properties. @param props a set of know properties @param value the string to parse for tokens @return the resolved string
[ "Resolve", "symbols", "in", "a", "supplied", "value", "against", "supplied", "known", "properties", "." ]
train
https://github.com/ops4j/org.ops4j.base/blob/b0e742c0d9511f6b19ca64da2ebaf30b7a47256a/ops4j-base-util-collections/src/main/java/org/ops4j/util/collections/PropertiesUtils.java#L139-L142
haifengl/smile
core/src/main/java/smile/taxonomy/Taxonomy.java
Taxonomy.lowestCommonAncestor
public Concept lowestCommonAncestor(String v, String w) { Concept vnode = getConcept(v); Concept wnode = getConcept(w); return lowestCommonAncestor(vnode, wnode); }
java
public Concept lowestCommonAncestor(String v, String w) { Concept vnode = getConcept(v); Concept wnode = getConcept(w); return lowestCommonAncestor(vnode, wnode); }
[ "public", "Concept", "lowestCommonAncestor", "(", "String", "v", ",", "String", "w", ")", "{", "Concept", "vnode", "=", "getConcept", "(", "v", ")", ";", "Concept", "wnode", "=", "getConcept", "(", "w", ")", ";", "return", "lowestCommonAncestor", "(", "vno...
Returns the lowest common ancestor (LCA) of concepts v and w. The lowest common ancestor is defined between two nodes v and w as the lowest node that has both v and w as descendants (where we allow a node to be a descendant of itself).
[ "Returns", "the", "lowest", "common", "ancestor", "(", "LCA", ")", "of", "concepts", "v", "and", "w", ".", "The", "lowest", "common", "ancestor", "is", "defined", "between", "two", "nodes", "v", "and", "w", "as", "the", "lowest", "node", "that", "has", ...
train
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/core/src/main/java/smile/taxonomy/Taxonomy.java#L110-L115
google/error-prone-javac
src/jdk.compiler/share/classes/com/sun/tools/javac/tree/TreeInfo.java
TreeInfo.isStaticSelector
public static boolean isStaticSelector(JCTree base, Names names) { if (base == null) return false; switch (base.getTag()) { case IDENT: JCIdent id = (JCIdent)base; return id.name != names._this && id.name != names._super && isStaticSym(base); case SELECT: return isStaticSym(base) && isStaticSelector(((JCFieldAccess)base).selected, names); case TYPEAPPLY: case TYPEARRAY: return true; case ANNOTATED_TYPE: return isStaticSelector(((JCAnnotatedType)base).underlyingType, names); default: return false; } }
java
public static boolean isStaticSelector(JCTree base, Names names) { if (base == null) return false; switch (base.getTag()) { case IDENT: JCIdent id = (JCIdent)base; return id.name != names._this && id.name != names._super && isStaticSym(base); case SELECT: return isStaticSym(base) && isStaticSelector(((JCFieldAccess)base).selected, names); case TYPEAPPLY: case TYPEARRAY: return true; case ANNOTATED_TYPE: return isStaticSelector(((JCAnnotatedType)base).underlyingType, names); default: return false; } }
[ "public", "static", "boolean", "isStaticSelector", "(", "JCTree", "base", ",", "Names", "names", ")", "{", "if", "(", "base", "==", "null", ")", "return", "false", ";", "switch", "(", "base", ".", "getTag", "(", ")", ")", "{", "case", "IDENT", ":", "...
Return true if the AST corresponds to a static select of the kind A.B
[ "Return", "true", "if", "the", "AST", "corresponds", "to", "a", "static", "select", "of", "the", "kind", "A", ".", "B" ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/TreeInfo.java#L283-L303
netty/netty
codec-http/src/main/java/io/netty/handler/codec/http/HttpUtil.java
HttpUtil.setTransferEncodingChunked
public static void setTransferEncodingChunked(HttpMessage m, boolean chunked) { if (chunked) { m.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED); m.headers().remove(HttpHeaderNames.CONTENT_LENGTH); } else { List<String> encodings = m.headers().getAll(HttpHeaderNames.TRANSFER_ENCODING); if (encodings.isEmpty()) { return; } List<CharSequence> values = new ArrayList<CharSequence>(encodings); Iterator<CharSequence> valuesIt = values.iterator(); while (valuesIt.hasNext()) { CharSequence value = valuesIt.next(); if (HttpHeaderValues.CHUNKED.contentEqualsIgnoreCase(value)) { valuesIt.remove(); } } if (values.isEmpty()) { m.headers().remove(HttpHeaderNames.TRANSFER_ENCODING); } else { m.headers().set(HttpHeaderNames.TRANSFER_ENCODING, values); } } }
java
public static void setTransferEncodingChunked(HttpMessage m, boolean chunked) { if (chunked) { m.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED); m.headers().remove(HttpHeaderNames.CONTENT_LENGTH); } else { List<String> encodings = m.headers().getAll(HttpHeaderNames.TRANSFER_ENCODING); if (encodings.isEmpty()) { return; } List<CharSequence> values = new ArrayList<CharSequence>(encodings); Iterator<CharSequence> valuesIt = values.iterator(); while (valuesIt.hasNext()) { CharSequence value = valuesIt.next(); if (HttpHeaderValues.CHUNKED.contentEqualsIgnoreCase(value)) { valuesIt.remove(); } } if (values.isEmpty()) { m.headers().remove(HttpHeaderNames.TRANSFER_ENCODING); } else { m.headers().set(HttpHeaderNames.TRANSFER_ENCODING, values); } } }
[ "public", "static", "void", "setTransferEncodingChunked", "(", "HttpMessage", "m", ",", "boolean", "chunked", ")", "{", "if", "(", "chunked", ")", "{", "m", ".", "headers", "(", ")", ".", "set", "(", "HttpHeaderNames", ".", "TRANSFER_ENCODING", ",", "HttpHea...
Set the {@link HttpHeaderNames#TRANSFER_ENCODING} to either include {@link HttpHeaderValues#CHUNKED} if {@code chunked} is {@code true}, or remove {@link HttpHeaderValues#CHUNKED} if {@code chunked} is {@code false}. @param m The message which contains the headers to modify. @param chunked if {@code true} then include {@link HttpHeaderValues#CHUNKED} in the headers. otherwise remove {@link HttpHeaderValues#CHUNKED} from the headers.
[ "Set", "the", "{", "@link", "HttpHeaderNames#TRANSFER_ENCODING", "}", "to", "either", "include", "{", "@link", "HttpHeaderValues#CHUNKED", "}", "if", "{", "@code", "chunked", "}", "is", "{", "@code", "true", "}", "or", "remove", "{", "@link", "HttpHeaderValues#C...
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/codec-http/src/main/java/io/netty/handler/codec/http/HttpUtil.java#L312-L335
knowm/XChange
xchange-dsx/src/main/java/org/knowm/xchange/dsx/service/core/DSXMarketDataServiceCore.java
DSXMarketDataServiceCore.getOrderBook
@Override public OrderBook getOrderBook(CurrencyPair currencyPair, Object... args) throws IOException { String marketName = DSXAdapters.currencyPairToMarketName(currencyPair); String accountType = null; try { if (args != null) { accountType = (String) args[0]; } } catch (ArrayIndexOutOfBoundsException e) { // ignore, can happen if no argument given. } DSXOrderbookWrapper dsxOrderbookWrapper = getDSXOrderbook(marketName, accountType); DSXOrderbook orderbook = dsxOrderbookWrapper.getOrderbook(marketName); // Adapt to XChange DTOs List<LimitOrder> asks = DSXAdapters.adaptOrders(orderbook.getAsks(), currencyPair, "ask", ""); List<LimitOrder> bids = DSXAdapters.adaptOrders(orderbook.getBids(), currencyPair, "bid", ""); return new OrderBook(null, asks, bids); }
java
@Override public OrderBook getOrderBook(CurrencyPair currencyPair, Object... args) throws IOException { String marketName = DSXAdapters.currencyPairToMarketName(currencyPair); String accountType = null; try { if (args != null) { accountType = (String) args[0]; } } catch (ArrayIndexOutOfBoundsException e) { // ignore, can happen if no argument given. } DSXOrderbookWrapper dsxOrderbookWrapper = getDSXOrderbook(marketName, accountType); DSXOrderbook orderbook = dsxOrderbookWrapper.getOrderbook(marketName); // Adapt to XChange DTOs List<LimitOrder> asks = DSXAdapters.adaptOrders(orderbook.getAsks(), currencyPair, "ask", ""); List<LimitOrder> bids = DSXAdapters.adaptOrders(orderbook.getBids(), currencyPair, "bid", ""); return new OrderBook(null, asks, bids); }
[ "@", "Override", "public", "OrderBook", "getOrderBook", "(", "CurrencyPair", "currencyPair", ",", "Object", "...", "args", ")", "throws", "IOException", "{", "String", "marketName", "=", "DSXAdapters", ".", "currencyPairToMarketName", "(", "currencyPair", ")", ";", ...
Get market depth from exchange @param currencyPair Currency pair for getting info about @param args Optional arguments. Exchange-specific @return The OrderBook @throws IOException
[ "Get", "market", "depth", "from", "exchange" ]
train
https://github.com/knowm/XChange/blob/e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186/xchange-dsx/src/main/java/org/knowm/xchange/dsx/service/core/DSXMarketDataServiceCore.java#L67-L89
threerings/narya
core/src/main/java/com/threerings/presents/server/InvocationException.java
InvocationException.requireAccess
public static void requireAccess (ClientObject clobj, Permission perm, Object context) throws InvocationException { String errmsg = clobj.checkAccess(perm, context); if (errmsg != null) { throw new InvocationException(errmsg); } }
java
public static void requireAccess (ClientObject clobj, Permission perm, Object context) throws InvocationException { String errmsg = clobj.checkAccess(perm, context); if (errmsg != null) { throw new InvocationException(errmsg); } }
[ "public", "static", "void", "requireAccess", "(", "ClientObject", "clobj", ",", "Permission", "perm", ",", "Object", "context", ")", "throws", "InvocationException", "{", "String", "errmsg", "=", "clobj", ".", "checkAccess", "(", "perm", ",", "context", ")", "...
Requires that the specified client have the specified permissions. @throws InvocationException if they do not.
[ "Requires", "that", "the", "specified", "client", "have", "the", "specified", "permissions", "." ]
train
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/server/InvocationException.java#L39-L46
exoplatform/jcr
exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/backup/impl/BackupManagerImpl.java
BackupManagerImpl.startBackup
BackupChain startBackup(BackupConfig config, BackupJobListener jobListener) throws BackupOperationException, BackupConfigurationException, RepositoryException, RepositoryConfigurationException { validateBackupConfig(config); Calendar startTime = Calendar.getInstance(); File dir = FileNameProducer.generateBackupSetDir(config.getRepository(), config.getWorkspace(), config.getBackupDir() .getPath(), startTime); PrivilegedFileHelper.mkdirs(dir); config.setBackupDir(dir); BackupChain bchain = new BackupChainImpl(config, logsDirectory, repoService, fullBackupType, incrementalBackupType, IdGenerator .generate(), logsDirectory, startTime); bchain.addListener(messagesListener); bchain.addListener(jobListener); currentBackups.add(bchain); bchain.startBackup(); return bchain; }
java
BackupChain startBackup(BackupConfig config, BackupJobListener jobListener) throws BackupOperationException, BackupConfigurationException, RepositoryException, RepositoryConfigurationException { validateBackupConfig(config); Calendar startTime = Calendar.getInstance(); File dir = FileNameProducer.generateBackupSetDir(config.getRepository(), config.getWorkspace(), config.getBackupDir() .getPath(), startTime); PrivilegedFileHelper.mkdirs(dir); config.setBackupDir(dir); BackupChain bchain = new BackupChainImpl(config, logsDirectory, repoService, fullBackupType, incrementalBackupType, IdGenerator .generate(), logsDirectory, startTime); bchain.addListener(messagesListener); bchain.addListener(jobListener); currentBackups.add(bchain); bchain.startBackup(); return bchain; }
[ "BackupChain", "startBackup", "(", "BackupConfig", "config", ",", "BackupJobListener", "jobListener", ")", "throws", "BackupOperationException", ",", "BackupConfigurationException", ",", "RepositoryException", ",", "RepositoryConfigurationException", "{", "validateBackupConfig", ...
Internally used for call with job listener from scheduler. @param config @param jobListener @return @throws BackupOperationException @throws BackupConfigurationException @throws RepositoryException @throws RepositoryConfigurationException
[ "Internally", "used", "for", "call", "with", "job", "listener", "from", "scheduler", "." ]
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/backup/impl/BackupManagerImpl.java#L764-L787
wcm-io/wcm-io-handler
media/src/main/java/io/wcm/handler/mediasource/dam/impl/DamAsset.java
DamAsset.getDamRendition
protected Rendition getDamRendition(MediaArgs mediaArgs) { return new DamRendition(this.damAsset, this.cropDimension, this.rotation, mediaArgs, adaptable); }
java
protected Rendition getDamRendition(MediaArgs mediaArgs) { return new DamRendition(this.damAsset, this.cropDimension, this.rotation, mediaArgs, adaptable); }
[ "protected", "Rendition", "getDamRendition", "(", "MediaArgs", "mediaArgs", ")", "{", "return", "new", "DamRendition", "(", "this", ".", "damAsset", ",", "this", ".", "cropDimension", ",", "this", ".", "rotation", ",", "mediaArgs", ",", "adaptable", ")", ";", ...
Get DAM rendition instance. @param mediaArgs Media args @return DAM rendition instance (may be invalid rendition)
[ "Get", "DAM", "rendition", "instance", "." ]
train
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/media/src/main/java/io/wcm/handler/mediasource/dam/impl/DamAsset.java#L161-L163
lucee/Lucee
core/src/main/java/lucee/runtime/rest/RestUtil.java
RestUtil.matchPath
public static int matchPath(Struct variables, Path[] restPath, String[] callerPath) { if (restPath.length > callerPath.length) return -1; int index = 0; for (; index < restPath.length; index++) { if (!restPath[index].match(variables, callerPath[index])) return -1; } return index - 1; }
java
public static int matchPath(Struct variables, Path[] restPath, String[] callerPath) { if (restPath.length > callerPath.length) return -1; int index = 0; for (; index < restPath.length; index++) { if (!restPath[index].match(variables, callerPath[index])) return -1; } return index - 1; }
[ "public", "static", "int", "matchPath", "(", "Struct", "variables", ",", "Path", "[", "]", "restPath", ",", "String", "[", "]", "callerPath", ")", "{", "if", "(", "restPath", ".", "length", ">", "callerPath", ".", "length", ")", "return", "-", "1", ";"...
check if caller path match the cfc path @param variables @param restPath @param callerPath @return match until which index of the given cfc path, returns -1 if there is no match
[ "check", "if", "caller", "path", "match", "the", "cfc", "path" ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/rest/RestUtil.java#L46-L54
zaproxy/zaproxy
src/org/parosproxy/paros/network/HttpHeader.java
HttpHeader.setHeader
public void setHeader(String name, String value) { // int pos = 0; // int crlfpos = 0; Pattern pattern = null; if (getHeaders(name) == null && value != null) { // header value not found, append to end addHeader(name, value); } else { pattern = getHeaderRegex(name); Matcher matcher = pattern.matcher(mMsgHeader); if (value == null) { // delete header mMsgHeader = matcher.replaceAll(""); } else { // replace header String newString = name + ": " + value + mLineDelimiter; mMsgHeader = matcher.replaceAll(Matcher.quoteReplacement(newString)); } // set into hashtable replaceInternalHeaderFields(name, value); } }
java
public void setHeader(String name, String value) { // int pos = 0; // int crlfpos = 0; Pattern pattern = null; if (getHeaders(name) == null && value != null) { // header value not found, append to end addHeader(name, value); } else { pattern = getHeaderRegex(name); Matcher matcher = pattern.matcher(mMsgHeader); if (value == null) { // delete header mMsgHeader = matcher.replaceAll(""); } else { // replace header String newString = name + ": " + value + mLineDelimiter; mMsgHeader = matcher.replaceAll(Matcher.quoteReplacement(newString)); } // set into hashtable replaceInternalHeaderFields(name, value); } }
[ "public", "void", "setHeader", "(", "String", "name", ",", "String", "value", ")", "{", "//\t\tint pos = 0;\r", "//\t\tint crlfpos = 0;\r", "Pattern", "pattern", "=", "null", ";", "if", "(", "getHeaders", "(", "name", ")", "==", "null", "&&", "value", "!=", ...
Set a header name and value. If the name is not found, it will be added. If the value is null, the header will be removed. @param name @param value
[ "Set", "a", "header", "name", "and", "value", ".", "If", "the", "name", "is", "not", "found", "it", "will", "be", "added", ".", "If", "the", "value", "is", "null", "the", "header", "will", "be", "removed", "." ]
train
https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/parosproxy/paros/network/HttpHeader.java#L250-L273
spring-projects/spring-ldap
core/src/main/java/org/springframework/ldap/core/support/AbstractContextSource.java
AbstractContextSource.createContext
protected DirContext createContext(Hashtable<String, Object> environment) { DirContext ctx = null; try { ctx = getDirContextInstance(environment); if (LOG.isInfoEnabled()) { Hashtable<?, ?> ctxEnv = ctx.getEnvironment(); String ldapUrl = (String) ctxEnv.get(Context.PROVIDER_URL); LOG.debug("Got Ldap context on server '" + ldapUrl + "'"); } return ctx; } catch (NamingException e) { closeContext(ctx); throw LdapUtils.convertLdapException(e); } }
java
protected DirContext createContext(Hashtable<String, Object> environment) { DirContext ctx = null; try { ctx = getDirContextInstance(environment); if (LOG.isInfoEnabled()) { Hashtable<?, ?> ctxEnv = ctx.getEnvironment(); String ldapUrl = (String) ctxEnv.get(Context.PROVIDER_URL); LOG.debug("Got Ldap context on server '" + ldapUrl + "'"); } return ctx; } catch (NamingException e) { closeContext(ctx); throw LdapUtils.convertLdapException(e); } }
[ "protected", "DirContext", "createContext", "(", "Hashtable", "<", "String", ",", "Object", ">", "environment", ")", "{", "DirContext", "ctx", "=", "null", ";", "try", "{", "ctx", "=", "getDirContextInstance", "(", "environment", ")", ";", "if", "(", "LOG", ...
Create a DirContext using the supplied environment. @param environment the LDAP environment to use when creating the <code>DirContext</code>. @return a new DirContext implementation initialized with the supplied environment.
[ "Create", "a", "DirContext", "using", "the", "supplied", "environment", "." ]
train
https://github.com/spring-projects/spring-ldap/blob/15142d4ae18a9dc6b363a1ebf085e2bda9d9a4c0/core/src/main/java/org/springframework/ldap/core/support/AbstractContextSource.java#L339-L357
nextreports/nextreports-engine
src/ro/nextreports/engine/util/ReportUtil.java
ReportUtil.saveReport
public static void saveReport(Report report, String path) { FileOutputStream fos = null; try { fos = new FileOutputStream(path); saveReport(report, fos); } catch (Exception ex) { LOG.error(ex.getMessage(), ex); ex.printStackTrace(); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } }
java
public static void saveReport(Report report, String path) { FileOutputStream fos = null; try { fos = new FileOutputStream(path); saveReport(report, fos); } catch (Exception ex) { LOG.error(ex.getMessage(), ex); ex.printStackTrace(); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } }
[ "public", "static", "void", "saveReport", "(", "Report", "report", ",", "String", "path", ")", "{", "FileOutputStream", "fos", "=", "null", ";", "try", "{", "fos", "=", "new", "FileOutputStream", "(", "path", ")", ";", "saveReport", "(", "report", ",", "...
Write a report object to a file at specified path @param report report object @param path file path
[ "Write", "a", "report", "object", "to", "a", "file", "at", "specified", "path" ]
train
https://github.com/nextreports/nextreports-engine/blob/a847575a9298b5fce63b88961190c5b83ddccc44/src/ro/nextreports/engine/util/ReportUtil.java#L211-L228