repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
218
func_name
stringlengths
4
140
whole_func_string
stringlengths
153
5.32k
language
stringclasses
1 value
func_code_string
stringlengths
72
4k
func_code_tokens
sequencelengths
20
832
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
sequencelengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
102
339
albfernandez/itext2
src/main/java/com/lowagie/text/pdf/PdfChunk.java
PdfChunk.getWidthCorrected
public float getWidthCorrected(float charSpacing, float wordSpacing) { """ Gets the width of the <CODE>PdfChunk</CODE> taking into account the extra character and word spacing. @param charSpacing the extra character spacing @param wordSpacing the extra word spacing @return the calculated width """ if (image != null) { return image.getScaledWidth() + charSpacing; } int numberOfSpaces = 0; int idx = -1; while ((idx = value.indexOf(' ', idx + 1)) >= 0) ++numberOfSpaces; return width() + (value.length() * charSpacing + numberOfSpaces * wordSpacing); }
java
public float getWidthCorrected(float charSpacing, float wordSpacing) { if (image != null) { return image.getScaledWidth() + charSpacing; } int numberOfSpaces = 0; int idx = -1; while ((idx = value.indexOf(' ', idx + 1)) >= 0) ++numberOfSpaces; return width() + (value.length() * charSpacing + numberOfSpaces * wordSpacing); }
[ "public", "float", "getWidthCorrected", "(", "float", "charSpacing", ",", "float", "wordSpacing", ")", "{", "if", "(", "image", "!=", "null", ")", "{", "return", "image", ".", "getScaledWidth", "(", ")", "+", "charSpacing", ";", "}", "int", "numberOfSpaces", "=", "0", ";", "int", "idx", "=", "-", "1", ";", "while", "(", "(", "idx", "=", "value", ".", "indexOf", "(", "'", "'", ",", "idx", "+", "1", ")", ")", ">=", "0", ")", "++", "numberOfSpaces", ";", "return", "width", "(", ")", "+", "(", "value", ".", "length", "(", ")", "*", "charSpacing", "+", "numberOfSpaces", "*", "wordSpacing", ")", ";", "}" ]
Gets the width of the <CODE>PdfChunk</CODE> taking into account the extra character and word spacing. @param charSpacing the extra character spacing @param wordSpacing the extra word spacing @return the calculated width
[ "Gets", "the", "width", "of", "the", "<CODE", ">", "PdfChunk<", "/", "CODE", ">", "taking", "into", "account", "the", "extra", "character", "and", "word", "spacing", "." ]
train
https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/PdfChunk.java#L548-L558
gmessner/gitlab4j-api
src/main/java/org/gitlab4j/api/GroupApi.java
GroupApi.deleteLdapGroupLink
public void deleteLdapGroupLink(Object groupIdOrPath, String cn) throws GitLabApiException { """ Deletes an LDAP group link. <pre><code>GitLab Endpoint: DELETE /groups/:id/ldap_group_links/:cn</code></pre> @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path @param cn the CN of the LDAP group link to delete @throws GitLabApiException if any exception occurs """ if (cn == null || cn.trim().isEmpty()) { throw new RuntimeException("cn cannot be null or empty"); } delete(Response.Status.OK, null, "groups", getGroupIdOrPath(groupIdOrPath), "ldap_group_links", cn); }
java
public void deleteLdapGroupLink(Object groupIdOrPath, String cn) throws GitLabApiException { if (cn == null || cn.trim().isEmpty()) { throw new RuntimeException("cn cannot be null or empty"); } delete(Response.Status.OK, null, "groups", getGroupIdOrPath(groupIdOrPath), "ldap_group_links", cn); }
[ "public", "void", "deleteLdapGroupLink", "(", "Object", "groupIdOrPath", ",", "String", "cn", ")", "throws", "GitLabApiException", "{", "if", "(", "cn", "==", "null", "||", "cn", ".", "trim", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "throw", "new", "RuntimeException", "(", "\"cn cannot be null or empty\"", ")", ";", "}", "delete", "(", "Response", ".", "Status", ".", "OK", ",", "null", ",", "\"groups\"", ",", "getGroupIdOrPath", "(", "groupIdOrPath", ")", ",", "\"ldap_group_links\"", ",", "cn", ")", ";", "}" ]
Deletes an LDAP group link. <pre><code>GitLab Endpoint: DELETE /groups/:id/ldap_group_links/:cn</code></pre> @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path @param cn the CN of the LDAP group link to delete @throws GitLabApiException if any exception occurs
[ "Deletes", "an", "LDAP", "group", "link", "." ]
train
https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/GroupApi.java#L961-L968
hltcoe/annotated-nyt
src/main/java/com/nytlabs/corpus/NYTCorpusDocumentParser.java
NYTCorpusDocumentParser.parseStringToDOM
private Document parseStringToDOM(String s, String encoding) { """ Parse a string to a DOM document. @param s A string containing an XML document. @return The DOM document if it can be parsed, or null otherwise. """ try { DocumentBuilderFactory factory = DocumentBuilderFactory .newInstance(); factory.setValidating(false); InputStream is = new ByteArrayInputStream(s.getBytes(encoding)); Document doc = factory.newDocumentBuilder().parse(is); return doc; } catch (SAXException e) { e.printStackTrace(); System.out.println("Exception processing string."); } catch (ParserConfigurationException e) { e.printStackTrace(); System.out.println("Exception processing string."); } catch (IOException e) { e.printStackTrace(); System.out.println("Exception processing string."); } return null; }
java
private Document parseStringToDOM(String s, String encoding) { try { DocumentBuilderFactory factory = DocumentBuilderFactory .newInstance(); factory.setValidating(false); InputStream is = new ByteArrayInputStream(s.getBytes(encoding)); Document doc = factory.newDocumentBuilder().parse(is); return doc; } catch (SAXException e) { e.printStackTrace(); System.out.println("Exception processing string."); } catch (ParserConfigurationException e) { e.printStackTrace(); System.out.println("Exception processing string."); } catch (IOException e) { e.printStackTrace(); System.out.println("Exception processing string."); } return null; }
[ "private", "Document", "parseStringToDOM", "(", "String", "s", ",", "String", "encoding", ")", "{", "try", "{", "DocumentBuilderFactory", "factory", "=", "DocumentBuilderFactory", ".", "newInstance", "(", ")", ";", "factory", ".", "setValidating", "(", "false", ")", ";", "InputStream", "is", "=", "new", "ByteArrayInputStream", "(", "s", ".", "getBytes", "(", "encoding", ")", ")", ";", "Document", "doc", "=", "factory", ".", "newDocumentBuilder", "(", ")", ".", "parse", "(", "is", ")", ";", "return", "doc", ";", "}", "catch", "(", "SAXException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "System", ".", "out", ".", "println", "(", "\"Exception processing string.\"", ")", ";", "}", "catch", "(", "ParserConfigurationException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "System", ".", "out", ".", "println", "(", "\"Exception processing string.\"", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "System", ".", "out", ".", "println", "(", "\"Exception processing string.\"", ")", ";", "}", "return", "null", ";", "}" ]
Parse a string to a DOM document. @param s A string containing an XML document. @return The DOM document if it can be parsed, or null otherwise.
[ "Parse", "a", "string", "to", "a", "DOM", "document", "." ]
train
https://github.com/hltcoe/annotated-nyt/blob/0a4daa97705591cefea9de61614770ae2665a48e/src/main/java/com/nytlabs/corpus/NYTCorpusDocumentParser.java#L430-L449
eclipse/hawkbit
hawkbit-dmf/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpDeadletterProperties.java
AmqpDeadletterProperties.createDeadletterQueue
public Queue createDeadletterQueue(final String queueName) { """ Create a deadletter queue with ttl for messages @param queueName the deadlette queue name @return the deadletter queue """ return new Queue(queueName, true, false, false, getTTLArgs()); }
java
public Queue createDeadletterQueue(final String queueName) { return new Queue(queueName, true, false, false, getTTLArgs()); }
[ "public", "Queue", "createDeadletterQueue", "(", "final", "String", "queueName", ")", "{", "return", "new", "Queue", "(", "queueName", ",", "true", ",", "false", ",", "false", ",", "getTTLArgs", "(", ")", ")", ";", "}" ]
Create a deadletter queue with ttl for messages @param queueName the deadlette queue name @return the deadletter queue
[ "Create", "a", "deadletter", "queue", "with", "ttl", "for", "messages" ]
train
https://github.com/eclipse/hawkbit/blob/9884452ad42f3b4827461606d8a9215c8625a7fe/hawkbit-dmf/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpDeadletterProperties.java#L53-L55
elki-project/elki
elki/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/subspace/DiSH.java
DiSH.logClusterSizes
private void logClusterSizes(String m, int dimensionality, Object2ObjectOpenCustomHashMap<long[], List<ArrayModifiableDBIDs>> clustersMap) { """ Log cluster sizes in verbose mode. @param m Log message @param dimensionality Dimensionality @param clustersMap Cluster map """ if(LOG.isVerbose()) { final StringBuilder msg = new StringBuilder(1000).append(m).append('\n'); for(ObjectIterator<Object2ObjectMap.Entry<long[], List<ArrayModifiableDBIDs>>> iter = clustersMap.object2ObjectEntrySet().fastIterator(); iter.hasNext();) { Object2ObjectMap.Entry<long[], List<ArrayModifiableDBIDs>> entry = iter.next(); msg.append(BitsUtil.toStringLow(entry.getKey(), dimensionality)).append(" sizes:"); for(ArrayModifiableDBIDs c : entry.getValue()) { msg.append(' ').append(c.size()); } msg.append('\n'); } LOG.verbose(msg.toString()); } }
java
private void logClusterSizes(String m, int dimensionality, Object2ObjectOpenCustomHashMap<long[], List<ArrayModifiableDBIDs>> clustersMap) { if(LOG.isVerbose()) { final StringBuilder msg = new StringBuilder(1000).append(m).append('\n'); for(ObjectIterator<Object2ObjectMap.Entry<long[], List<ArrayModifiableDBIDs>>> iter = clustersMap.object2ObjectEntrySet().fastIterator(); iter.hasNext();) { Object2ObjectMap.Entry<long[], List<ArrayModifiableDBIDs>> entry = iter.next(); msg.append(BitsUtil.toStringLow(entry.getKey(), dimensionality)).append(" sizes:"); for(ArrayModifiableDBIDs c : entry.getValue()) { msg.append(' ').append(c.size()); } msg.append('\n'); } LOG.verbose(msg.toString()); } }
[ "private", "void", "logClusterSizes", "(", "String", "m", ",", "int", "dimensionality", ",", "Object2ObjectOpenCustomHashMap", "<", "long", "[", "]", ",", "List", "<", "ArrayModifiableDBIDs", ">", ">", "clustersMap", ")", "{", "if", "(", "LOG", ".", "isVerbose", "(", ")", ")", "{", "final", "StringBuilder", "msg", "=", "new", "StringBuilder", "(", "1000", ")", ".", "append", "(", "m", ")", ".", "append", "(", "'", "'", ")", ";", "for", "(", "ObjectIterator", "<", "Object2ObjectMap", ".", "Entry", "<", "long", "[", "]", ",", "List", "<", "ArrayModifiableDBIDs", ">", ">", ">", "iter", "=", "clustersMap", ".", "object2ObjectEntrySet", "(", ")", ".", "fastIterator", "(", ")", ";", "iter", ".", "hasNext", "(", ")", ";", ")", "{", "Object2ObjectMap", ".", "Entry", "<", "long", "[", "]", ",", "List", "<", "ArrayModifiableDBIDs", ">", ">", "entry", "=", "iter", ".", "next", "(", ")", ";", "msg", ".", "append", "(", "BitsUtil", ".", "toStringLow", "(", "entry", ".", "getKey", "(", ")", ",", "dimensionality", ")", ")", ".", "append", "(", "\" sizes:\"", ")", ";", "for", "(", "ArrayModifiableDBIDs", "c", ":", "entry", ".", "getValue", "(", ")", ")", "{", "msg", ".", "append", "(", "'", "'", ")", ".", "append", "(", "c", ".", "size", "(", ")", ")", ";", "}", "msg", ".", "append", "(", "'", "'", ")", ";", "}", "LOG", ".", "verbose", "(", "msg", ".", "toString", "(", ")", ")", ";", "}", "}" ]
Log cluster sizes in verbose mode. @param m Log message @param dimensionality Dimensionality @param clustersMap Cluster map
[ "Log", "cluster", "sizes", "in", "verbose", "mode", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/subspace/DiSH.java#L220-L233
flavioarfaria/KenBurnsView
library/src/main/java/com/flaviofaria/kenburnsview/MathUtils.java
MathUtils.haveSameAspectRatio
protected static boolean haveSameAspectRatio(RectF r1, RectF r2) { """ Checks whether two {@link RectF} have the same aspect ratio. @param r1 the first rect. @param r2 the second rect. @return {@code true} if both rectangles have the same aspect ratio, {@code false} otherwise. """ // Reduces precision to avoid problems when comparing aspect ratios. float srcRectRatio = MathUtils.truncate(MathUtils.getRectRatio(r1), 3); float dstRectRatio = MathUtils.truncate(MathUtils.getRectRatio(r2), 3); // Compares aspect ratios that allows for a tolerance range of [0, 0.01] return (Math.abs(srcRectRatio-dstRectRatio) <= 0.01f); }
java
protected static boolean haveSameAspectRatio(RectF r1, RectF r2) { // Reduces precision to avoid problems when comparing aspect ratios. float srcRectRatio = MathUtils.truncate(MathUtils.getRectRatio(r1), 3); float dstRectRatio = MathUtils.truncate(MathUtils.getRectRatio(r2), 3); // Compares aspect ratios that allows for a tolerance range of [0, 0.01] return (Math.abs(srcRectRatio-dstRectRatio) <= 0.01f); }
[ "protected", "static", "boolean", "haveSameAspectRatio", "(", "RectF", "r1", ",", "RectF", "r2", ")", "{", "// Reduces precision to avoid problems when comparing aspect ratios.", "float", "srcRectRatio", "=", "MathUtils", ".", "truncate", "(", "MathUtils", ".", "getRectRatio", "(", "r1", ")", ",", "3", ")", ";", "float", "dstRectRatio", "=", "MathUtils", ".", "truncate", "(", "MathUtils", ".", "getRectRatio", "(", "r2", ")", ",", "3", ")", ";", "// Compares aspect ratios that allows for a tolerance range of [0, 0.01] ", "return", "(", "Math", ".", "abs", "(", "srcRectRatio", "-", "dstRectRatio", ")", "<=", "0.01f", ")", ";", "}" ]
Checks whether two {@link RectF} have the same aspect ratio. @param r1 the first rect. @param r2 the second rect. @return {@code true} if both rectangles have the same aspect ratio, {@code false} otherwise.
[ "Checks", "whether", "two", "{" ]
train
https://github.com/flavioarfaria/KenBurnsView/blob/57a0fd7a586759c5c2e18fda51a3fcb09b48f388/library/src/main/java/com/flaviofaria/kenburnsview/MathUtils.java#L45-L52
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/string/StringHelper.java
StringHelper.getConcatenatedOnDemand
@Nonnull public static String getConcatenatedOnDemand (@Nullable final String sFront, @Nullable final String sEnd) { """ Concatenate the strings sFront and sEnd. If either front or back is <code>null</code> or empty only the other element is returned. If both strings are <code>null</code> or empty and empty String is returned. @param sFront Front string. May be <code>null</code>. @param sEnd May be <code>null</code>. @return The concatenated string. Never <code>null</code>. """ if (sFront == null) return sEnd == null ? "" : sEnd; if (sEnd == null) return sFront; return sFront + sEnd; }
java
@Nonnull public static String getConcatenatedOnDemand (@Nullable final String sFront, @Nullable final String sEnd) { if (sFront == null) return sEnd == null ? "" : sEnd; if (sEnd == null) return sFront; return sFront + sEnd; }
[ "@", "Nonnull", "public", "static", "String", "getConcatenatedOnDemand", "(", "@", "Nullable", "final", "String", "sFront", ",", "@", "Nullable", "final", "String", "sEnd", ")", "{", "if", "(", "sFront", "==", "null", ")", "return", "sEnd", "==", "null", "?", "\"\"", ":", "sEnd", ";", "if", "(", "sEnd", "==", "null", ")", "return", "sFront", ";", "return", "sFront", "+", "sEnd", ";", "}" ]
Concatenate the strings sFront and sEnd. If either front or back is <code>null</code> or empty only the other element is returned. If both strings are <code>null</code> or empty and empty String is returned. @param sFront Front string. May be <code>null</code>. @param sEnd May be <code>null</code>. @return The concatenated string. Never <code>null</code>.
[ "Concatenate", "the", "strings", "sFront", "and", "sEnd", ".", "If", "either", "front", "or", "back", "is", "<code", ">", "null<", "/", "code", ">", "or", "empty", "only", "the", "other", "element", "is", "returned", ".", "If", "both", "strings", "are", "<code", ">", "null<", "/", "code", ">", "or", "empty", "and", "empty", "String", "is", "returned", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/string/StringHelper.java#L2418-L2426
elki-project/elki
elki-core-api/src/main/java/de/lmu/ifi/dbs/elki/data/spatial/SpatialUtil.java
SpatialUtil.relativeOverlap
public static double relativeOverlap(SpatialComparable box1, SpatialComparable box2) { """ Computes the volume of the overlapping box between two SpatialComparables and return the relation between the volume of the overlapping box and the volume of both SpatialComparable. @param box1 the first SpatialComparable @param box2 the second SpatialComparable @return the overlap volume in relation to the singular volumes. """ final int dim = assertSameDimensionality(box1, box2); // the overlap volume double overlap = 1.; double vol1 = 1.; double vol2 = 1.; for(int i = 0; i < dim; i++) { final double box1min = box1.getMin(i); final double box1max = box1.getMax(i); final double box2min = box2.getMin(i); final double box2max = box2.getMax(i); final double omax = Math.min(box1max, box2max); final double omin = Math.max(box1min, box2min); // if omax <= omin in any dimension, the overlap box has a volume of zero if(omax <= omin) { return 0.; } overlap *= omax - omin; vol1 *= box1max - box1min; vol2 *= box2max - box2min; } return overlap / (vol1 + vol2); }
java
public static double relativeOverlap(SpatialComparable box1, SpatialComparable box2) { final int dim = assertSameDimensionality(box1, box2); // the overlap volume double overlap = 1.; double vol1 = 1.; double vol2 = 1.; for(int i = 0; i < dim; i++) { final double box1min = box1.getMin(i); final double box1max = box1.getMax(i); final double box2min = box2.getMin(i); final double box2max = box2.getMax(i); final double omax = Math.min(box1max, box2max); final double omin = Math.max(box1min, box2min); // if omax <= omin in any dimension, the overlap box has a volume of zero if(omax <= omin) { return 0.; } overlap *= omax - omin; vol1 *= box1max - box1min; vol2 *= box2max - box2min; } return overlap / (vol1 + vol2); }
[ "public", "static", "double", "relativeOverlap", "(", "SpatialComparable", "box1", ",", "SpatialComparable", "box2", ")", "{", "final", "int", "dim", "=", "assertSameDimensionality", "(", "box1", ",", "box2", ")", ";", "// the overlap volume", "double", "overlap", "=", "1.", ";", "double", "vol1", "=", "1.", ";", "double", "vol2", "=", "1.", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "dim", ";", "i", "++", ")", "{", "final", "double", "box1min", "=", "box1", ".", "getMin", "(", "i", ")", ";", "final", "double", "box1max", "=", "box1", ".", "getMax", "(", "i", ")", ";", "final", "double", "box2min", "=", "box2", ".", "getMin", "(", "i", ")", ";", "final", "double", "box2max", "=", "box2", ".", "getMax", "(", "i", ")", ";", "final", "double", "omax", "=", "Math", ".", "min", "(", "box1max", ",", "box2max", ")", ";", "final", "double", "omin", "=", "Math", ".", "max", "(", "box1min", ",", "box2min", ")", ";", "// if omax <= omin in any dimension, the overlap box has a volume of zero", "if", "(", "omax", "<=", "omin", ")", "{", "return", "0.", ";", "}", "overlap", "*=", "omax", "-", "omin", ";", "vol1", "*=", "box1max", "-", "box1min", ";", "vol2", "*=", "box2max", "-", "box2min", ";", "}", "return", "overlap", "/", "(", "vol1", "+", "vol2", ")", ";", "}" ]
Computes the volume of the overlapping box between two SpatialComparables and return the relation between the volume of the overlapping box and the volume of both SpatialComparable. @param box1 the first SpatialComparable @param box2 the second SpatialComparable @return the overlap volume in relation to the singular volumes.
[ "Computes", "the", "volume", "of", "the", "overlapping", "box", "between", "two", "SpatialComparables", "and", "return", "the", "relation", "between", "the", "volume", "of", "the", "overlapping", "box", "and", "the", "volume", "of", "both", "SpatialComparable", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-api/src/main/java/de/lmu/ifi/dbs/elki/data/spatial/SpatialUtil.java#L337-L365
synchronoss/cpo-api
cpo-jdbc/src/main/java/org/synchronoss/cpo/jdbc/jta/JdbcCpoXaAdapter.java
JdbcCpoXaAdapter.deleteObjects
@Override public <T> long deleteObjects(String name, Collection<T> coll, Collection<CpoWhere> wheres, Collection<CpoOrderBy> orderBy, Collection<CpoNativeFunction> nativeExpressions) throws CpoException { """ Removes the Objects contained in the collection from the datasource. The assumption is that the object exists in the datasource. This method stores the objects contained in the collection in the datasource. The objects in the collection will be treated as one transaction, assuming the datasource supports transactions. <p> This means that if one of the objects fail being deleted in the datasource then the CpoAdapter should stop processing the remainder of the collection, and if supported, rollback all the objects deleted thus far. <p> <pre>Example: <code> <p> class SomeObject so = null; class CpoAdapter cpo = null; <p> try { cpo = new JdbcCpoAdapter(new JdbcDataSourceInfo(driver, url, user, password,1,1,false)); } catch (CpoException ce) { // Handle the error cpo = null; } <p> if (cpo!=null) { ArrayList al = new ArrayList(); for (int i=0; i<3; i++){ so = new SomeObject(); so.setId(1); so.setName("SomeName"); al.add(so); } <p> try{ cpo.deleteObjects("IdNameDelete",al); } catch (CpoException ce) { // Handle the error } } </code> </pre> @param name The String name of the DELETE Function Group that will be used to create the object in the datasource. null signifies that the default rules will be used. @param coll This is a collection of objects that have been defined within the metadata of the datasource. If the class is not defined an exception will be thrown. @param wheres A collection of CpoWhere beans that define the constraints that should be used when retrieving beans @param orderBy The CpoOrderBy bean that defines the order in which beans should be returned @param nativeExpressions Native expression that will be used to augment the expression stored in the meta data. This text will be embedded at run-time @return The number of objects deleted from the datasource @throws CpoException Thrown if there are errors accessing the datasource """ return getCurrentResource().deleteObjects( name, coll, wheres, orderBy, nativeExpressions); }
java
@Override public <T> long deleteObjects(String name, Collection<T> coll, Collection<CpoWhere> wheres, Collection<CpoOrderBy> orderBy, Collection<CpoNativeFunction> nativeExpressions) throws CpoException { return getCurrentResource().deleteObjects( name, coll, wheres, orderBy, nativeExpressions); }
[ "@", "Override", "public", "<", "T", ">", "long", "deleteObjects", "(", "String", "name", ",", "Collection", "<", "T", ">", "coll", ",", "Collection", "<", "CpoWhere", ">", "wheres", ",", "Collection", "<", "CpoOrderBy", ">", "orderBy", ",", "Collection", "<", "CpoNativeFunction", ">", "nativeExpressions", ")", "throws", "CpoException", "{", "return", "getCurrentResource", "(", ")", ".", "deleteObjects", "(", "name", ",", "coll", ",", "wheres", ",", "orderBy", ",", "nativeExpressions", ")", ";", "}" ]
Removes the Objects contained in the collection from the datasource. The assumption is that the object exists in the datasource. This method stores the objects contained in the collection in the datasource. The objects in the collection will be treated as one transaction, assuming the datasource supports transactions. <p> This means that if one of the objects fail being deleted in the datasource then the CpoAdapter should stop processing the remainder of the collection, and if supported, rollback all the objects deleted thus far. <p> <pre>Example: <code> <p> class SomeObject so = null; class CpoAdapter cpo = null; <p> try { cpo = new JdbcCpoAdapter(new JdbcDataSourceInfo(driver, url, user, password,1,1,false)); } catch (CpoException ce) { // Handle the error cpo = null; } <p> if (cpo!=null) { ArrayList al = new ArrayList(); for (int i=0; i<3; i++){ so = new SomeObject(); so.setId(1); so.setName("SomeName"); al.add(so); } <p> try{ cpo.deleteObjects("IdNameDelete",al); } catch (CpoException ce) { // Handle the error } } </code> </pre> @param name The String name of the DELETE Function Group that will be used to create the object in the datasource. null signifies that the default rules will be used. @param coll This is a collection of objects that have been defined within the metadata of the datasource. If the class is not defined an exception will be thrown. @param wheres A collection of CpoWhere beans that define the constraints that should be used when retrieving beans @param orderBy The CpoOrderBy bean that defines the order in which beans should be returned @param nativeExpressions Native expression that will be used to augment the expression stored in the meta data. This text will be embedded at run-time @return The number of objects deleted from the datasource @throws CpoException Thrown if there are errors accessing the datasource
[ "Removes", "the", "Objects", "contained", "in", "the", "collection", "from", "the", "datasource", ".", "The", "assumption", "is", "that", "the", "object", "exists", "in", "the", "datasource", ".", "This", "method", "stores", "the", "objects", "contained", "in", "the", "collection", "in", "the", "datasource", ".", "The", "objects", "in", "the", "collection", "will", "be", "treated", "as", "one", "transaction", "assuming", "the", "datasource", "supports", "transactions", ".", "<p", ">", "This", "means", "that", "if", "one", "of", "the", "objects", "fail", "being", "deleted", "in", "the", "datasource", "then", "the", "CpoAdapter", "should", "stop", "processing", "the", "remainder", "of", "the", "collection", "and", "if", "supported", "rollback", "all", "the", "objects", "deleted", "thus", "far", ".", "<p", ">", "<pre", ">", "Example", ":", "<code", ">", "<p", ">", "class", "SomeObject", "so", "=", "null", ";", "class", "CpoAdapter", "cpo", "=", "null", ";", "<p", ">", "try", "{", "cpo", "=", "new", "JdbcCpoAdapter", "(", "new", "JdbcDataSourceInfo", "(", "driver", "url", "user", "password", "1", "1", "false", "))", ";", "}", "catch", "(", "CpoException", "ce", ")", "{", "//", "Handle", "the", "error", "cpo", "=", "null", ";", "}", "<p", ">", "if", "(", "cpo!", "=", "null", ")", "{", "ArrayList", "al", "=", "new", "ArrayList", "()", ";", "for", "(", "int", "i", "=", "0", ";", "i<3", ";", "i", "++", ")", "{", "so", "=", "new", "SomeObject", "()", ";", "so", ".", "setId", "(", "1", ")", ";", "so", ".", "setName", "(", "SomeName", ")", ";", "al", ".", "add", "(", "so", ")", ";", "}", "<p", ">", "try", "{", "cpo", ".", "deleteObjects", "(", "IdNameDelete", "al", ")", ";", "}", "catch", "(", "CpoException", "ce", ")", "{", "//", "Handle", "the", "error", "}", "}", "<", "/", "code", ">", "<", "/", "pre", ">" ]
train
https://github.com/synchronoss/cpo-api/blob/dc745aca3b3206abf80b85d9689b0132f5baa694/cpo-jdbc/src/main/java/org/synchronoss/cpo/jdbc/jta/JdbcCpoXaAdapter.java#L686-L689
oehf/ipf-oht-atna
auditor/src/main/java/org/openhealthtools/ihe/atna/auditor/events/ihe/GenericIHEAuditEventMessage.java
GenericIHEAuditEventMessage.addSourceActiveParticipant
public void addSourceActiveParticipant(String userId, String altUserId, String userName, String networkId, boolean isRequestor) { """ Adds an Active Participant block representing the source participant @param userId The Active Participant's User ID @param altUserId The Active Participant's Alternate UserID @param userName The Active Participant's UserName @param networkId The Active Participant's Network Access Point ID @param isRequestor Whether the participant represents the requestor """ addActiveParticipant( userId, altUserId, userName, isRequestor, Collections.singletonList(new DICOMActiveParticipantRoleIdCodes.Source()), networkId); }
java
public void addSourceActiveParticipant(String userId, String altUserId, String userName, String networkId, boolean isRequestor) { addActiveParticipant( userId, altUserId, userName, isRequestor, Collections.singletonList(new DICOMActiveParticipantRoleIdCodes.Source()), networkId); }
[ "public", "void", "addSourceActiveParticipant", "(", "String", "userId", ",", "String", "altUserId", ",", "String", "userName", ",", "String", "networkId", ",", "boolean", "isRequestor", ")", "{", "addActiveParticipant", "(", "userId", ",", "altUserId", ",", "userName", ",", "isRequestor", ",", "Collections", ".", "singletonList", "(", "new", "DICOMActiveParticipantRoleIdCodes", ".", "Source", "(", ")", ")", ",", "networkId", ")", ";", "}" ]
Adds an Active Participant block representing the source participant @param userId The Active Participant's User ID @param altUserId The Active Participant's Alternate UserID @param userName The Active Participant's UserName @param networkId The Active Participant's Network Access Point ID @param isRequestor Whether the participant represents the requestor
[ "Adds", "an", "Active", "Participant", "block", "representing", "the", "source", "participant" ]
train
https://github.com/oehf/ipf-oht-atna/blob/25ed1e926825169c94923a2c89a4618f60478ae8/auditor/src/main/java/org/openhealthtools/ihe/atna/auditor/events/ihe/GenericIHEAuditEventMessage.java#L96-L105
apache/incubator-atlas
webapp/src/main/java/org/apache/atlas/web/listeners/LoginProcessor.java
LoginProcessor.getServerPrincipal
private String getServerPrincipal(String principal, String host) throws IOException { """ Return a server (service) principal. The token "_HOST" in the principal will be replaced with the local host name (e.g. dgi/_HOST will be changed to dgi/localHostName) @param principal the input principal containing an option "_HOST" token @return the service principal. @throws IOException """ return SecurityUtil.getServerPrincipal(principal, host); }
java
private String getServerPrincipal(String principal, String host) throws IOException { return SecurityUtil.getServerPrincipal(principal, host); }
[ "private", "String", "getServerPrincipal", "(", "String", "principal", ",", "String", "host", ")", "throws", "IOException", "{", "return", "SecurityUtil", ".", "getServerPrincipal", "(", "principal", ",", "host", ")", ";", "}" ]
Return a server (service) principal. The token "_HOST" in the principal will be replaced with the local host name (e.g. dgi/_HOST will be changed to dgi/localHostName) @param principal the input principal containing an option "_HOST" token @return the service principal. @throws IOException
[ "Return", "a", "server", "(", "service", ")", "principal", ".", "The", "token", "_HOST", "in", "the", "principal", "will", "be", "replaced", "with", "the", "local", "host", "name", "(", "e", ".", "g", ".", "dgi", "/", "_HOST", "will", "be", "changed", "to", "dgi", "/", "localHostName", ")" ]
train
https://github.com/apache/incubator-atlas/blob/e0d2cdc27c32742ebecd24db4cca62dc04dcdf4b/webapp/src/main/java/org/apache/atlas/web/listeners/LoginProcessor.java#L119-L121
asciidoctor/asciidoctorj
asciidoctorj-core/src/main/java/org/asciidoctor/jruby/extension/processorproxies/ProcessorProxyUtil.java
ProcessorProxyUtil.getExtensionBaseClass
public static RubyClass getExtensionBaseClass(Ruby rubyRuntime, String processorClassName) { """ For a simple Ruby class name like "Treeprocessor" it returns the associated RubyClass from Asciidoctor::Extensions, e.g. Asciidoctor::Extensions::Treeprocessor @param rubyRuntime @param processorClassName @return The Ruby class object for the given extension class name, e.g. Asciidoctor::Extensions::TreeProcessor """ RubyModule extensionsModule = getExtensionsModule(rubyRuntime); return extensionsModule.getClass(processorClassName); }
java
public static RubyClass getExtensionBaseClass(Ruby rubyRuntime, String processorClassName) { RubyModule extensionsModule = getExtensionsModule(rubyRuntime); return extensionsModule.getClass(processorClassName); }
[ "public", "static", "RubyClass", "getExtensionBaseClass", "(", "Ruby", "rubyRuntime", ",", "String", "processorClassName", ")", "{", "RubyModule", "extensionsModule", "=", "getExtensionsModule", "(", "rubyRuntime", ")", ";", "return", "extensionsModule", ".", "getClass", "(", "processorClassName", ")", ";", "}" ]
For a simple Ruby class name like "Treeprocessor" it returns the associated RubyClass from Asciidoctor::Extensions, e.g. Asciidoctor::Extensions::Treeprocessor @param rubyRuntime @param processorClassName @return The Ruby class object for the given extension class name, e.g. Asciidoctor::Extensions::TreeProcessor
[ "For", "a", "simple", "Ruby", "class", "name", "like", "Treeprocessor", "it", "returns", "the", "associated", "RubyClass", "from", "Asciidoctor", "::", "Extensions", "e", ".", "g", ".", "Asciidoctor", "::", "Extensions", "::", "Treeprocessor" ]
train
https://github.com/asciidoctor/asciidoctorj/blob/e348c9a12b54c33fea7b05d70224c007e2ee75a9/asciidoctorj-core/src/main/java/org/asciidoctor/jruby/extension/processorproxies/ProcessorProxyUtil.java#L23-L26
wmdietl/jsr308-langtools
src/share/classes/javax/tools/ToolProvider.java
ToolProvider.trace
static <T> T trace(Level level, Object reason) { """ /* Define the system property "sun.tools.ToolProvider" to enable debugging: java ... -Dsun.tools.ToolProvider ... """ // NOTE: do not make this method private as it affects stack traces try { if (System.getProperty(propertyName) != null) { StackTraceElement[] st = Thread.currentThread().getStackTrace(); String method = "???"; String cls = ToolProvider.class.getName(); if (st.length > 2) { StackTraceElement frame = st[2]; method = String.format((Locale)null, "%s(%s:%s)", frame.getMethodName(), frame.getFileName(), frame.getLineNumber()); cls = frame.getClassName(); } Logger logger = Logger.getLogger(loggerName); if (reason instanceof Throwable) { logger.logp(level, cls, method, reason.getClass().getName(), (Throwable)reason); } else { logger.logp(level, cls, method, String.valueOf(reason)); } } } catch (SecurityException ex) { System.err.format((Locale)null, "%s: %s; %s%n", ToolProvider.class.getName(), reason, ex.getLocalizedMessage()); } return null; }
java
static <T> T trace(Level level, Object reason) { // NOTE: do not make this method private as it affects stack traces try { if (System.getProperty(propertyName) != null) { StackTraceElement[] st = Thread.currentThread().getStackTrace(); String method = "???"; String cls = ToolProvider.class.getName(); if (st.length > 2) { StackTraceElement frame = st[2]; method = String.format((Locale)null, "%s(%s:%s)", frame.getMethodName(), frame.getFileName(), frame.getLineNumber()); cls = frame.getClassName(); } Logger logger = Logger.getLogger(loggerName); if (reason instanceof Throwable) { logger.logp(level, cls, method, reason.getClass().getName(), (Throwable)reason); } else { logger.logp(level, cls, method, String.valueOf(reason)); } } } catch (SecurityException ex) { System.err.format((Locale)null, "%s: %s; %s%n", ToolProvider.class.getName(), reason, ex.getLocalizedMessage()); } return null; }
[ "static", "<", "T", ">", "T", "trace", "(", "Level", "level", ",", "Object", "reason", ")", "{", "// NOTE: do not make this method private as it affects stack traces", "try", "{", "if", "(", "System", ".", "getProperty", "(", "propertyName", ")", "!=", "null", ")", "{", "StackTraceElement", "[", "]", "st", "=", "Thread", ".", "currentThread", "(", ")", ".", "getStackTrace", "(", ")", ";", "String", "method", "=", "\"???\"", ";", "String", "cls", "=", "ToolProvider", ".", "class", ".", "getName", "(", ")", ";", "if", "(", "st", ".", "length", ">", "2", ")", "{", "StackTraceElement", "frame", "=", "st", "[", "2", "]", ";", "method", "=", "String", ".", "format", "(", "(", "Locale", ")", "null", ",", "\"%s(%s:%s)\"", ",", "frame", ".", "getMethodName", "(", ")", ",", "frame", ".", "getFileName", "(", ")", ",", "frame", ".", "getLineNumber", "(", ")", ")", ";", "cls", "=", "frame", ".", "getClassName", "(", ")", ";", "}", "Logger", "logger", "=", "Logger", ".", "getLogger", "(", "loggerName", ")", ";", "if", "(", "reason", "instanceof", "Throwable", ")", "{", "logger", ".", "logp", "(", "level", ",", "cls", ",", "method", ",", "reason", ".", "getClass", "(", ")", ".", "getName", "(", ")", ",", "(", "Throwable", ")", "reason", ")", ";", "}", "else", "{", "logger", ".", "logp", "(", "level", ",", "cls", ",", "method", ",", "String", ".", "valueOf", "(", "reason", ")", ")", ";", "}", "}", "}", "catch", "(", "SecurityException", "ex", ")", "{", "System", ".", "err", ".", "format", "(", "(", "Locale", ")", "null", ",", "\"%s: %s; %s%n\"", ",", "ToolProvider", ".", "class", ".", "getName", "(", ")", ",", "reason", ",", "ex", ".", "getLocalizedMessage", "(", ")", ")", ";", "}", "return", "null", ";", "}" ]
/* Define the system property "sun.tools.ToolProvider" to enable debugging: java ... -Dsun.tools.ToolProvider ...
[ "/", "*", "Define", "the", "system", "property", "sun", ".", "tools", ".", "ToolProvider", "to", "enable", "debugging", ":" ]
train
https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/javax/tools/ToolProvider.java#L60-L90
Azure/azure-sdk-for-java
network/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/NetworkWatchersInner.java
NetworkWatchersInner.getFlowLogStatus
public FlowLogInformationInner getFlowLogStatus(String resourceGroupName, String networkWatcherName, String targetResourceId) { """ Queries status of flow log on a specified resource. @param resourceGroupName The name of the network watcher resource group. @param networkWatcherName The name of the network watcher resource. @param targetResourceId The target resource where getting the flow logging status. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the FlowLogInformationInner object if successful. """ return getFlowLogStatusWithServiceResponseAsync(resourceGroupName, networkWatcherName, targetResourceId).toBlocking().last().body(); }
java
public FlowLogInformationInner getFlowLogStatus(String resourceGroupName, String networkWatcherName, String targetResourceId) { return getFlowLogStatusWithServiceResponseAsync(resourceGroupName, networkWatcherName, targetResourceId).toBlocking().last().body(); }
[ "public", "FlowLogInformationInner", "getFlowLogStatus", "(", "String", "resourceGroupName", ",", "String", "networkWatcherName", ",", "String", "targetResourceId", ")", "{", "return", "getFlowLogStatusWithServiceResponseAsync", "(", "resourceGroupName", ",", "networkWatcherName", ",", "targetResourceId", ")", ".", "toBlocking", "(", ")", ".", "last", "(", ")", ".", "body", "(", ")", ";", "}" ]
Queries status of flow log on a specified resource. @param resourceGroupName The name of the network watcher resource group. @param networkWatcherName The name of the network watcher resource. @param targetResourceId The target resource where getting the flow logging status. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the FlowLogInformationInner object if successful.
[ "Queries", "status", "of", "flow", "log", "on", "a", "specified", "resource", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/NetworkWatchersInner.java#L1970-L1972
jenkinsci/ghprb-plugin
src/main/java/org/jenkinsci/plugins/ghprb/upstream/GhprbUpstreamStatusListener.java
GhprbUpstreamStatusListener.onCompleted
@Override public void onCompleted(AbstractBuild<?, ?> build, TaskListener listener) { """ Sets the status to the build result when the job is done, and then calls the createCommitStatus method to send it to GitHub """ Map<String, String> envVars = returnEnvironmentVars(build, listener); if (envVars == null) { return; } try { returnGhprbSimpleStatus(envVars).onBuildComplete(build, listener, repo); } catch (GhprbCommitStatusException e) { e.printStackTrace(); } }
java
@Override public void onCompleted(AbstractBuild<?, ?> build, TaskListener listener) { Map<String, String> envVars = returnEnvironmentVars(build, listener); if (envVars == null) { return; } try { returnGhprbSimpleStatus(envVars).onBuildComplete(build, listener, repo); } catch (GhprbCommitStatusException e) { e.printStackTrace(); } }
[ "@", "Override", "public", "void", "onCompleted", "(", "AbstractBuild", "<", "?", ",", "?", ">", "build", ",", "TaskListener", "listener", ")", "{", "Map", "<", "String", ",", "String", ">", "envVars", "=", "returnEnvironmentVars", "(", "build", ",", "listener", ")", ";", "if", "(", "envVars", "==", "null", ")", "{", "return", ";", "}", "try", "{", "returnGhprbSimpleStatus", "(", "envVars", ")", ".", "onBuildComplete", "(", "build", ",", "listener", ",", "repo", ")", ";", "}", "catch", "(", "GhprbCommitStatusException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "}" ]
Sets the status to the build result when the job is done, and then calls the createCommitStatus method to send it to GitHub
[ "Sets", "the", "status", "to", "the", "build", "result", "when", "the", "job", "is", "done", "and", "then", "calls", "the", "createCommitStatus", "method", "to", "send", "it", "to", "GitHub" ]
train
https://github.com/jenkinsci/ghprb-plugin/blob/b972d3b94ebbe6d40542c2771407e297bff8430b/src/main/java/org/jenkinsci/plugins/ghprb/upstream/GhprbUpstreamStatusListener.java#L115-L127
facebookarchive/hadoop-20
src/contrib/highavailability/src/java/org/apache/hadoop/hdfs/server/namenode/AvatarNodeZkUtil.java
AvatarNodeZkUtil.checkZooKeeperBeforeFailover
static ZookeeperTxId checkZooKeeperBeforeFailover(Configuration startupConf, Configuration confg, boolean noverification) throws IOException { """ Verifies whether we are in a consistent state before we perform a failover @param startupConf the startup configuration @param confg the current configuration @param noverification whether or not to skip some zookeeper based verification @return the session id and last transaction id information from zookeeper @throws IOException """ AvatarZooKeeperClient zk = null; String fsname = startupConf.get(NameNode.DFS_NAMENODE_RPC_ADDRESS_KEY); int maxTries = startupConf.getInt("dfs.avatarnode.zk.retries", 3); Exception lastException = null; for (int i = 0; i < maxTries; i++) { try { zk = new AvatarZooKeeperClient(confg, null, false); LOG.info("Failover: Checking if the primary is empty"); String zkRegistry = zk.getPrimaryAvatarAddress(fsname, new Stat(), false, i > 0); if (zkRegistry != null) { throw new IOException( "Can't switch the AvatarNode to primary since " + "zookeeper record is not clean. Either use shutdownAvatar to kill " + "the current primary and clean the ZooKeeper entry, " + "or clear out the ZooKeeper entry if the primary is dead"); } if (noverification) { return null; } LOG.info("Failover: Obtaining last transaction id from ZK"); String address = startupConf.get(NameNode.DFS_NAMENODE_RPC_ADDRESS_KEY); long sessionId = zk.getPrimarySsId(address, i > 0); ZookeeperTxId zkTxId = zk.getPrimaryLastTxId(address, i > 0); if (sessionId != zkTxId.getSessionId()) { throw new IOException("Session Id in the ssid node : " + sessionId + " does not match the session Id in the txid node : " + zkTxId.getSessionId()); } return zkTxId; } catch (Exception e) { LOG.error("Got Exception reading primary node registration " + "from ZooKeeper. Will retry...", e); lastException = e; } finally { shutdownZkClient(zk); } } throw new IOException(lastException); }
java
static ZookeeperTxId checkZooKeeperBeforeFailover(Configuration startupConf, Configuration confg, boolean noverification) throws IOException { AvatarZooKeeperClient zk = null; String fsname = startupConf.get(NameNode.DFS_NAMENODE_RPC_ADDRESS_KEY); int maxTries = startupConf.getInt("dfs.avatarnode.zk.retries", 3); Exception lastException = null; for (int i = 0; i < maxTries; i++) { try { zk = new AvatarZooKeeperClient(confg, null, false); LOG.info("Failover: Checking if the primary is empty"); String zkRegistry = zk.getPrimaryAvatarAddress(fsname, new Stat(), false, i > 0); if (zkRegistry != null) { throw new IOException( "Can't switch the AvatarNode to primary since " + "zookeeper record is not clean. Either use shutdownAvatar to kill " + "the current primary and clean the ZooKeeper entry, " + "or clear out the ZooKeeper entry if the primary is dead"); } if (noverification) { return null; } LOG.info("Failover: Obtaining last transaction id from ZK"); String address = startupConf.get(NameNode.DFS_NAMENODE_RPC_ADDRESS_KEY); long sessionId = zk.getPrimarySsId(address, i > 0); ZookeeperTxId zkTxId = zk.getPrimaryLastTxId(address, i > 0); if (sessionId != zkTxId.getSessionId()) { throw new IOException("Session Id in the ssid node : " + sessionId + " does not match the session Id in the txid node : " + zkTxId.getSessionId()); } return zkTxId; } catch (Exception e) { LOG.error("Got Exception reading primary node registration " + "from ZooKeeper. Will retry...", e); lastException = e; } finally { shutdownZkClient(zk); } } throw new IOException(lastException); }
[ "static", "ZookeeperTxId", "checkZooKeeperBeforeFailover", "(", "Configuration", "startupConf", ",", "Configuration", "confg", ",", "boolean", "noverification", ")", "throws", "IOException", "{", "AvatarZooKeeperClient", "zk", "=", "null", ";", "String", "fsname", "=", "startupConf", ".", "get", "(", "NameNode", ".", "DFS_NAMENODE_RPC_ADDRESS_KEY", ")", ";", "int", "maxTries", "=", "startupConf", ".", "getInt", "(", "\"dfs.avatarnode.zk.retries\"", ",", "3", ")", ";", "Exception", "lastException", "=", "null", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "maxTries", ";", "i", "++", ")", "{", "try", "{", "zk", "=", "new", "AvatarZooKeeperClient", "(", "confg", ",", "null", ",", "false", ")", ";", "LOG", ".", "info", "(", "\"Failover: Checking if the primary is empty\"", ")", ";", "String", "zkRegistry", "=", "zk", ".", "getPrimaryAvatarAddress", "(", "fsname", ",", "new", "Stat", "(", ")", ",", "false", ",", "i", ">", "0", ")", ";", "if", "(", "zkRegistry", "!=", "null", ")", "{", "throw", "new", "IOException", "(", "\"Can't switch the AvatarNode to primary since \"", "+", "\"zookeeper record is not clean. Either use shutdownAvatar to kill \"", "+", "\"the current primary and clean the ZooKeeper entry, \"", "+", "\"or clear out the ZooKeeper entry if the primary is dead\"", ")", ";", "}", "if", "(", "noverification", ")", "{", "return", "null", ";", "}", "LOG", ".", "info", "(", "\"Failover: Obtaining last transaction id from ZK\"", ")", ";", "String", "address", "=", "startupConf", ".", "get", "(", "NameNode", ".", "DFS_NAMENODE_RPC_ADDRESS_KEY", ")", ";", "long", "sessionId", "=", "zk", ".", "getPrimarySsId", "(", "address", ",", "i", ">", "0", ")", ";", "ZookeeperTxId", "zkTxId", "=", "zk", ".", "getPrimaryLastTxId", "(", "address", ",", "i", ">", "0", ")", ";", "if", "(", "sessionId", "!=", "zkTxId", ".", "getSessionId", "(", ")", ")", "{", "throw", "new", "IOException", "(", "\"Session Id in the ssid node : \"", "+", "sessionId", "+", "\" does not match the session Id in the txid node : \"", "+", "zkTxId", ".", "getSessionId", "(", ")", ")", ";", "}", "return", "zkTxId", ";", "}", "catch", "(", "Exception", "e", ")", "{", "LOG", ".", "error", "(", "\"Got Exception reading primary node registration \"", "+", "\"from ZooKeeper. Will retry...\"", ",", "e", ")", ";", "lastException", "=", "e", ";", "}", "finally", "{", "shutdownZkClient", "(", "zk", ")", ";", "}", "}", "throw", "new", "IOException", "(", "lastException", ")", ";", "}" ]
Verifies whether we are in a consistent state before we perform a failover @param startupConf the startup configuration @param confg the current configuration @param noverification whether or not to skip some zookeeper based verification @return the session id and last transaction id information from zookeeper @throws IOException
[ "Verifies", "whether", "we", "are", "in", "a", "consistent", "state", "before", "we", "perform", "a", "failover" ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/highavailability/src/java/org/apache/hadoop/hdfs/server/namenode/AvatarNodeZkUtil.java#L54-L98
wildfly/wildfly-core
deployment-scanner/src/main/java/org/jboss/as/server/deployment/scanner/ZipCompletionScanner.java
ZipCompletionScanner.isCompleteZip
public static boolean isCompleteZip(File file) throws IOException, NonScannableZipException { """ Scans the given file looking for a complete zip file format end of central directory record. @param file the file @return true if a complete end of central directory record could be found @throws IOException """ FileChannel channel = null; try { channel = new FileInputStream(file).getChannel(); long size = channel.size(); if (size < ENDLEN) { // Obvious case return false; } else if (validateEndRecord(file, channel, size - ENDLEN)) { // typical case where file is complete and end record has no comment return true; } // Either file is incomplete or the end of central directory record includes an arbitrary length comment // So, we have to scan backwards looking for an end of central directory record return scanForEndSig(file, channel); } finally { safeClose(channel); } }
java
public static boolean isCompleteZip(File file) throws IOException, NonScannableZipException { FileChannel channel = null; try { channel = new FileInputStream(file).getChannel(); long size = channel.size(); if (size < ENDLEN) { // Obvious case return false; } else if (validateEndRecord(file, channel, size - ENDLEN)) { // typical case where file is complete and end record has no comment return true; } // Either file is incomplete or the end of central directory record includes an arbitrary length comment // So, we have to scan backwards looking for an end of central directory record return scanForEndSig(file, channel); } finally { safeClose(channel); } }
[ "public", "static", "boolean", "isCompleteZip", "(", "File", "file", ")", "throws", "IOException", ",", "NonScannableZipException", "{", "FileChannel", "channel", "=", "null", ";", "try", "{", "channel", "=", "new", "FileInputStream", "(", "file", ")", ".", "getChannel", "(", ")", ";", "long", "size", "=", "channel", ".", "size", "(", ")", ";", "if", "(", "size", "<", "ENDLEN", ")", "{", "// Obvious case", "return", "false", ";", "}", "else", "if", "(", "validateEndRecord", "(", "file", ",", "channel", ",", "size", "-", "ENDLEN", ")", ")", "{", "// typical case where file is complete and end record has no comment", "return", "true", ";", "}", "// Either file is incomplete or the end of central directory record includes an arbitrary length comment", "// So, we have to scan backwards looking for an end of central directory record", "return", "scanForEndSig", "(", "file", ",", "channel", ")", ";", "}", "finally", "{", "safeClose", "(", "channel", ")", ";", "}", "}" ]
Scans the given file looking for a complete zip file format end of central directory record. @param file the file @return true if a complete end of central directory record could be found @throws IOException
[ "Scans", "the", "given", "file", "looking", "for", "a", "complete", "zip", "file", "format", "end", "of", "central", "directory", "record", "." ]
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/deployment-scanner/src/main/java/org/jboss/as/server/deployment/scanner/ZipCompletionScanner.java#L107-L128
box/box-android-sdk
box-content-sdk/src/main/java/com/box/androidsdk/content/BoxApiFile.java
BoxApiFile.getUploadRequest
public BoxRequestsFile.UploadFile getUploadRequest(InputStream fileInputStream, String fileName, String destinationFolderId) { """ Gets a request that uploads a file from an input stream @param fileInputStream input stream of the file @param fileName name of the new file @param destinationFolderId id of the parent folder for the new file @return request to upload a file from an input stream """ BoxRequestsFile.UploadFile request = new BoxRequestsFile.UploadFile(fileInputStream, fileName, destinationFolderId, getFileUploadUrl(), mSession); return request; }
java
public BoxRequestsFile.UploadFile getUploadRequest(InputStream fileInputStream, String fileName, String destinationFolderId){ BoxRequestsFile.UploadFile request = new BoxRequestsFile.UploadFile(fileInputStream, fileName, destinationFolderId, getFileUploadUrl(), mSession); return request; }
[ "public", "BoxRequestsFile", ".", "UploadFile", "getUploadRequest", "(", "InputStream", "fileInputStream", ",", "String", "fileName", ",", "String", "destinationFolderId", ")", "{", "BoxRequestsFile", ".", "UploadFile", "request", "=", "new", "BoxRequestsFile", ".", "UploadFile", "(", "fileInputStream", ",", "fileName", ",", "destinationFolderId", ",", "getFileUploadUrl", "(", ")", ",", "mSession", ")", ";", "return", "request", ";", "}" ]
Gets a request that uploads a file from an input stream @param fileInputStream input stream of the file @param fileName name of the new file @param destinationFolderId id of the parent folder for the new file @return request to upload a file from an input stream
[ "Gets", "a", "request", "that", "uploads", "a", "file", "from", "an", "input", "stream" ]
train
https://github.com/box/box-android-sdk/blob/a621ad5ddebf23067fec27529130d72718fc0e88/box-content-sdk/src/main/java/com/box/androidsdk/content/BoxApiFile.java#L313-L316
alkacon/opencms-core
src/org/opencms/module/CmsModuleImportExportHandler.java
CmsModuleImportExportHandler.reportBeginImport
public static void reportBeginImport(I_CmsReport report, String modulePackageName) { """ Writes the messages for starting an import to the given report.<p> @param report the report to write to @param modulePackageName the module name """ report.print(Messages.get().container(Messages.RPT_IMPORT_MODULE_BEGIN_0), I_CmsReport.FORMAT_HEADLINE); if (report instanceof CmsHtmlReport) { report.print( org.opencms.report.Messages.get().container( org.opencms.report.Messages.RPT_ARGUMENT_1, "<i>" + modulePackageName + "</i>")); } else { report.print( org.opencms.report.Messages.get().container( org.opencms.report.Messages.RPT_ARGUMENT_1, modulePackageName)); } report.println(org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_DOTS_0)); }
java
public static void reportBeginImport(I_CmsReport report, String modulePackageName) { report.print(Messages.get().container(Messages.RPT_IMPORT_MODULE_BEGIN_0), I_CmsReport.FORMAT_HEADLINE); if (report instanceof CmsHtmlReport) { report.print( org.opencms.report.Messages.get().container( org.opencms.report.Messages.RPT_ARGUMENT_1, "<i>" + modulePackageName + "</i>")); } else { report.print( org.opencms.report.Messages.get().container( org.opencms.report.Messages.RPT_ARGUMENT_1, modulePackageName)); } report.println(org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_DOTS_0)); }
[ "public", "static", "void", "reportBeginImport", "(", "I_CmsReport", "report", ",", "String", "modulePackageName", ")", "{", "report", ".", "print", "(", "Messages", ".", "get", "(", ")", ".", "container", "(", "Messages", ".", "RPT_IMPORT_MODULE_BEGIN_0", ")", ",", "I_CmsReport", ".", "FORMAT_HEADLINE", ")", ";", "if", "(", "report", "instanceof", "CmsHtmlReport", ")", "{", "report", ".", "print", "(", "org", ".", "opencms", ".", "report", ".", "Messages", ".", "get", "(", ")", ".", "container", "(", "org", ".", "opencms", ".", "report", ".", "Messages", ".", "RPT_ARGUMENT_1", ",", "\"<i>\"", "+", "modulePackageName", "+", "\"</i>\"", ")", ")", ";", "}", "else", "{", "report", ".", "print", "(", "org", ".", "opencms", ".", "report", ".", "Messages", ".", "get", "(", ")", ".", "container", "(", "org", ".", "opencms", ".", "report", ".", "Messages", ".", "RPT_ARGUMENT_1", ",", "modulePackageName", ")", ")", ";", "}", "report", ".", "println", "(", "org", ".", "opencms", ".", "report", ".", "Messages", ".", "get", "(", ")", ".", "container", "(", "org", ".", "opencms", ".", "report", ".", "Messages", ".", "RPT_DOTS_0", ")", ")", ";", "}" ]
Writes the messages for starting an import to the given report.<p> @param report the report to write to @param modulePackageName the module name
[ "Writes", "the", "messages", "for", "starting", "an", "import", "to", "the", "given", "report", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/module/CmsModuleImportExportHandler.java#L334-L349
dropwizard/metrics
metrics-core/src/main/java/com/codahale/metrics/MetricRegistry.java
MetricRegistry.registerAll
public void registerAll(String prefix, MetricSet metrics) throws IllegalArgumentException { """ Given a metric set, registers them with the given prefix prepended to their names. @param prefix a name prefix @param metrics a set of metrics @throws IllegalArgumentException if any of the names are already registered """ for (Map.Entry<String, Metric> entry : metrics.getMetrics().entrySet()) { if (entry.getValue() instanceof MetricSet) { registerAll(name(prefix, entry.getKey()), (MetricSet) entry.getValue()); } else { register(name(prefix, entry.getKey()), entry.getValue()); } } }
java
public void registerAll(String prefix, MetricSet metrics) throws IllegalArgumentException { for (Map.Entry<String, Metric> entry : metrics.getMetrics().entrySet()) { if (entry.getValue() instanceof MetricSet) { registerAll(name(prefix, entry.getKey()), (MetricSet) entry.getValue()); } else { register(name(prefix, entry.getKey()), entry.getValue()); } } }
[ "public", "void", "registerAll", "(", "String", "prefix", ",", "MetricSet", "metrics", ")", "throws", "IllegalArgumentException", "{", "for", "(", "Map", ".", "Entry", "<", "String", ",", "Metric", ">", "entry", ":", "metrics", ".", "getMetrics", "(", ")", ".", "entrySet", "(", ")", ")", "{", "if", "(", "entry", ".", "getValue", "(", ")", "instanceof", "MetricSet", ")", "{", "registerAll", "(", "name", "(", "prefix", ",", "entry", ".", "getKey", "(", ")", ")", ",", "(", "MetricSet", ")", "entry", ".", "getValue", "(", ")", ")", ";", "}", "else", "{", "register", "(", "name", "(", "prefix", ",", "entry", ".", "getKey", "(", ")", ")", ",", "entry", ".", "getValue", "(", ")", ")", ";", "}", "}", "}" ]
Given a metric set, registers them with the given prefix prepended to their names. @param prefix a name prefix @param metrics a set of metrics @throws IllegalArgumentException if any of the names are already registered
[ "Given", "a", "metric", "set", "registers", "them", "with", "the", "given", "prefix", "prepended", "to", "their", "names", "." ]
train
https://github.com/dropwizard/metrics/blob/3c6105a0b9b4416c59e16b6b841b123052d6f57d/metrics-core/src/main/java/com/codahale/metrics/MetricRegistry.java#L511-L519
bazaarvoice/jolt
complete/src/main/java/com/bazaarvoice/jolt/ChainrFactory.java
ChainrFactory.fromClassPath
public static Chainr fromClassPath( String chainrSpecClassPath, ChainrInstantiator chainrInstantiator ) { """ Builds a Chainr instance using the spec described in the data via the class path that is passed in. @param chainrSpecClassPath The class path that points to the chainr spec. @param chainrInstantiator the ChainrInstantiator to use to initialze the Chainr instance @return a Chainr instance """ Object chainrSpec = JsonUtils.classpathToObject( chainrSpecClassPath ); return getChainr( chainrInstantiator, chainrSpec ); }
java
public static Chainr fromClassPath( String chainrSpecClassPath, ChainrInstantiator chainrInstantiator ) { Object chainrSpec = JsonUtils.classpathToObject( chainrSpecClassPath ); return getChainr( chainrInstantiator, chainrSpec ); }
[ "public", "static", "Chainr", "fromClassPath", "(", "String", "chainrSpecClassPath", ",", "ChainrInstantiator", "chainrInstantiator", ")", "{", "Object", "chainrSpec", "=", "JsonUtils", ".", "classpathToObject", "(", "chainrSpecClassPath", ")", ";", "return", "getChainr", "(", "chainrInstantiator", ",", "chainrSpec", ")", ";", "}" ]
Builds a Chainr instance using the spec described in the data via the class path that is passed in. @param chainrSpecClassPath The class path that points to the chainr spec. @param chainrInstantiator the ChainrInstantiator to use to initialze the Chainr instance @return a Chainr instance
[ "Builds", "a", "Chainr", "instance", "using", "the", "spec", "described", "in", "the", "data", "via", "the", "class", "path", "that", "is", "passed", "in", "." ]
train
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/complete/src/main/java/com/bazaarvoice/jolt/ChainrFactory.java#L45-L48
rey5137/material
material/src/main/java/com/rey/material/widget/EditText.java
EditText.setCompoundDrawablesRelative
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) public void setCompoundDrawablesRelative (Drawable start, Drawable top, Drawable end, Drawable bottom) { """ Sets the Drawables (if any) to appear to the start of, above, to the end of, and below the text. Use {@code null} if you do not want a Drawable there. The Drawables must already have had {@link Drawable#setBounds} called. <p> Calling this method will overwrite any Drawables previously set using {@link #setCompoundDrawables} or related methods. @attr ref android.R.styleable#TextView_drawableStart @attr ref android.R.styleable#TextView_drawableTop @attr ref android.R.styleable#TextView_drawableEnd @attr ref android.R.styleable#TextView_drawableBottom """ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) mInputView.setCompoundDrawablesRelative(start, top, end, bottom); else mInputView.setCompoundDrawables(start, top, end, bottom); }
java
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) public void setCompoundDrawablesRelative (Drawable start, Drawable top, Drawable end, Drawable bottom){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) mInputView.setCompoundDrawablesRelative(start, top, end, bottom); else mInputView.setCompoundDrawables(start, top, end, bottom); }
[ "@", "TargetApi", "(", "Build", ".", "VERSION_CODES", ".", "JELLY_BEAN_MR1", ")", "public", "void", "setCompoundDrawablesRelative", "(", "Drawable", "start", ",", "Drawable", "top", ",", "Drawable", "end", ",", "Drawable", "bottom", ")", "{", "if", "(", "Build", ".", "VERSION", ".", "SDK_INT", ">=", "Build", ".", "VERSION_CODES", ".", "JELLY_BEAN_MR1", ")", "mInputView", ".", "setCompoundDrawablesRelative", "(", "start", ",", "top", ",", "end", ",", "bottom", ")", ";", "else", "mInputView", ".", "setCompoundDrawables", "(", "start", ",", "top", ",", "end", ",", "bottom", ")", ";", "}" ]
Sets the Drawables (if any) to appear to the start of, above, to the end of, and below the text. Use {@code null} if you do not want a Drawable there. The Drawables must already have had {@link Drawable#setBounds} called. <p> Calling this method will overwrite any Drawables previously set using {@link #setCompoundDrawables} or related methods. @attr ref android.R.styleable#TextView_drawableStart @attr ref android.R.styleable#TextView_drawableTop @attr ref android.R.styleable#TextView_drawableEnd @attr ref android.R.styleable#TextView_drawableBottom
[ "Sets", "the", "Drawables", "(", "if", "any", ")", "to", "appear", "to", "the", "start", "of", "above", "to", "the", "end", "of", "and", "below", "the", "text", ".", "Use", "{", "@code", "null", "}", "if", "you", "do", "not", "want", "a", "Drawable", "there", ".", "The", "Drawables", "must", "already", "have", "had", "{", "@link", "Drawable#setBounds", "}", "called", ".", "<p", ">", "Calling", "this", "method", "will", "overwrite", "any", "Drawables", "previously", "set", "using", "{", "@link", "#setCompoundDrawables", "}", "or", "related", "methods", "." ]
train
https://github.com/rey5137/material/blob/1bbcac2686a0023ef7720d3fe455bb116d115af8/material/src/main/java/com/rey/material/widget/EditText.java#L2718-L2724
uber/AutoDispose
static-analysis/autodispose-error-prone/src/main/java/com/uber/autodispose/errorprone/AbstractReturnValueIgnored.java
AbstractReturnValueIgnored.describe
private Description describe(MethodInvocationTree methodInvocationTree, VisitorState state) { """ Fixes the error by assigning the result of the call to the receiver reference, or deleting the method call. """ // Find the root of the field access chain, i.e. a.intern().trim() ==> a. ExpressionTree identifierExpr = ASTHelpers.getRootAssignable(methodInvocationTree); String identifierStr = null; Type identifierType = null; if (identifierExpr != null) { identifierStr = state.getSourceForNode(identifierExpr); if (identifierExpr instanceof JCIdent) { identifierType = ((JCIdent) identifierExpr).sym.type; } else if (identifierExpr instanceof JCFieldAccess) { identifierType = ((JCFieldAccess) identifierExpr).sym.type; } else { throw new IllegalStateException("Expected a JCIdent or a JCFieldAccess"); } } Type returnType = getReturnType(((JCMethodInvocation) methodInvocationTree).getMethodSelect()); Fix fix; if (identifierStr != null && !"this".equals(identifierStr) && returnType != null && state.getTypes().isAssignable(returnType, identifierType)) { // Fix by assigning the assigning the result of the call to the root receiver reference. fix = SuggestedFix.prefixWith(methodInvocationTree, identifierStr + " = "); } else { // Unclear what the programmer intended. Delete since we don't know what else to do. Tree parent = state.getPath().getParentPath().getLeaf(); fix = SuggestedFix.delete(parent); } return describeMatch(methodInvocationTree, fix); }
java
private Description describe(MethodInvocationTree methodInvocationTree, VisitorState state) { // Find the root of the field access chain, i.e. a.intern().trim() ==> a. ExpressionTree identifierExpr = ASTHelpers.getRootAssignable(methodInvocationTree); String identifierStr = null; Type identifierType = null; if (identifierExpr != null) { identifierStr = state.getSourceForNode(identifierExpr); if (identifierExpr instanceof JCIdent) { identifierType = ((JCIdent) identifierExpr).sym.type; } else if (identifierExpr instanceof JCFieldAccess) { identifierType = ((JCFieldAccess) identifierExpr).sym.type; } else { throw new IllegalStateException("Expected a JCIdent or a JCFieldAccess"); } } Type returnType = getReturnType(((JCMethodInvocation) methodInvocationTree).getMethodSelect()); Fix fix; if (identifierStr != null && !"this".equals(identifierStr) && returnType != null && state.getTypes().isAssignable(returnType, identifierType)) { // Fix by assigning the assigning the result of the call to the root receiver reference. fix = SuggestedFix.prefixWith(methodInvocationTree, identifierStr + " = "); } else { // Unclear what the programmer intended. Delete since we don't know what else to do. Tree parent = state.getPath().getParentPath().getLeaf(); fix = SuggestedFix.delete(parent); } return describeMatch(methodInvocationTree, fix); }
[ "private", "Description", "describe", "(", "MethodInvocationTree", "methodInvocationTree", ",", "VisitorState", "state", ")", "{", "// Find the root of the field access chain, i.e. a.intern().trim() ==> a.", "ExpressionTree", "identifierExpr", "=", "ASTHelpers", ".", "getRootAssignable", "(", "methodInvocationTree", ")", ";", "String", "identifierStr", "=", "null", ";", "Type", "identifierType", "=", "null", ";", "if", "(", "identifierExpr", "!=", "null", ")", "{", "identifierStr", "=", "state", ".", "getSourceForNode", "(", "identifierExpr", ")", ";", "if", "(", "identifierExpr", "instanceof", "JCIdent", ")", "{", "identifierType", "=", "(", "(", "JCIdent", ")", "identifierExpr", ")", ".", "sym", ".", "type", ";", "}", "else", "if", "(", "identifierExpr", "instanceof", "JCFieldAccess", ")", "{", "identifierType", "=", "(", "(", "JCFieldAccess", ")", "identifierExpr", ")", ".", "sym", ".", "type", ";", "}", "else", "{", "throw", "new", "IllegalStateException", "(", "\"Expected a JCIdent or a JCFieldAccess\"", ")", ";", "}", "}", "Type", "returnType", "=", "getReturnType", "(", "(", "(", "JCMethodInvocation", ")", "methodInvocationTree", ")", ".", "getMethodSelect", "(", ")", ")", ";", "Fix", "fix", ";", "if", "(", "identifierStr", "!=", "null", "&&", "!", "\"this\"", ".", "equals", "(", "identifierStr", ")", "&&", "returnType", "!=", "null", "&&", "state", ".", "getTypes", "(", ")", ".", "isAssignable", "(", "returnType", ",", "identifierType", ")", ")", "{", "// Fix by assigning the assigning the result of the call to the root receiver reference.", "fix", "=", "SuggestedFix", ".", "prefixWith", "(", "methodInvocationTree", ",", "identifierStr", "+", "\" = \"", ")", ";", "}", "else", "{", "// Unclear what the programmer intended. Delete since we don't know what else to do.", "Tree", "parent", "=", "state", ".", "getPath", "(", ")", ".", "getParentPath", "(", ")", ".", "getLeaf", "(", ")", ";", "fix", "=", "SuggestedFix", ".", "delete", "(", "parent", ")", ";", "}", "return", "describeMatch", "(", "methodInvocationTree", ",", "fix", ")", ";", "}" ]
Fixes the error by assigning the result of the call to the receiver reference, or deleting the method call.
[ "Fixes", "the", "error", "by", "assigning", "the", "result", "of", "the", "call", "to", "the", "receiver", "reference", "or", "deleting", "the", "method", "call", "." ]
train
https://github.com/uber/AutoDispose/blob/1115b0274f7960354289bb3ae7ba75b0c5a47457/static-analysis/autodispose-error-prone/src/main/java/com/uber/autodispose/errorprone/AbstractReturnValueIgnored.java#L262-L293
JodaOrg/joda-time
src/main/java/org/joda/time/Period.java
Period.withFieldAdded
public Period withFieldAdded(DurationFieldType field, int value) { """ Creates a new Period instance with the valueToAdd added to the specified field. <p> This period instance is immutable and unaffected by this method call. @param field the field to set, not null @param value the value to add @return the new period instance @throws IllegalArgumentException if the field type is null or unsupported """ if (field == null) { throw new IllegalArgumentException("Field must not be null"); } if (value == 0) { return this; } int[] newValues = getValues(); // cloned super.addFieldInto(newValues, field, value); return new Period(newValues, getPeriodType()); }
java
public Period withFieldAdded(DurationFieldType field, int value) { if (field == null) { throw new IllegalArgumentException("Field must not be null"); } if (value == 0) { return this; } int[] newValues = getValues(); // cloned super.addFieldInto(newValues, field, value); return new Period(newValues, getPeriodType()); }
[ "public", "Period", "withFieldAdded", "(", "DurationFieldType", "field", ",", "int", "value", ")", "{", "if", "(", "field", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Field must not be null\"", ")", ";", "}", "if", "(", "value", "==", "0", ")", "{", "return", "this", ";", "}", "int", "[", "]", "newValues", "=", "getValues", "(", ")", ";", "// cloned", "super", ".", "addFieldInto", "(", "newValues", ",", "field", ",", "value", ")", ";", "return", "new", "Period", "(", "newValues", ",", "getPeriodType", "(", ")", ")", ";", "}" ]
Creates a new Period instance with the valueToAdd added to the specified field. <p> This period instance is immutable and unaffected by this method call. @param field the field to set, not null @param value the value to add @return the new period instance @throws IllegalArgumentException if the field type is null or unsupported
[ "Creates", "a", "new", "Period", "instance", "with", "the", "valueToAdd", "added", "to", "the", "specified", "field", ".", "<p", ">", "This", "period", "instance", "is", "immutable", "and", "unaffected", "by", "this", "method", "call", "." ]
train
https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/Period.java#L892-L902
sarl/sarl
main/coreplugins/io.sarl.eclipse/src/io/sarl/eclipse/SARLEclipsePlugin.java
SARLEclipsePlugin.createStatus
public IStatus createStatus(int severity, int code, String message) { """ Create a status. @param severity the severity level, see {@link IStatus}. @param code the code of the error. @param message the message associated to the status. @return the status. """ return createStatus(severity, code, message, null); }
java
public IStatus createStatus(int severity, int code, String message) { return createStatus(severity, code, message, null); }
[ "public", "IStatus", "createStatus", "(", "int", "severity", ",", "int", "code", ",", "String", "message", ")", "{", "return", "createStatus", "(", "severity", ",", "code", ",", "message", ",", "null", ")", ";", "}" ]
Create a status. @param severity the severity level, see {@link IStatus}. @param code the code of the error. @param message the message associated to the status. @return the status.
[ "Create", "a", "status", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.eclipse/src/io/sarl/eclipse/SARLEclipsePlugin.java#L229-L231
UrielCh/ovh-java-sdk
ovh-java-sdk-caascontainers/src/main/java/net/minidev/ovh/api/ApiOvhCaascontainers.java
ApiOvhCaascontainers.serviceName_frameworks_frameworkId_apps_GET
public OvhApplication serviceName_frameworks_frameworkId_apps_GET(String serviceName, String frameworkId) throws IOException { """ List apps in the framework REST: GET /caas/containers/{serviceName}/frameworks/{frameworkId}/apps @param frameworkId [required] framework id @param serviceName [required] service name API beta """ String qPath = "/caas/containers/{serviceName}/frameworks/{frameworkId}/apps"; StringBuilder sb = path(qPath, serviceName, frameworkId); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhApplication.class); }
java
public OvhApplication serviceName_frameworks_frameworkId_apps_GET(String serviceName, String frameworkId) throws IOException { String qPath = "/caas/containers/{serviceName}/frameworks/{frameworkId}/apps"; StringBuilder sb = path(qPath, serviceName, frameworkId); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhApplication.class); }
[ "public", "OvhApplication", "serviceName_frameworks_frameworkId_apps_GET", "(", "String", "serviceName", ",", "String", "frameworkId", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/caas/containers/{serviceName}/frameworks/{frameworkId}/apps\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ",", "frameworkId", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"GET\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhApplication", ".", "class", ")", ";", "}" ]
List apps in the framework REST: GET /caas/containers/{serviceName}/frameworks/{frameworkId}/apps @param frameworkId [required] framework id @param serviceName [required] service name API beta
[ "List", "apps", "in", "the", "framework" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-caascontainers/src/main/java/net/minidev/ovh/api/ApiOvhCaascontainers.java#L215-L220
ops4j/org.ops4j.pax.logging
pax-logging-service/src/main/java/org/apache/log4j/receivers/varia/LogFilePatternReceiver.java
LogFilePatternReceiver.buildMessage
private String buildMessage(String firstMessageLine, int exceptionLine) { """ Combine all message lines occuring in the additionalLines list, adding a newline character between each line <p> the event will already have a message - combine this message with the message lines in the additionalLines list (all entries prior to the exceptionLine index) @param firstMessageLine primary message line @param exceptionLine index of first exception line @return message """ if (additionalLines.size() == 0) { return firstMessageLine; } StringBuffer message = new StringBuffer(); if (firstMessageLine != null) { message.append(firstMessageLine); } int linesToProcess = (exceptionLine == -1?additionalLines.size(): exceptionLine); for (int i = 0; i < linesToProcess; i++) { message.append(newLine); message.append(additionalLines.get(i)); } return message.toString(); }
java
private String buildMessage(String firstMessageLine, int exceptionLine) { if (additionalLines.size() == 0) { return firstMessageLine; } StringBuffer message = new StringBuffer(); if (firstMessageLine != null) { message.append(firstMessageLine); } int linesToProcess = (exceptionLine == -1?additionalLines.size(): exceptionLine); for (int i = 0; i < linesToProcess; i++) { message.append(newLine); message.append(additionalLines.get(i)); } return message.toString(); }
[ "private", "String", "buildMessage", "(", "String", "firstMessageLine", ",", "int", "exceptionLine", ")", "{", "if", "(", "additionalLines", ".", "size", "(", ")", "==", "0", ")", "{", "return", "firstMessageLine", ";", "}", "StringBuffer", "message", "=", "new", "StringBuffer", "(", ")", ";", "if", "(", "firstMessageLine", "!=", "null", ")", "{", "message", ".", "append", "(", "firstMessageLine", ")", ";", "}", "int", "linesToProcess", "=", "(", "exceptionLine", "==", "-", "1", "?", "additionalLines", ".", "size", "(", ")", ":", "exceptionLine", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "linesToProcess", ";", "i", "++", ")", "{", "message", ".", "append", "(", "newLine", ")", ";", "message", ".", "append", "(", "additionalLines", ".", "get", "(", "i", ")", ")", ";", "}", "return", "message", ".", "toString", "(", ")", ";", "}" ]
Combine all message lines occuring in the additionalLines list, adding a newline character between each line <p> the event will already have a message - combine this message with the message lines in the additionalLines list (all entries prior to the exceptionLine index) @param firstMessageLine primary message line @param exceptionLine index of first exception line @return message
[ "Combine", "all", "message", "lines", "occuring", "in", "the", "additionalLines", "list", "adding", "a", "newline", "character", "between", "each", "line", "<p", ">", "the", "event", "will", "already", "have", "a", "message", "-", "combine", "this", "message", "with", "the", "message", "lines", "in", "the", "additionalLines", "list", "(", "all", "entries", "prior", "to", "the", "exceptionLine", "index", ")" ]
train
https://github.com/ops4j/org.ops4j.pax.logging/blob/493de4e1db4fe9f981f3dd78b8e40e5bf2b2e59d/pax-logging-service/src/main/java/org/apache/log4j/receivers/varia/LogFilePatternReceiver.java#L400-L416
grails/gorm-hibernate5
grails-datastore-gorm-hibernate5/src/main/groovy/org/grails/orm/hibernate/query/GrailsHibernateQueryUtils.java
GrailsHibernateQueryUtils.addOrderPossiblyNested
private static void addOrderPossiblyNested(CriteriaQuery query, From queryRoot, CriteriaBuilder criteriaBuilder, PersistentEntity entity, String sort, String order, boolean ignoreCase) { """ Add order to criteria, creating necessary subCriteria if nested sort property (ie. sort:'nested.property'). """ int firstDotPos = sort.indexOf("."); if (firstDotPos == -1) { addOrder(entity, query, queryRoot, criteriaBuilder, sort, order, ignoreCase); } else { // nested property String sortHead = sort.substring(0, firstDotPos); String sortTail = sort.substring(firstDotPos + 1); PersistentProperty property = entity.getPropertyByName(sortHead); if (property instanceof Embedded) { // embedded objects cannot reference entities (at time of writing), so no more recursion needed addOrder(entity, query, queryRoot, criteriaBuilder, sort, order, ignoreCase); } else if (property instanceof Association) { Association a = (Association) property; final Join join = queryRoot.join(sortHead); PersistentEntity associatedEntity = a.getAssociatedEntity(); Class<?> propertyTargetClass = associatedEntity.getJavaClass(); addOrderPossiblyNested(query, join, criteriaBuilder, associatedEntity, sortTail, order, ignoreCase); // Recurse on nested sort } } }
java
private static void addOrderPossiblyNested(CriteriaQuery query, From queryRoot, CriteriaBuilder criteriaBuilder, PersistentEntity entity, String sort, String order, boolean ignoreCase) { int firstDotPos = sort.indexOf("."); if (firstDotPos == -1) { addOrder(entity, query, queryRoot, criteriaBuilder, sort, order, ignoreCase); } else { // nested property String sortHead = sort.substring(0, firstDotPos); String sortTail = sort.substring(firstDotPos + 1); PersistentProperty property = entity.getPropertyByName(sortHead); if (property instanceof Embedded) { // embedded objects cannot reference entities (at time of writing), so no more recursion needed addOrder(entity, query, queryRoot, criteriaBuilder, sort, order, ignoreCase); } else if (property instanceof Association) { Association a = (Association) property; final Join join = queryRoot.join(sortHead); PersistentEntity associatedEntity = a.getAssociatedEntity(); Class<?> propertyTargetClass = associatedEntity.getJavaClass(); addOrderPossiblyNested(query, join, criteriaBuilder, associatedEntity, sortTail, order, ignoreCase); // Recurse on nested sort } } }
[ "private", "static", "void", "addOrderPossiblyNested", "(", "CriteriaQuery", "query", ",", "From", "queryRoot", ",", "CriteriaBuilder", "criteriaBuilder", ",", "PersistentEntity", "entity", ",", "String", "sort", ",", "String", "order", ",", "boolean", "ignoreCase", ")", "{", "int", "firstDotPos", "=", "sort", ".", "indexOf", "(", "\".\"", ")", ";", "if", "(", "firstDotPos", "==", "-", "1", ")", "{", "addOrder", "(", "entity", ",", "query", ",", "queryRoot", ",", "criteriaBuilder", ",", "sort", ",", "order", ",", "ignoreCase", ")", ";", "}", "else", "{", "// nested property", "String", "sortHead", "=", "sort", ".", "substring", "(", "0", ",", "firstDotPos", ")", ";", "String", "sortTail", "=", "sort", ".", "substring", "(", "firstDotPos", "+", "1", ")", ";", "PersistentProperty", "property", "=", "entity", ".", "getPropertyByName", "(", "sortHead", ")", ";", "if", "(", "property", "instanceof", "Embedded", ")", "{", "// embedded objects cannot reference entities (at time of writing), so no more recursion needed", "addOrder", "(", "entity", ",", "query", ",", "queryRoot", ",", "criteriaBuilder", ",", "sort", ",", "order", ",", "ignoreCase", ")", ";", "}", "else", "if", "(", "property", "instanceof", "Association", ")", "{", "Association", "a", "=", "(", "Association", ")", "property", ";", "final", "Join", "join", "=", "queryRoot", ".", "join", "(", "sortHead", ")", ";", "PersistentEntity", "associatedEntity", "=", "a", ".", "getAssociatedEntity", "(", ")", ";", "Class", "<", "?", ">", "propertyTargetClass", "=", "associatedEntity", ".", "getJavaClass", "(", ")", ";", "addOrderPossiblyNested", "(", "query", ",", "join", ",", "criteriaBuilder", ",", "associatedEntity", ",", "sortTail", ",", "order", ",", "ignoreCase", ")", ";", "// Recurse on nested sort", "}", "}", "}" ]
Add order to criteria, creating necessary subCriteria if nested sort property (ie. sort:'nested.property').
[ "Add", "order", "to", "criteria", "creating", "necessary", "subCriteria", "if", "nested", "sort", "property", "(", "ie", ".", "sort", ":", "nested", ".", "property", ")", "." ]
train
https://github.com/grails/gorm-hibernate5/blob/0ebb80cd769ef2bea955723d4543828a3e9542ef/grails-datastore-gorm-hibernate5/src/main/groovy/org/grails/orm/hibernate/query/GrailsHibernateQueryUtils.java#L268-L293
JavaMoney/jsr354-ri
moneta-core/src/main/java/org/javamoney/moneta/spi/AbstractCurrencyConversion.java
AbstractCurrencyConversion.roundFactor
protected NumberValue roundFactor(MonetaryAmount amount, NumberValue factor) { """ Optionally rounds the factor to be used. By default this method will only round as much as it is needed, so the factor can be handled by the target amount instance based on its numeric capabilities. Rounding is applied only if {@code amount.getContext().getMaxScale() > 0} as follows: <ul> <li>If the amount provides a {@link MathContext} as context property this is used.</li> <li>If the amount provides a {@link RoundingMode}, this is used (default is {@code RoundingMode.HALF_EVEN}).</li> <li>By default the scale used is scale of the conversion factor. If the acmount allows a higher scale based on {@code amount.getContext().getMaxScale()}, this higher scale is used.</li> </ul> @param amount the amount, not null. @param factor the factor @return the new rounding factor, never null. """ if (amount.getContext().getMaxScale() > 0) { MathContext mathContext = amount.getContext().get(MathContext.class); if(mathContext==null){ int scale = factor.getScale(); if (factor.getScale() > amount.getContext().getMaxScale()) { scale = amount.getContext().getMaxScale(); } RoundingMode roundingMode = amount.getContext().get(RoundingMode.class); if(roundingMode==null){ roundingMode = RoundingMode.HALF_EVEN; } mathContext = new MathContext(scale, roundingMode); } return factor.round(mathContext); } return factor; }
java
protected NumberValue roundFactor(MonetaryAmount amount, NumberValue factor) { if (amount.getContext().getMaxScale() > 0) { MathContext mathContext = amount.getContext().get(MathContext.class); if(mathContext==null){ int scale = factor.getScale(); if (factor.getScale() > amount.getContext().getMaxScale()) { scale = amount.getContext().getMaxScale(); } RoundingMode roundingMode = amount.getContext().get(RoundingMode.class); if(roundingMode==null){ roundingMode = RoundingMode.HALF_EVEN; } mathContext = new MathContext(scale, roundingMode); } return factor.round(mathContext); } return factor; }
[ "protected", "NumberValue", "roundFactor", "(", "MonetaryAmount", "amount", ",", "NumberValue", "factor", ")", "{", "if", "(", "amount", ".", "getContext", "(", ")", ".", "getMaxScale", "(", ")", ">", "0", ")", "{", "MathContext", "mathContext", "=", "amount", ".", "getContext", "(", ")", ".", "get", "(", "MathContext", ".", "class", ")", ";", "if", "(", "mathContext", "==", "null", ")", "{", "int", "scale", "=", "factor", ".", "getScale", "(", ")", ";", "if", "(", "factor", ".", "getScale", "(", ")", ">", "amount", ".", "getContext", "(", ")", ".", "getMaxScale", "(", ")", ")", "{", "scale", "=", "amount", ".", "getContext", "(", ")", ".", "getMaxScale", "(", ")", ";", "}", "RoundingMode", "roundingMode", "=", "amount", ".", "getContext", "(", ")", ".", "get", "(", "RoundingMode", ".", "class", ")", ";", "if", "(", "roundingMode", "==", "null", ")", "{", "roundingMode", "=", "RoundingMode", ".", "HALF_EVEN", ";", "}", "mathContext", "=", "new", "MathContext", "(", "scale", ",", "roundingMode", ")", ";", "}", "return", "factor", ".", "round", "(", "mathContext", ")", ";", "}", "return", "factor", ";", "}" ]
Optionally rounds the factor to be used. By default this method will only round as much as it is needed, so the factor can be handled by the target amount instance based on its numeric capabilities. Rounding is applied only if {@code amount.getContext().getMaxScale() > 0} as follows: <ul> <li>If the amount provides a {@link MathContext} as context property this is used.</li> <li>If the amount provides a {@link RoundingMode}, this is used (default is {@code RoundingMode.HALF_EVEN}).</li> <li>By default the scale used is scale of the conversion factor. If the acmount allows a higher scale based on {@code amount.getContext().getMaxScale()}, this higher scale is used.</li> </ul> @param amount the amount, not null. @param factor the factor @return the new rounding factor, never null.
[ "Optionally", "rounds", "the", "factor", "to", "be", "used", ".", "By", "default", "this", "method", "will", "only", "round", "as", "much", "as", "it", "is", "needed", "so", "the", "factor", "can", "be", "handled", "by", "the", "target", "amount", "instance", "based", "on", "its", "numeric", "capabilities", ".", "Rounding", "is", "applied", "only", "if", "{", "@code", "amount", ".", "getContext", "()", ".", "getMaxScale", "()", ">", "0", "}", "as", "follows", ":", "<ul", ">", "<li", ">", "If", "the", "amount", "provides", "a", "{", "@link", "MathContext", "}", "as", "context", "property", "this", "is", "used", ".", "<", "/", "li", ">", "<li", ">", "If", "the", "amount", "provides", "a", "{", "@link", "RoundingMode", "}", "this", "is", "used", "(", "default", "is", "{", "@code", "RoundingMode", ".", "HALF_EVEN", "}", ")", ".", "<", "/", "li", ">", "<li", ">", "By", "default", "the", "scale", "used", "is", "scale", "of", "the", "conversion", "factor", ".", "If", "the", "acmount", "allows", "a", "higher", "scale", "based", "on", "{", "@code", "amount", ".", "getContext", "()", ".", "getMaxScale", "()", "}", "this", "higher", "scale", "is", "used", ".", "<", "/", "li", ">", "<", "/", "ul", ">" ]
train
https://github.com/JavaMoney/jsr354-ri/blob/cf8ff2bbaf9b115acc05eb9b0c76c8397c308284/moneta-core/src/main/java/org/javamoney/moneta/spi/AbstractCurrencyConversion.java#L138-L155
mikepenz/FastAdapter
app/src/main/java/com/mikepenz/fastadapter/app/model/ModelIconItem.java
ModelIconItem.bindView
@Override public void bindView(ViewHolder viewHolder, List<Object> payloads) { """ binds the data of this item onto the viewHolder @param viewHolder the viewHolder of this item """ super.bindView(viewHolder, payloads); //define our data for the view viewHolder.image.setIcon(new IconicsDrawable(viewHolder.image.getContext(), getModel().icon)); viewHolder.name.setText(getModel().icon.getName()); }
java
@Override public void bindView(ViewHolder viewHolder, List<Object> payloads) { super.bindView(viewHolder, payloads); //define our data for the view viewHolder.image.setIcon(new IconicsDrawable(viewHolder.image.getContext(), getModel().icon)); viewHolder.name.setText(getModel().icon.getName()); }
[ "@", "Override", "public", "void", "bindView", "(", "ViewHolder", "viewHolder", ",", "List", "<", "Object", ">", "payloads", ")", "{", "super", ".", "bindView", "(", "viewHolder", ",", "payloads", ")", ";", "//define our data for the view", "viewHolder", ".", "image", ".", "setIcon", "(", "new", "IconicsDrawable", "(", "viewHolder", ".", "image", ".", "getContext", "(", ")", ",", "getModel", "(", ")", ".", "icon", ")", ")", ";", "viewHolder", ".", "name", ".", "setText", "(", "getModel", "(", ")", ".", "icon", ".", "getName", "(", ")", ")", ";", "}" ]
binds the data of this item onto the viewHolder @param viewHolder the viewHolder of this item
[ "binds", "the", "data", "of", "this", "item", "onto", "the", "viewHolder" ]
train
https://github.com/mikepenz/FastAdapter/blob/3b2412abe001ba58422e0125846b704d4dba4ae9/app/src/main/java/com/mikepenz/fastadapter/app/model/ModelIconItem.java#L51-L58
lessthanoptimal/ejml
main/ejml-ddense/src/org/ejml/dense/fixed/CommonOps_DDF2.java
CommonOps_DDF2.multAddOuter
public static void multAddOuter( double alpha , DMatrix2x2 A , double beta , DMatrix2 u , DMatrix2 v , DMatrix2x2 C ) { """ C = &alpha;A + &beta;u*v<sup>T</sup> @param alpha scale factor applied to A @param A matrix @param beta scale factor applies to outer product @param u vector @param v vector @param C Storage for solution. Can be same instance as A. """ C.a11 = alpha*A.a11 + beta*u.a1*v.a1; C.a12 = alpha*A.a12 + beta*u.a1*v.a2; C.a21 = alpha*A.a21 + beta*u.a2*v.a1; C.a22 = alpha*A.a22 + beta*u.a2*v.a2; }
java
public static void multAddOuter( double alpha , DMatrix2x2 A , double beta , DMatrix2 u , DMatrix2 v , DMatrix2x2 C ) { C.a11 = alpha*A.a11 + beta*u.a1*v.a1; C.a12 = alpha*A.a12 + beta*u.a1*v.a2; C.a21 = alpha*A.a21 + beta*u.a2*v.a1; C.a22 = alpha*A.a22 + beta*u.a2*v.a2; }
[ "public", "static", "void", "multAddOuter", "(", "double", "alpha", ",", "DMatrix2x2", "A", ",", "double", "beta", ",", "DMatrix2", "u", ",", "DMatrix2", "v", ",", "DMatrix2x2", "C", ")", "{", "C", ".", "a11", "=", "alpha", "*", "A", ".", "a11", "+", "beta", "*", "u", ".", "a1", "*", "v", ".", "a1", ";", "C", ".", "a12", "=", "alpha", "*", "A", ".", "a12", "+", "beta", "*", "u", ".", "a1", "*", "v", ".", "a2", ";", "C", ".", "a21", "=", "alpha", "*", "A", ".", "a21", "+", "beta", "*", "u", ".", "a2", "*", "v", ".", "a1", ";", "C", ".", "a22", "=", "alpha", "*", "A", ".", "a22", "+", "beta", "*", "u", ".", "a2", "*", "v", ".", "a2", ";", "}" ]
C = &alpha;A + &beta;u*v<sup>T</sup> @param alpha scale factor applied to A @param A matrix @param beta scale factor applies to outer product @param u vector @param v vector @param C Storage for solution. Can be same instance as A.
[ "C", "=", "&alpha", ";", "A", "+", "&beta", ";", "u", "*", "v<sup", ">", "T<", "/", "sup", ">" ]
train
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/fixed/CommonOps_DDF2.java#L537-L542
google/closure-templates
java/src/com/google/template/soy/soyparse/ParseErrors.java
ParseErrors.validateSelectCaseLabel
static String validateSelectCaseLabel(ExprNode caseValue, ErrorReporter reporter) { """ Validates an expression being used as a {@code case} label in a {@code select}. """ boolean isNumeric; boolean isError; String value; if (caseValue instanceof StringNode) { value = ((StringNode) caseValue).getValue(); // Validate that our select cases are argument names as required by the ICU MessageFormat // library. We can offer a much better user experience by doing this validation eagerly. // NOTE: in theory we could allow numeric select cases, but this is almost always an error // (they should have used plural), if there turns out to be some good reason for this (e.g. // the numbers are reflect ordinals instead of cardinals), then we can revisit this error. int argNumber = MessagePattern.validateArgumentName(value); if (argNumber != MessagePattern.ARG_NAME_NOT_NUMBER) { try { // there are more efficient ways to do this, but we are already in an error case so who // cares Long.parseLong(value); isNumeric = true; } catch (NumberFormatException nfe) { isNumeric = false; } isError = true; } else { isNumeric = false; isError = false; } } else { isNumeric = caseValue instanceof FloatNode || caseValue instanceof IntegerNode; isError = true; value = ""; } if (isError) { reporter.report( caseValue.getSourceLocation(), SELECT_CASE_INVALID_VALUE, isNumeric ? " Did you mean to use {plural} instead of {select}?" : ""); } return value; }
java
static String validateSelectCaseLabel(ExprNode caseValue, ErrorReporter reporter) { boolean isNumeric; boolean isError; String value; if (caseValue instanceof StringNode) { value = ((StringNode) caseValue).getValue(); // Validate that our select cases are argument names as required by the ICU MessageFormat // library. We can offer a much better user experience by doing this validation eagerly. // NOTE: in theory we could allow numeric select cases, but this is almost always an error // (they should have used plural), if there turns out to be some good reason for this (e.g. // the numbers are reflect ordinals instead of cardinals), then we can revisit this error. int argNumber = MessagePattern.validateArgumentName(value); if (argNumber != MessagePattern.ARG_NAME_NOT_NUMBER) { try { // there are more efficient ways to do this, but we are already in an error case so who // cares Long.parseLong(value); isNumeric = true; } catch (NumberFormatException nfe) { isNumeric = false; } isError = true; } else { isNumeric = false; isError = false; } } else { isNumeric = caseValue instanceof FloatNode || caseValue instanceof IntegerNode; isError = true; value = ""; } if (isError) { reporter.report( caseValue.getSourceLocation(), SELECT_CASE_INVALID_VALUE, isNumeric ? " Did you mean to use {plural} instead of {select}?" : ""); } return value; }
[ "static", "String", "validateSelectCaseLabel", "(", "ExprNode", "caseValue", ",", "ErrorReporter", "reporter", ")", "{", "boolean", "isNumeric", ";", "boolean", "isError", ";", "String", "value", ";", "if", "(", "caseValue", "instanceof", "StringNode", ")", "{", "value", "=", "(", "(", "StringNode", ")", "caseValue", ")", ".", "getValue", "(", ")", ";", "// Validate that our select cases are argument names as required by the ICU MessageFormat", "// library. We can offer a much better user experience by doing this validation eagerly.", "// NOTE: in theory we could allow numeric select cases, but this is almost always an error", "// (they should have used plural), if there turns out to be some good reason for this (e.g.", "// the numbers are reflect ordinals instead of cardinals), then we can revisit this error.", "int", "argNumber", "=", "MessagePattern", ".", "validateArgumentName", "(", "value", ")", ";", "if", "(", "argNumber", "!=", "MessagePattern", ".", "ARG_NAME_NOT_NUMBER", ")", "{", "try", "{", "// there are more efficient ways to do this, but we are already in an error case so who", "// cares", "Long", ".", "parseLong", "(", "value", ")", ";", "isNumeric", "=", "true", ";", "}", "catch", "(", "NumberFormatException", "nfe", ")", "{", "isNumeric", "=", "false", ";", "}", "isError", "=", "true", ";", "}", "else", "{", "isNumeric", "=", "false", ";", "isError", "=", "false", ";", "}", "}", "else", "{", "isNumeric", "=", "caseValue", "instanceof", "FloatNode", "||", "caseValue", "instanceof", "IntegerNode", ";", "isError", "=", "true", ";", "value", "=", "\"\"", ";", "}", "if", "(", "isError", ")", "{", "reporter", ".", "report", "(", "caseValue", ".", "getSourceLocation", "(", ")", ",", "SELECT_CASE_INVALID_VALUE", ",", "isNumeric", "?", "\" Did you mean to use {plural} instead of {select}?\"", ":", "\"\"", ")", ";", "}", "return", "value", ";", "}" ]
Validates an expression being used as a {@code case} label in a {@code select}.
[ "Validates", "an", "expression", "being", "used", "as", "a", "{" ]
train
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/soyparse/ParseErrors.java#L342-L380
openengsb/openengsb
components/ekb/transformation-wonderland/src/main/java/org/openengsb/core/ekb/transformation/wonderland/internal/performer/TransformationPerformer.java
TransformationPerformer.getObjectValue
private Object getObjectValue(String fieldname, boolean fromSource) throws Exception { """ Gets the value of the field with the field name either from the source object or the target object, depending on the parameters. Is also aware of temporary fields. """ Object sourceObject = fromSource ? source : target; Object result = null; for (String part : StringUtils.split(fieldname, ".")) { if (isTemporaryField(part)) { result = loadObjectFromTemporary(part, fieldname); } else { result = loadObjectFromField(part, result, sourceObject); } } return result; }
java
private Object getObjectValue(String fieldname, boolean fromSource) throws Exception { Object sourceObject = fromSource ? source : target; Object result = null; for (String part : StringUtils.split(fieldname, ".")) { if (isTemporaryField(part)) { result = loadObjectFromTemporary(part, fieldname); } else { result = loadObjectFromField(part, result, sourceObject); } } return result; }
[ "private", "Object", "getObjectValue", "(", "String", "fieldname", ",", "boolean", "fromSource", ")", "throws", "Exception", "{", "Object", "sourceObject", "=", "fromSource", "?", "source", ":", "target", ";", "Object", "result", "=", "null", ";", "for", "(", "String", "part", ":", "StringUtils", ".", "split", "(", "fieldname", ",", "\".\"", ")", ")", "{", "if", "(", "isTemporaryField", "(", "part", ")", ")", "{", "result", "=", "loadObjectFromTemporary", "(", "part", ",", "fieldname", ")", ";", "}", "else", "{", "result", "=", "loadObjectFromField", "(", "part", ",", "result", ",", "sourceObject", ")", ";", "}", "}", "return", "result", ";", "}" ]
Gets the value of the field with the field name either from the source object or the target object, depending on the parameters. Is also aware of temporary fields.
[ "Gets", "the", "value", "of", "the", "field", "with", "the", "field", "name", "either", "from", "the", "source", "object", "or", "the", "target", "object", "depending", "on", "the", "parameters", ".", "Is", "also", "aware", "of", "temporary", "fields", "." ]
train
https://github.com/openengsb/openengsb/blob/d39058000707f617cd405629f9bc7f17da7b414a/components/ekb/transformation-wonderland/src/main/java/org/openengsb/core/ekb/transformation/wonderland/internal/performer/TransformationPerformer.java#L166-L177
enasequence/sequencetools
src/main/java/uk/ac/ebi/embl/api/validation/EnaValidator.java
EnaValidator.prepareReader
private void prepareReader(BufferedReader fileReader, String fileId) { """ Prepare reader. @param fileReader the file reader @param fileId the file name """ switch (fileType) { case EMBL: EmblEntryReader emblReader = new EmblEntryReader( fileReader, EmblEntryReader.Format.EMBL_FORMAT,fileId); emblReader.setCheckBlockCounts(lineCount); reader = emblReader; break; case GENBANK: reader = new GenbankEntryReader(fileReader,fileId); break; case GFF3: reader = new GFF3FlatFileEntryReader(fileReader); break; case FASTA: reader = new FastaFileReader(new FastaLineReader(fileReader)); break; case AGP: reader= new AGPFileReader(new AGPLineReader(fileReader)); break; default: System.exit(0); break; } }
java
private void prepareReader(BufferedReader fileReader, String fileId) { switch (fileType) { case EMBL: EmblEntryReader emblReader = new EmblEntryReader( fileReader, EmblEntryReader.Format.EMBL_FORMAT,fileId); emblReader.setCheckBlockCounts(lineCount); reader = emblReader; break; case GENBANK: reader = new GenbankEntryReader(fileReader,fileId); break; case GFF3: reader = new GFF3FlatFileEntryReader(fileReader); break; case FASTA: reader = new FastaFileReader(new FastaLineReader(fileReader)); break; case AGP: reader= new AGPFileReader(new AGPLineReader(fileReader)); break; default: System.exit(0); break; } }
[ "private", "void", "prepareReader", "(", "BufferedReader", "fileReader", ",", "String", "fileId", ")", "{", "switch", "(", "fileType", ")", "{", "case", "EMBL", ":", "EmblEntryReader", "emblReader", "=", "new", "EmblEntryReader", "(", "fileReader", ",", "EmblEntryReader", ".", "Format", ".", "EMBL_FORMAT", ",", "fileId", ")", ";", "emblReader", ".", "setCheckBlockCounts", "(", "lineCount", ")", ";", "reader", "=", "emblReader", ";", "break", ";", "case", "GENBANK", ":", "reader", "=", "new", "GenbankEntryReader", "(", "fileReader", ",", "fileId", ")", ";", "break", ";", "case", "GFF3", ":", "reader", "=", "new", "GFF3FlatFileEntryReader", "(", "fileReader", ")", ";", "break", ";", "case", "FASTA", ":", "reader", "=", "new", "FastaFileReader", "(", "new", "FastaLineReader", "(", "fileReader", ")", ")", ";", "break", ";", "case", "AGP", ":", "reader", "=", "new", "AGPFileReader", "(", "new", "AGPLineReader", "(", "fileReader", ")", ")", ";", "break", ";", "default", ":", "System", ".", "exit", "(", "0", ")", ";", "break", ";", "}", "}" ]
Prepare reader. @param fileReader the file reader @param fileId the file name
[ "Prepare", "reader", "." ]
train
https://github.com/enasequence/sequencetools/blob/4127f5e1a17540239f5810136153fbd6737fa262/src/main/java/uk/ac/ebi/embl/api/validation/EnaValidator.java#L545-L571
ops4j/org.ops4j.base
ops4j-base-io/src/main/java/org/ops4j/io/ZipExploder.java
ZipExploder.copyFileEntry
public void copyFileEntry(File destDir, ZipFile zf, ZipEntry ze) throws IOException { """ copy a single entry from the archive @param destDir @param zf @param ze @throws IOException """ BufferedInputStream dis = new BufferedInputStream(zf.getInputStream(ze)); try { copyFileEntry(destDir, ze.isDirectory(), ze.getName(), dis); } finally { try { dis.close(); } catch (IOException ioe) { } } }
java
public void copyFileEntry(File destDir, ZipFile zf, ZipEntry ze) throws IOException { BufferedInputStream dis = new BufferedInputStream(zf.getInputStream(ze)); try { copyFileEntry(destDir, ze.isDirectory(), ze.getName(), dis); } finally { try { dis.close(); } catch (IOException ioe) { } } }
[ "public", "void", "copyFileEntry", "(", "File", "destDir", ",", "ZipFile", "zf", ",", "ZipEntry", "ze", ")", "throws", "IOException", "{", "BufferedInputStream", "dis", "=", "new", "BufferedInputStream", "(", "zf", ".", "getInputStream", "(", "ze", ")", ")", ";", "try", "{", "copyFileEntry", "(", "destDir", ",", "ze", ".", "isDirectory", "(", ")", ",", "ze", ".", "getName", "(", ")", ",", "dis", ")", ";", "}", "finally", "{", "try", "{", "dis", ".", "close", "(", ")", ";", "}", "catch", "(", "IOException", "ioe", ")", "{", "}", "}", "}" ]
copy a single entry from the archive @param destDir @param zf @param ze @throws IOException
[ "copy", "a", "single", "entry", "from", "the", "archive" ]
train
https://github.com/ops4j/org.ops4j.base/blob/b0e742c0d9511f6b19ca64da2ebaf30b7a47256a/ops4j-base-io/src/main/java/org/ops4j/io/ZipExploder.java#L304-L314
livetribe/livetribe-slp
core/src/main/java/org/livetribe/slp/sa/StandardServiceAgentServer.java
StandardServiceAgentServer.handleTCPSrvReg
protected void handleTCPSrvReg(SrvReg srvReg, Socket socket) { """ Handles a unicast TCP SrvReg message arrived to this service agent. <br /> This service agent will reply with an acknowledge containing the result of the registration. @param srvReg the SrvReg message to handle @param socket the socket connected to th client where to write the reply """ try { boolean update = srvReg.isUpdating(); ServiceInfo givenService = ServiceInfo.from(srvReg); ServiceInfoCache.Result<ServiceInfo> result = cacheService(givenService, update); forwardRegistration(givenService, result.getPrevious(), result.getCurrent(), update); tcpSrvAck.perform(socket, srvReg, SLPError.NO_ERROR); } catch (ServiceLocationException x) { tcpSrvAck.perform(socket, srvReg, x.getSLPError()); } }
java
protected void handleTCPSrvReg(SrvReg srvReg, Socket socket) { try { boolean update = srvReg.isUpdating(); ServiceInfo givenService = ServiceInfo.from(srvReg); ServiceInfoCache.Result<ServiceInfo> result = cacheService(givenService, update); forwardRegistration(givenService, result.getPrevious(), result.getCurrent(), update); tcpSrvAck.perform(socket, srvReg, SLPError.NO_ERROR); } catch (ServiceLocationException x) { tcpSrvAck.perform(socket, srvReg, x.getSLPError()); } }
[ "protected", "void", "handleTCPSrvReg", "(", "SrvReg", "srvReg", ",", "Socket", "socket", ")", "{", "try", "{", "boolean", "update", "=", "srvReg", ".", "isUpdating", "(", ")", ";", "ServiceInfo", "givenService", "=", "ServiceInfo", ".", "from", "(", "srvReg", ")", ";", "ServiceInfoCache", ".", "Result", "<", "ServiceInfo", ">", "result", "=", "cacheService", "(", "givenService", ",", "update", ")", ";", "forwardRegistration", "(", "givenService", ",", "result", ".", "getPrevious", "(", ")", ",", "result", ".", "getCurrent", "(", ")", ",", "update", ")", ";", "tcpSrvAck", ".", "perform", "(", "socket", ",", "srvReg", ",", "SLPError", ".", "NO_ERROR", ")", ";", "}", "catch", "(", "ServiceLocationException", "x", ")", "{", "tcpSrvAck", ".", "perform", "(", "socket", ",", "srvReg", ",", "x", ".", "getSLPError", "(", ")", ")", ";", "}", "}" ]
Handles a unicast TCP SrvReg message arrived to this service agent. <br /> This service agent will reply with an acknowledge containing the result of the registration. @param srvReg the SrvReg message to handle @param socket the socket connected to th client where to write the reply
[ "Handles", "a", "unicast", "TCP", "SrvReg", "message", "arrived", "to", "this", "service", "agent", ".", "<br", "/", ">", "This", "service", "agent", "will", "reply", "with", "an", "acknowledge", "containing", "the", "result", "of", "the", "registration", "." ]
train
https://github.com/livetribe/livetribe-slp/blob/6cc13dbe81feab133fe3dd291ca081cbc6e1f591/core/src/main/java/org/livetribe/slp/sa/StandardServiceAgentServer.java#L168-L182
spotify/docgenerator
scanner/src/main/java/com/spotify/docgenerator/JacksonJerseyAnnotationProcessor.java
JacksonJerseyAnnotationProcessor.computeMethod
private ResourceMethod computeMethod(ExecutableElement ee, List<ResourceArgument> arguments) { """ Given an {@link ExecutableElement} representing the method, and the already computed list of arguments to the method, produce a {@link ResourceMethod}. """ final String javaDoc = processingEnv.getElementUtils().getDocComment(ee); final Path pathAnnotation = ee.getAnnotation(Path.class); final Produces producesAnnotation = ee.getAnnotation(Produces.class); return new ResourceMethod( ee.getSimpleName().toString(), computeRequestMethod(ee), (pathAnnotation == null) ? null : pathAnnotation.value(), (producesAnnotation == null) ? null : Joiner.on(",").join(producesAnnotation.value()), makeTypeDescriptor(ee.getReturnType()), arguments, javaDoc); }
java
private ResourceMethod computeMethod(ExecutableElement ee, List<ResourceArgument> arguments) { final String javaDoc = processingEnv.getElementUtils().getDocComment(ee); final Path pathAnnotation = ee.getAnnotation(Path.class); final Produces producesAnnotation = ee.getAnnotation(Produces.class); return new ResourceMethod( ee.getSimpleName().toString(), computeRequestMethod(ee), (pathAnnotation == null) ? null : pathAnnotation.value(), (producesAnnotation == null) ? null : Joiner.on(",").join(producesAnnotation.value()), makeTypeDescriptor(ee.getReturnType()), arguments, javaDoc); }
[ "private", "ResourceMethod", "computeMethod", "(", "ExecutableElement", "ee", ",", "List", "<", "ResourceArgument", ">", "arguments", ")", "{", "final", "String", "javaDoc", "=", "processingEnv", ".", "getElementUtils", "(", ")", ".", "getDocComment", "(", "ee", ")", ";", "final", "Path", "pathAnnotation", "=", "ee", ".", "getAnnotation", "(", "Path", ".", "class", ")", ";", "final", "Produces", "producesAnnotation", "=", "ee", ".", "getAnnotation", "(", "Produces", ".", "class", ")", ";", "return", "new", "ResourceMethod", "(", "ee", ".", "getSimpleName", "(", ")", ".", "toString", "(", ")", ",", "computeRequestMethod", "(", "ee", ")", ",", "(", "pathAnnotation", "==", "null", ")", "?", "null", ":", "pathAnnotation", ".", "value", "(", ")", ",", "(", "producesAnnotation", "==", "null", ")", "?", "null", ":", "Joiner", ".", "on", "(", "\",\"", ")", ".", "join", "(", "producesAnnotation", ".", "value", "(", ")", ")", ",", "makeTypeDescriptor", "(", "ee", ".", "getReturnType", "(", ")", ")", ",", "arguments", ",", "javaDoc", ")", ";", "}" ]
Given an {@link ExecutableElement} representing the method, and the already computed list of arguments to the method, produce a {@link ResourceMethod}.
[ "Given", "an", "{" ]
train
https://github.com/spotify/docgenerator/blob/a7965f6d4a1546864a3f8584b86841cef9ac2f65/scanner/src/main/java/com/spotify/docgenerator/JacksonJerseyAnnotationProcessor.java#L169-L181
sockeqwe/SwipeBack
library/src/com/hannesdorfmann/swipeback/SwipeBack.java
SwipeBack.setSwipeBackView
public SwipeBack setSwipeBackView(View view, LayoutParams params) { """ Set the swipe back view to an explicit view. @param view The swipe back view. @param params Layout parameters for the view. """ mSwipeBackView = view; mSwipeBackContainer.removeAllViews(); mSwipeBackContainer.addView(view, params); notifySwipeBackViewCreated(mSwipeBackView); return this; }
java
public SwipeBack setSwipeBackView(View view, LayoutParams params) { mSwipeBackView = view; mSwipeBackContainer.removeAllViews(); mSwipeBackContainer.addView(view, params); notifySwipeBackViewCreated(mSwipeBackView); return this; }
[ "public", "SwipeBack", "setSwipeBackView", "(", "View", "view", ",", "LayoutParams", "params", ")", "{", "mSwipeBackView", "=", "view", ";", "mSwipeBackContainer", ".", "removeAllViews", "(", ")", ";", "mSwipeBackContainer", ".", "addView", "(", "view", ",", "params", ")", ";", "notifySwipeBackViewCreated", "(", "mSwipeBackView", ")", ";", "return", "this", ";", "}" ]
Set the swipe back view to an explicit view. @param view The swipe back view. @param params Layout parameters for the view.
[ "Set", "the", "swipe", "back", "view", "to", "an", "explicit", "view", "." ]
train
https://github.com/sockeqwe/SwipeBack/blob/09ed11f48e930ed47fd4f07ad1c786fc9fff3c48/library/src/com/hannesdorfmann/swipeback/SwipeBack.java#L1385-L1393
UrielCh/ovh-java-sdk
ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java
ApiOvhCloud.project_serviceName_network_private_networkId_region_POST
public OvhNetwork project_serviceName_network_private_networkId_region_POST(String serviceName, String networkId, String region) throws IOException { """ Activate private network in a new region REST: POST /cloud/project/{serviceName}/network/private/{networkId}/region @param networkId [required] Network id @param region [required] Region to active on your network @param serviceName [required] Service name """ String qPath = "/cloud/project/{serviceName}/network/private/{networkId}/region"; StringBuilder sb = path(qPath, serviceName, networkId); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "region", region); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhNetwork.class); }
java
public OvhNetwork project_serviceName_network_private_networkId_region_POST(String serviceName, String networkId, String region) throws IOException { String qPath = "/cloud/project/{serviceName}/network/private/{networkId}/region"; StringBuilder sb = path(qPath, serviceName, networkId); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "region", region); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhNetwork.class); }
[ "public", "OvhNetwork", "project_serviceName_network_private_networkId_region_POST", "(", "String", "serviceName", ",", "String", "networkId", ",", "String", "region", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/cloud/project/{serviceName}/network/private/{networkId}/region\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ",", "networkId", ")", ";", "HashMap", "<", "String", ",", "Object", ">", "o", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "addBody", "(", "o", ",", "\"region\"", ",", "region", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"POST\"", ",", "sb", ".", "toString", "(", ")", ",", "o", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhNetwork", ".", "class", ")", ";", "}" ]
Activate private network in a new region REST: POST /cloud/project/{serviceName}/network/private/{networkId}/region @param networkId [required] Network id @param region [required] Region to active on your network @param serviceName [required] Service name
[ "Activate", "private", "network", "in", "a", "new", "region" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java#L812-L819
wuman/orientdb-android
core/src/main/java/com/orientechnologies/orient/core/index/OIndexDefinitionFactory.java
OIndexDefinitionFactory.createIndexDefinition
public static OIndexDefinition createIndexDefinition(final OClass oClass, final List<String> fieldNames, final List<OType> types) { """ Creates an instance of {@link OIndexDefinition} for automatic index. @param oClass class which will be indexed @param fieldNames list of properties which will be indexed. Format should be '<property> [by key|value]', use 'by key' or 'by value' to describe how to index maps. By default maps indexed by key @param types types of indexed properties @return index definition instance """ checkTypes(oClass, fieldNames, types); if (fieldNames.size() == 1) return createSingleFieldIndexDefinition(oClass, fieldNames.get(0), types.get(0)); else return createMultipleFieldIndexDefinition(oClass, fieldNames, types); }
java
public static OIndexDefinition createIndexDefinition(final OClass oClass, final List<String> fieldNames, final List<OType> types) { checkTypes(oClass, fieldNames, types); if (fieldNames.size() == 1) return createSingleFieldIndexDefinition(oClass, fieldNames.get(0), types.get(0)); else return createMultipleFieldIndexDefinition(oClass, fieldNames, types); }
[ "public", "static", "OIndexDefinition", "createIndexDefinition", "(", "final", "OClass", "oClass", ",", "final", "List", "<", "String", ">", "fieldNames", ",", "final", "List", "<", "OType", ">", "types", ")", "{", "checkTypes", "(", "oClass", ",", "fieldNames", ",", "types", ")", ";", "if", "(", "fieldNames", ".", "size", "(", ")", "==", "1", ")", "return", "createSingleFieldIndexDefinition", "(", "oClass", ",", "fieldNames", ".", "get", "(", "0", ")", ",", "types", ".", "get", "(", "0", ")", ")", ";", "else", "return", "createMultipleFieldIndexDefinition", "(", "oClass", ",", "fieldNames", ",", "types", ")", ";", "}" ]
Creates an instance of {@link OIndexDefinition} for automatic index. @param oClass class which will be indexed @param fieldNames list of properties which will be indexed. Format should be '<property> [by key|value]', use 'by key' or 'by value' to describe how to index maps. By default maps indexed by key @param types types of indexed properties @return index definition instance
[ "Creates", "an", "instance", "of", "{", "@link", "OIndexDefinition", "}", "for", "automatic", "index", "." ]
train
https://github.com/wuman/orientdb-android/blob/ff9b17e4349f26168b2d0c4facb1a18cbfbe8cf0/core/src/main/java/com/orientechnologies/orient/core/index/OIndexDefinitionFactory.java#L32-L39
ngageoint/geopackage-java
src/main/java/mil/nga/geopackage/extension/coverage/CoverageDataPng.java
CoverageDataPng.getPixelValue
public short getPixelValue(WritableRaster raster, int x, int y) { """ Get the pixel value as an "unsigned short" from the raster and the coordinate @param raster image raster @param x x coordinate @param y y coordinate @return "unsigned short" pixel value """ Object pixelData = raster.getDataElements(x, y, null); short sdata[] = (short[]) pixelData; if (sdata.length != 1) { throw new UnsupportedOperationException( "This method is not supported by this color model"); } short pixelValue = sdata[0]; return pixelValue; }
java
public short getPixelValue(WritableRaster raster, int x, int y) { Object pixelData = raster.getDataElements(x, y, null); short sdata[] = (short[]) pixelData; if (sdata.length != 1) { throw new UnsupportedOperationException( "This method is not supported by this color model"); } short pixelValue = sdata[0]; return pixelValue; }
[ "public", "short", "getPixelValue", "(", "WritableRaster", "raster", ",", "int", "x", ",", "int", "y", ")", "{", "Object", "pixelData", "=", "raster", ".", "getDataElements", "(", "x", ",", "y", ",", "null", ")", ";", "short", "sdata", "[", "]", "=", "(", "short", "[", "]", ")", "pixelData", ";", "if", "(", "sdata", ".", "length", "!=", "1", ")", "{", "throw", "new", "UnsupportedOperationException", "(", "\"This method is not supported by this color model\"", ")", ";", "}", "short", "pixelValue", "=", "sdata", "[", "0", "]", ";", "return", "pixelValue", ";", "}" ]
Get the pixel value as an "unsigned short" from the raster and the coordinate @param raster image raster @param x x coordinate @param y y coordinate @return "unsigned short" pixel value
[ "Get", "the", "pixel", "value", "as", "an", "unsigned", "short", "from", "the", "raster", "and", "the", "coordinate" ]
train
https://github.com/ngageoint/geopackage-java/blob/889bffb5d18330a3f4bd89443acf7959ebe3a376/src/main/java/mil/nga/geopackage/extension/coverage/CoverageDataPng.java#L154-L164
google/closure-templates
java/src/com/google/template/soy/soytree/MsgNode.java
MsgNode.genSubstUnitInfo
private static SubstUnitInfo genSubstUnitInfo(MsgNode msgNode, ErrorReporter errorReporter) { """ Helper function to generate SubstUnitInfo, which contains mappings from/to substitution unit nodes (placeholders and plural/select nodes) to/from generated var names. <p>It is guaranteed that the same var name will never be shared by multiple nodes of different types (types are placeholder, plural, and select). @param msgNode The MsgNode to process. @return The generated SubstUnitInfo for the given MsgNode. """ return genFinalSubstUnitInfoMapsHelper( RepresentativeNodes.createFromNode(msgNode, errorReporter)); }
java
private static SubstUnitInfo genSubstUnitInfo(MsgNode msgNode, ErrorReporter errorReporter) { return genFinalSubstUnitInfoMapsHelper( RepresentativeNodes.createFromNode(msgNode, errorReporter)); }
[ "private", "static", "SubstUnitInfo", "genSubstUnitInfo", "(", "MsgNode", "msgNode", ",", "ErrorReporter", "errorReporter", ")", "{", "return", "genFinalSubstUnitInfoMapsHelper", "(", "RepresentativeNodes", ".", "createFromNode", "(", "msgNode", ",", "errorReporter", ")", ")", ";", "}" ]
Helper function to generate SubstUnitInfo, which contains mappings from/to substitution unit nodes (placeholders and plural/select nodes) to/from generated var names. <p>It is guaranteed that the same var name will never be shared by multiple nodes of different types (types are placeholder, plural, and select). @param msgNode The MsgNode to process. @return The generated SubstUnitInfo for the given MsgNode.
[ "Helper", "function", "to", "generate", "SubstUnitInfo", "which", "contains", "mappings", "from", "/", "to", "substitution", "unit", "nodes", "(", "placeholders", "and", "plural", "/", "select", "nodes", ")", "to", "/", "from", "generated", "var", "names", "." ]
train
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/soytree/MsgNode.java#L460-L463
alkacon/opencms-core
src/org/opencms/ui/apps/modules/CmsModuleInfoDialog.java
CmsModuleInfoDialog.formatResourceType
@SuppressWarnings("deprecation") CmsResourceInfo formatResourceType(I_CmsResourceType type) { """ Creates the resource info box for a resource type.<p> @param type the resource type @return the resource info box """ CmsExplorerTypeSettings settings = OpenCms.getWorkplaceManager().getExplorerTypeSetting(type.getTypeName()); Resource icon; String title; String subtitle; if (settings != null) { icon = CmsResourceUtil.getBigIconResource(settings, null); title = CmsVaadinUtils.getMessageText(settings.getKey()); if (title.startsWith("???")) { title = type.getTypeName(); } subtitle = type.getTypeName() + " (ID: " + type.getTypeId() + (settings.getReference() != null ? (", " + settings.getReference()) : "") + ")"; } else { icon = CmsResourceUtil.getBigIconResource( OpenCms.getWorkplaceManager().getExplorerTypeSetting("unknown"), null); title = type.getTypeName(); subtitle = type.getTypeName() + " (ID: " + type.getTypeId() + ")"; } CmsResourceInfo info = new CmsResourceInfo(title, subtitle, icon); return info; }
java
@SuppressWarnings("deprecation") CmsResourceInfo formatResourceType(I_CmsResourceType type) { CmsExplorerTypeSettings settings = OpenCms.getWorkplaceManager().getExplorerTypeSetting(type.getTypeName()); Resource icon; String title; String subtitle; if (settings != null) { icon = CmsResourceUtil.getBigIconResource(settings, null); title = CmsVaadinUtils.getMessageText(settings.getKey()); if (title.startsWith("???")) { title = type.getTypeName(); } subtitle = type.getTypeName() + " (ID: " + type.getTypeId() + (settings.getReference() != null ? (", " + settings.getReference()) : "") + ")"; } else { icon = CmsResourceUtil.getBigIconResource( OpenCms.getWorkplaceManager().getExplorerTypeSetting("unknown"), null); title = type.getTypeName(); subtitle = type.getTypeName() + " (ID: " + type.getTypeId() + ")"; } CmsResourceInfo info = new CmsResourceInfo(title, subtitle, icon); return info; }
[ "@", "SuppressWarnings", "(", "\"deprecation\"", ")", "CmsResourceInfo", "formatResourceType", "(", "I_CmsResourceType", "type", ")", "{", "CmsExplorerTypeSettings", "settings", "=", "OpenCms", ".", "getWorkplaceManager", "(", ")", ".", "getExplorerTypeSetting", "(", "type", ".", "getTypeName", "(", ")", ")", ";", "Resource", "icon", ";", "String", "title", ";", "String", "subtitle", ";", "if", "(", "settings", "!=", "null", ")", "{", "icon", "=", "CmsResourceUtil", ".", "getBigIconResource", "(", "settings", ",", "null", ")", ";", "title", "=", "CmsVaadinUtils", ".", "getMessageText", "(", "settings", ".", "getKey", "(", ")", ")", ";", "if", "(", "title", ".", "startsWith", "(", "\"???\"", ")", ")", "{", "title", "=", "type", ".", "getTypeName", "(", ")", ";", "}", "subtitle", "=", "type", ".", "getTypeName", "(", ")", "+", "\" (ID: \"", "+", "type", ".", "getTypeId", "(", ")", "+", "(", "settings", ".", "getReference", "(", ")", "!=", "null", "?", "(", "\", \"", "+", "settings", ".", "getReference", "(", ")", ")", ":", "\"\"", ")", "+", "\")\"", ";", "}", "else", "{", "icon", "=", "CmsResourceUtil", ".", "getBigIconResource", "(", "OpenCms", ".", "getWorkplaceManager", "(", ")", ".", "getExplorerTypeSetting", "(", "\"unknown\"", ")", ",", "null", ")", ";", "title", "=", "type", ".", "getTypeName", "(", ")", ";", "subtitle", "=", "type", ".", "getTypeName", "(", ")", "+", "\" (ID: \"", "+", "type", ".", "getTypeId", "(", ")", "+", "\")\"", ";", "}", "CmsResourceInfo", "info", "=", "new", "CmsResourceInfo", "(", "title", ",", "subtitle", ",", "icon", ")", ";", "return", "info", ";", "}" ]
Creates the resource info box for a resource type.<p> @param type the resource type @return the resource info box
[ "Creates", "the", "resource", "info", "box", "for", "a", "resource", "type", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/apps/modules/CmsModuleInfoDialog.java#L172-L199
sarl/sarl
sre/io.janusproject/io.janusproject.plugin/src/io/janusproject/kernel/space/AbstractEventSpace.java
AbstractEventSpace.doEmit
protected void doEmit(Event event, Scope<? super Address> scope) { """ Do the emission of the event. <p>This function emits the event <strong>only on the internal event bus</strong> of the agents. @param event the event to emit. @param scope description of the scope of the event, i.e. the receivers of the event. """ assert scope != null; assert event != null; final UniqueAddressParticipantRepository<Address> particips = getParticipantInternalDataStructure(); final SynchronizedCollection<EventListener> listeners = particips.getListeners(); synchronized (listeners.mutex()) { for (final EventListener listener : listeners) { final Address adr = getAddress(listener); if (scope.matches(adr)) { this.executorService.submit(new AsyncRunner(listener, event)); } } } }
java
protected void doEmit(Event event, Scope<? super Address> scope) { assert scope != null; assert event != null; final UniqueAddressParticipantRepository<Address> particips = getParticipantInternalDataStructure(); final SynchronizedCollection<EventListener> listeners = particips.getListeners(); synchronized (listeners.mutex()) { for (final EventListener listener : listeners) { final Address adr = getAddress(listener); if (scope.matches(adr)) { this.executorService.submit(new AsyncRunner(listener, event)); } } } }
[ "protected", "void", "doEmit", "(", "Event", "event", ",", "Scope", "<", "?", "super", "Address", ">", "scope", ")", "{", "assert", "scope", "!=", "null", ";", "assert", "event", "!=", "null", ";", "final", "UniqueAddressParticipantRepository", "<", "Address", ">", "particips", "=", "getParticipantInternalDataStructure", "(", ")", ";", "final", "SynchronizedCollection", "<", "EventListener", ">", "listeners", "=", "particips", ".", "getListeners", "(", ")", ";", "synchronized", "(", "listeners", ".", "mutex", "(", ")", ")", "{", "for", "(", "final", "EventListener", "listener", ":", "listeners", ")", "{", "final", "Address", "adr", "=", "getAddress", "(", "listener", ")", ";", "if", "(", "scope", ".", "matches", "(", "adr", ")", ")", "{", "this", ".", "executorService", ".", "submit", "(", "new", "AsyncRunner", "(", "listener", ",", "event", ")", ")", ";", "}", "}", "}", "}" ]
Do the emission of the event. <p>This function emits the event <strong>only on the internal event bus</strong> of the agents. @param event the event to emit. @param scope description of the scope of the event, i.e. the receivers of the event.
[ "Do", "the", "emission", "of", "the", "event", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/sre/io.janusproject/io.janusproject.plugin/src/io/janusproject/kernel/space/AbstractEventSpace.java#L172-L185
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/ICUData.java
ICUData.getRequiredStream
public static InputStream getRequiredStream(Class<?> root, String resourceName) { """ Convenience method that calls getStream(root, resourceName, true). @throws MissingResourceException if the resource could not be found """ return getStream(root, resourceName, true); }
java
public static InputStream getRequiredStream(Class<?> root, String resourceName) { return getStream(root, resourceName, true); }
[ "public", "static", "InputStream", "getRequiredStream", "(", "Class", "<", "?", ">", "root", ",", "String", "resourceName", ")", "{", "return", "getStream", "(", "root", ",", "resourceName", ",", "true", ")", ";", "}" ]
Convenience method that calls getStream(root, resourceName, true). @throws MissingResourceException if the resource could not be found
[ "Convenience", "method", "that", "calls", "getStream", "(", "root", "resourceName", "true", ")", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/ICUData.java#L221-L223
WiQuery/wiquery
wiquery-jquery-ui/src/main/java/org/odlabs/wiquery/ui/slider/SliderAnimate.java
SliderAnimate.setParam
private void setParam(Boolean booleanParam, AnimateEnum animateEnumParam, Number numberParam) { """ Method setting the right parameter @param booleanParam Boolean parameter @param animateEnumParam AnimateEnum parameter @param numberParam Number param """ this.booleanParam = booleanParam; this.animateEnumParam = animateEnumParam; this.numberParam = numberParam; }
java
private void setParam(Boolean booleanParam, AnimateEnum animateEnumParam, Number numberParam) { this.booleanParam = booleanParam; this.animateEnumParam = animateEnumParam; this.numberParam = numberParam; }
[ "private", "void", "setParam", "(", "Boolean", "booleanParam", ",", "AnimateEnum", "animateEnumParam", ",", "Number", "numberParam", ")", "{", "this", ".", "booleanParam", "=", "booleanParam", ";", "this", ".", "animateEnumParam", "=", "animateEnumParam", ";", "this", ".", "numberParam", "=", "numberParam", ";", "}" ]
Method setting the right parameter @param booleanParam Boolean parameter @param animateEnumParam AnimateEnum parameter @param numberParam Number param
[ "Method", "setting", "the", "right", "parameter" ]
train
https://github.com/WiQuery/wiquery/blob/1b8d60c7a3c37b90fd68c9cd0ff97178fcbcbb08/wiquery-jquery-ui/src/main/java/org/odlabs/wiquery/ui/slider/SliderAnimate.java#L213-L218
QSFT/Doradus
doradus-common/src/main/java/com/dell/doradus/common/Utils.java
Utils.formatDate
public static String formatDate(Calendar date, int precision) { """ Format a Calendar date with a given precision. 'precision' must be a Calendar "field" value such as Calendar.MINUTE. The allowed precisions and the corresponding string formats returned are: <pre> Calendar.MILLISECOND: YYYY-MM-DD hh:mm:ss.SSS Calendar.SECOND: YYYY-MM-DD hh:mm:ss Calendar.MINUTE: YYYY-MM-DD hh:mm Calendar.HOUR: YYYY-MM-DD hh Calendar.DATE: YYYY-MM-DD Calendar.MONTH: YYYY-MM Calendar.YEAR: YYYY </pre> Note that Calendar.DAY_OF_MONTH is a synonym for Calendar.DATE. @param date Date as a Calendar to be formatted. @param precision Calendar field value of desired precision. @return String formatted to the requested precision. """ assert date != null; // Remember that the bloody month field is zero-relative! switch (precision) { case Calendar.MILLISECOND: // YYYY-MM-DD hh:mm:ss.SSS return String.format("%04d-%02d-%02d %02d:%02d:%02d.%03d", date.get(Calendar.YEAR), date.get(Calendar.MONTH)+1, date.get(Calendar.DAY_OF_MONTH), date.get(Calendar.HOUR_OF_DAY), date.get(Calendar.MINUTE), date.get(Calendar.SECOND), date.get(Calendar.MILLISECOND)); case Calendar.SECOND: // YYYY-MM-DD hh:mm:ss return String.format("%04d-%02d-%02d %02d:%02d:%02d", date.get(Calendar.YEAR), date.get(Calendar.MONTH)+1, date.get(Calendar.DAY_OF_MONTH), date.get(Calendar.HOUR_OF_DAY), date.get(Calendar.MINUTE), date.get(Calendar.SECOND)); case Calendar.MINUTE: // YYYY-MM-DD hh:mm return String.format("%04d-%02d-%02d %02d:%02d", date.get(Calendar.YEAR), date.get(Calendar.MONTH)+1, date.get(Calendar.DAY_OF_MONTH), date.get(Calendar.HOUR_OF_DAY), date.get(Calendar.MINUTE)); case Calendar.HOUR: // YYYY-MM-DD hh return String.format("%04d-%02d-%02d %02d", date.get(Calendar.YEAR), date.get(Calendar.MONTH)+1, date.get(Calendar.DAY_OF_MONTH), date.get(Calendar.HOUR_OF_DAY)); case Calendar.DATE: // YYYY-MM-DD return String.format("%04d-%02d-%02d", date.get(Calendar.YEAR), date.get(Calendar.MONTH)+1, date.get(Calendar.DAY_OF_MONTH)); case Calendar.MONTH: // YYYY-MM return String.format("%04d-%02d", date.get(Calendar.YEAR), date.get(Calendar.MONTH)+1); case Calendar.YEAR: // YYYY return String.format("%04d", date.get(Calendar.YEAR)); } throw new IllegalArgumentException("Unknown precision: " + precision); }
java
public static String formatDate(Calendar date, int precision) { assert date != null; // Remember that the bloody month field is zero-relative! switch (precision) { case Calendar.MILLISECOND: // YYYY-MM-DD hh:mm:ss.SSS return String.format("%04d-%02d-%02d %02d:%02d:%02d.%03d", date.get(Calendar.YEAR), date.get(Calendar.MONTH)+1, date.get(Calendar.DAY_OF_MONTH), date.get(Calendar.HOUR_OF_DAY), date.get(Calendar.MINUTE), date.get(Calendar.SECOND), date.get(Calendar.MILLISECOND)); case Calendar.SECOND: // YYYY-MM-DD hh:mm:ss return String.format("%04d-%02d-%02d %02d:%02d:%02d", date.get(Calendar.YEAR), date.get(Calendar.MONTH)+1, date.get(Calendar.DAY_OF_MONTH), date.get(Calendar.HOUR_OF_DAY), date.get(Calendar.MINUTE), date.get(Calendar.SECOND)); case Calendar.MINUTE: // YYYY-MM-DD hh:mm return String.format("%04d-%02d-%02d %02d:%02d", date.get(Calendar.YEAR), date.get(Calendar.MONTH)+1, date.get(Calendar.DAY_OF_MONTH), date.get(Calendar.HOUR_OF_DAY), date.get(Calendar.MINUTE)); case Calendar.HOUR: // YYYY-MM-DD hh return String.format("%04d-%02d-%02d %02d", date.get(Calendar.YEAR), date.get(Calendar.MONTH)+1, date.get(Calendar.DAY_OF_MONTH), date.get(Calendar.HOUR_OF_DAY)); case Calendar.DATE: // YYYY-MM-DD return String.format("%04d-%02d-%02d", date.get(Calendar.YEAR), date.get(Calendar.MONTH)+1, date.get(Calendar.DAY_OF_MONTH)); case Calendar.MONTH: // YYYY-MM return String.format("%04d-%02d", date.get(Calendar.YEAR), date.get(Calendar.MONTH)+1); case Calendar.YEAR: // YYYY return String.format("%04d", date.get(Calendar.YEAR)); } throw new IllegalArgumentException("Unknown precision: " + precision); }
[ "public", "static", "String", "formatDate", "(", "Calendar", "date", ",", "int", "precision", ")", "{", "assert", "date", "!=", "null", ";", "// Remember that the bloody month field is zero-relative!\r", "switch", "(", "precision", ")", "{", "case", "Calendar", ".", "MILLISECOND", ":", "// YYYY-MM-DD hh:mm:ss.SSS\r", "return", "String", ".", "format", "(", "\"%04d-%02d-%02d %02d:%02d:%02d.%03d\"", ",", "date", ".", "get", "(", "Calendar", ".", "YEAR", ")", ",", "date", ".", "get", "(", "Calendar", ".", "MONTH", ")", "+", "1", ",", "date", ".", "get", "(", "Calendar", ".", "DAY_OF_MONTH", ")", ",", "date", ".", "get", "(", "Calendar", ".", "HOUR_OF_DAY", ")", ",", "date", ".", "get", "(", "Calendar", ".", "MINUTE", ")", ",", "date", ".", "get", "(", "Calendar", ".", "SECOND", ")", ",", "date", ".", "get", "(", "Calendar", ".", "MILLISECOND", ")", ")", ";", "case", "Calendar", ".", "SECOND", ":", "// YYYY-MM-DD hh:mm:ss\r", "return", "String", ".", "format", "(", "\"%04d-%02d-%02d %02d:%02d:%02d\"", ",", "date", ".", "get", "(", "Calendar", ".", "YEAR", ")", ",", "date", ".", "get", "(", "Calendar", ".", "MONTH", ")", "+", "1", ",", "date", ".", "get", "(", "Calendar", ".", "DAY_OF_MONTH", ")", ",", "date", ".", "get", "(", "Calendar", ".", "HOUR_OF_DAY", ")", ",", "date", ".", "get", "(", "Calendar", ".", "MINUTE", ")", ",", "date", ".", "get", "(", "Calendar", ".", "SECOND", ")", ")", ";", "case", "Calendar", ".", "MINUTE", ":", "// YYYY-MM-DD hh:mm\r", "return", "String", ".", "format", "(", "\"%04d-%02d-%02d %02d:%02d\"", ",", "date", ".", "get", "(", "Calendar", ".", "YEAR", ")", ",", "date", ".", "get", "(", "Calendar", ".", "MONTH", ")", "+", "1", ",", "date", ".", "get", "(", "Calendar", ".", "DAY_OF_MONTH", ")", ",", "date", ".", "get", "(", "Calendar", ".", "HOUR_OF_DAY", ")", ",", "date", ".", "get", "(", "Calendar", ".", "MINUTE", ")", ")", ";", "case", "Calendar", ".", "HOUR", ":", "// YYYY-MM-DD hh\r", "return", "String", ".", "format", "(", "\"%04d-%02d-%02d %02d\"", ",", "date", ".", "get", "(", "Calendar", ".", "YEAR", ")", ",", "date", ".", "get", "(", "Calendar", ".", "MONTH", ")", "+", "1", ",", "date", ".", "get", "(", "Calendar", ".", "DAY_OF_MONTH", ")", ",", "date", ".", "get", "(", "Calendar", ".", "HOUR_OF_DAY", ")", ")", ";", "case", "Calendar", ".", "DATE", ":", "// YYYY-MM-DD\r", "return", "String", ".", "format", "(", "\"%04d-%02d-%02d\"", ",", "date", ".", "get", "(", "Calendar", ".", "YEAR", ")", ",", "date", ".", "get", "(", "Calendar", ".", "MONTH", ")", "+", "1", ",", "date", ".", "get", "(", "Calendar", ".", "DAY_OF_MONTH", ")", ")", ";", "case", "Calendar", ".", "MONTH", ":", "// YYYY-MM\r", "return", "String", ".", "format", "(", "\"%04d-%02d\"", ",", "date", ".", "get", "(", "Calendar", ".", "YEAR", ")", ",", "date", ".", "get", "(", "Calendar", ".", "MONTH", ")", "+", "1", ")", ";", "case", "Calendar", ".", "YEAR", ":", "// YYYY\r", "return", "String", ".", "format", "(", "\"%04d\"", ",", "date", ".", "get", "(", "Calendar", ".", "YEAR", ")", ")", ";", "}", "throw", "new", "IllegalArgumentException", "(", "\"Unknown precision: \"", "+", "precision", ")", ";", "}" ]
Format a Calendar date with a given precision. 'precision' must be a Calendar "field" value such as Calendar.MINUTE. The allowed precisions and the corresponding string formats returned are: <pre> Calendar.MILLISECOND: YYYY-MM-DD hh:mm:ss.SSS Calendar.SECOND: YYYY-MM-DD hh:mm:ss Calendar.MINUTE: YYYY-MM-DD hh:mm Calendar.HOUR: YYYY-MM-DD hh Calendar.DATE: YYYY-MM-DD Calendar.MONTH: YYYY-MM Calendar.YEAR: YYYY </pre> Note that Calendar.DAY_OF_MONTH is a synonym for Calendar.DATE. @param date Date as a Calendar to be formatted. @param precision Calendar field value of desired precision. @return String formatted to the requested precision.
[ "Format", "a", "Calendar", "date", "with", "a", "given", "precision", ".", "precision", "must", "be", "a", "Calendar", "field", "value", "such", "as", "Calendar", ".", "MINUTE", ".", "The", "allowed", "precisions", "and", "the", "corresponding", "string", "formats", "returned", "are", ":", "<pre", ">", "Calendar", ".", "MILLISECOND", ":", "YYYY", "-", "MM", "-", "DD", "hh", ":", "mm", ":", "ss", ".", "SSS", "Calendar", ".", "SECOND", ":", "YYYY", "-", "MM", "-", "DD", "hh", ":", "mm", ":", "ss", "Calendar", ".", "MINUTE", ":", "YYYY", "-", "MM", "-", "DD", "hh", ":", "mm", "Calendar", ".", "HOUR", ":", "YYYY", "-", "MM", "-", "DD", "hh", "Calendar", ".", "DATE", ":", "YYYY", "-", "MM", "-", "DD", "Calendar", ".", "MONTH", ":", "YYYY", "-", "MM", "Calendar", ".", "YEAR", ":", "YYYY", "<", "/", "pre", ">", "Note", "that", "Calendar", ".", "DAY_OF_MONTH", "is", "a", "synonym", "for", "Calendar", ".", "DATE", "." ]
train
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-common/src/main/java/com/dell/doradus/common/Utils.java#L705-L743
facebookarchive/hadoop-20
src/core/org/apache/hadoop/net/NetUtils.java
NetUtils.getServerAddress
@Deprecated public static String getServerAddress(Configuration conf, String oldBindAddressName, String oldPortName, String newBindAddressName) { """ Handle the transition from pairs of attributes specifying a host and port to a single colon separated one. @param conf the configuration to check @param oldBindAddressName the old address attribute name @param oldPortName the old port attribute name @param newBindAddressName the new combined name @return the complete address from the configuration """ String oldAddr = conf.get(oldBindAddressName); int oldPort = conf.getInt(oldPortName, 0); String newAddrPort = conf.get(newBindAddressName); if (oldAddr == null && oldPort == 0) { return toIpPort(createSocketAddr(newAddrPort)); } InetSocketAddress newAddr = NetUtils.createSocketAddr(newAddrPort); if (oldAddr == null) { oldAddr = newAddr.getAddress().getHostAddress(); } else { LOG.warn("Configuration parameter " + oldBindAddressName + " is deprecated. Use " + newBindAddressName + " instead."); } if (oldPort == 0) { oldPort = newAddr.getPort(); } else { LOG.warn("Configuration parameter " + oldPortName + " is deprecated. Use " + newBindAddressName + " instead."); } try { return toIpPort(oldAddr, oldPort); } catch (UnknownHostException e) { LOG.error("DNS not supported."); LOG.fatal(e); } return oldAddr + ":" + oldPort; }
java
@Deprecated public static String getServerAddress(Configuration conf, String oldBindAddressName, String oldPortName, String newBindAddressName) { String oldAddr = conf.get(oldBindAddressName); int oldPort = conf.getInt(oldPortName, 0); String newAddrPort = conf.get(newBindAddressName); if (oldAddr == null && oldPort == 0) { return toIpPort(createSocketAddr(newAddrPort)); } InetSocketAddress newAddr = NetUtils.createSocketAddr(newAddrPort); if (oldAddr == null) { oldAddr = newAddr.getAddress().getHostAddress(); } else { LOG.warn("Configuration parameter " + oldBindAddressName + " is deprecated. Use " + newBindAddressName + " instead."); } if (oldPort == 0) { oldPort = newAddr.getPort(); } else { LOG.warn("Configuration parameter " + oldPortName + " is deprecated. Use " + newBindAddressName + " instead."); } try { return toIpPort(oldAddr, oldPort); } catch (UnknownHostException e) { LOG.error("DNS not supported."); LOG.fatal(e); } return oldAddr + ":" + oldPort; }
[ "@", "Deprecated", "public", "static", "String", "getServerAddress", "(", "Configuration", "conf", ",", "String", "oldBindAddressName", ",", "String", "oldPortName", ",", "String", "newBindAddressName", ")", "{", "String", "oldAddr", "=", "conf", ".", "get", "(", "oldBindAddressName", ")", ";", "int", "oldPort", "=", "conf", ".", "getInt", "(", "oldPortName", ",", "0", ")", ";", "String", "newAddrPort", "=", "conf", ".", "get", "(", "newBindAddressName", ")", ";", "if", "(", "oldAddr", "==", "null", "&&", "oldPort", "==", "0", ")", "{", "return", "toIpPort", "(", "createSocketAddr", "(", "newAddrPort", ")", ")", ";", "}", "InetSocketAddress", "newAddr", "=", "NetUtils", ".", "createSocketAddr", "(", "newAddrPort", ")", ";", "if", "(", "oldAddr", "==", "null", ")", "{", "oldAddr", "=", "newAddr", ".", "getAddress", "(", ")", ".", "getHostAddress", "(", ")", ";", "}", "else", "{", "LOG", ".", "warn", "(", "\"Configuration parameter \"", "+", "oldBindAddressName", "+", "\" is deprecated. Use \"", "+", "newBindAddressName", "+", "\" instead.\"", ")", ";", "}", "if", "(", "oldPort", "==", "0", ")", "{", "oldPort", "=", "newAddr", ".", "getPort", "(", ")", ";", "}", "else", "{", "LOG", ".", "warn", "(", "\"Configuration parameter \"", "+", "oldPortName", "+", "\" is deprecated. Use \"", "+", "newBindAddressName", "+", "\" instead.\"", ")", ";", "}", "try", "{", "return", "toIpPort", "(", "oldAddr", ",", "oldPort", ")", ";", "}", "catch", "(", "UnknownHostException", "e", ")", "{", "LOG", ".", "error", "(", "\"DNS not supported.\"", ")", ";", "LOG", ".", "fatal", "(", "e", ")", ";", "}", "return", "oldAddr", "+", "\":\"", "+", "oldPort", ";", "}" ]
Handle the transition from pairs of attributes specifying a host and port to a single colon separated one. @param conf the configuration to check @param oldBindAddressName the old address attribute name @param oldPortName the old port attribute name @param newBindAddressName the new combined name @return the complete address from the configuration
[ "Handle", "the", "transition", "from", "pairs", "of", "attributes", "specifying", "a", "host", "and", "port", "to", "a", "single", "colon", "separated", "one", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/net/NetUtils.java#L194-L225
OpenLiberty/open-liberty
dev/com.ibm.ws.jdbc/src/com/ibm/ws/rsadapter/impl/WSConnectionRequestInfoImpl.java
WSConnectionRequestInfoImpl.isReconfigurable
public final boolean isReconfigurable(WSConnectionRequestInfoImpl cri, boolean reauth) { """ Indicates whether a Connection with this CRI may be reconfigured to the specific CRI. @param cri The CRI to test against. @return true if a connection with the CRI represented by this class can be reconfigured to the specified CRI. """ // The CRI is only reconfigurable if all fields which cannot be changed already match. // Although sharding keys can sometimes be changed via connection.setShardingKey, // the spec does not guarantee that this method will allow all sharding keys // (even ones that are known to be valid) to be set on any connection. It leaves open // the possibility that the JDBC driver implementation can decide not to allow switching // between certain sharding keys. Given that we don't have any way of knowing in // advance that a switching will be accepted (without preemptively trying to change it), // we must consider sharding keys to be non-reconfigurable for the purposes of // selecting a connection from the pool. if (reauth) { return ivConfigID == cri.ivConfigID; } else { return match(ivUserName, cri.ivUserName) && match(ivPassword, cri.ivPassword) && match(ivShardingKey, cri.ivShardingKey) && match(ivSuperShardingKey, cri.ivSuperShardingKey) && ivConfigID == cri.ivConfigID; } }
java
public final boolean isReconfigurable(WSConnectionRequestInfoImpl cri, boolean reauth) { // The CRI is only reconfigurable if all fields which cannot be changed already match. // Although sharding keys can sometimes be changed via connection.setShardingKey, // the spec does not guarantee that this method will allow all sharding keys // (even ones that are known to be valid) to be set on any connection. It leaves open // the possibility that the JDBC driver implementation can decide not to allow switching // between certain sharding keys. Given that we don't have any way of knowing in // advance that a switching will be accepted (without preemptively trying to change it), // we must consider sharding keys to be non-reconfigurable for the purposes of // selecting a connection from the pool. if (reauth) { return ivConfigID == cri.ivConfigID; } else { return match(ivUserName, cri.ivUserName) && match(ivPassword, cri.ivPassword) && match(ivShardingKey, cri.ivShardingKey) && match(ivSuperShardingKey, cri.ivSuperShardingKey) && ivConfigID == cri.ivConfigID; } }
[ "public", "final", "boolean", "isReconfigurable", "(", "WSConnectionRequestInfoImpl", "cri", ",", "boolean", "reauth", ")", "{", "// The CRI is only reconfigurable if all fields which cannot be changed already match.", "// Although sharding keys can sometimes be changed via connection.setShardingKey,", "// the spec does not guarantee that this method will allow all sharding keys", "// (even ones that are known to be valid) to be set on any connection. It leaves open", "// the possibility that the JDBC driver implementation can decide not to allow switching", "// between certain sharding keys. Given that we don't have any way of knowing in", "// advance that a switching will be accepted (without preemptively trying to change it),", "// we must consider sharding keys to be non-reconfigurable for the purposes of", "// selecting a connection from the pool.", "if", "(", "reauth", ")", "{", "return", "ivConfigID", "==", "cri", ".", "ivConfigID", ";", "}", "else", "{", "return", "match", "(", "ivUserName", ",", "cri", ".", "ivUserName", ")", "&&", "match", "(", "ivPassword", ",", "cri", ".", "ivPassword", ")", "&&", "match", "(", "ivShardingKey", ",", "cri", ".", "ivShardingKey", ")", "&&", "match", "(", "ivSuperShardingKey", ",", "cri", ".", "ivSuperShardingKey", ")", "&&", "ivConfigID", "==", "cri", ".", "ivConfigID", ";", "}", "}" ]
Indicates whether a Connection with this CRI may be reconfigured to the specific CRI. @param cri The CRI to test against. @return true if a connection with the CRI represented by this class can be reconfigured to the specified CRI.
[ "Indicates", "whether", "a", "Connection", "with", "this", "CRI", "may", "be", "reconfigured", "to", "the", "specific", "CRI", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jdbc/src/com/ibm/ws/rsadapter/impl/WSConnectionRequestInfoImpl.java#L419-L442
dwdyer/reportng
reportng/src/java/main/org/uncommons/reportng/HTMLReporter.java
HTMLReporter.createLog
private void createLog(File outputDirectory, boolean onlyFailures) throws Exception { """ Generate a groups list for each suite. @param outputDirectory The target directory for the generated file(s). """ if (!Reporter.getOutput().isEmpty()) { VelocityContext context = createContext(); context.put(ONLY_FAILURES_KEY, onlyFailures); generateFile(new File(outputDirectory, OUTPUT_FILE), OUTPUT_FILE + TEMPLATE_EXTENSION, context); } }
java
private void createLog(File outputDirectory, boolean onlyFailures) throws Exception { if (!Reporter.getOutput().isEmpty()) { VelocityContext context = createContext(); context.put(ONLY_FAILURES_KEY, onlyFailures); generateFile(new File(outputDirectory, OUTPUT_FILE), OUTPUT_FILE + TEMPLATE_EXTENSION, context); } }
[ "private", "void", "createLog", "(", "File", "outputDirectory", ",", "boolean", "onlyFailures", ")", "throws", "Exception", "{", "if", "(", "!", "Reporter", ".", "getOutput", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "VelocityContext", "context", "=", "createContext", "(", ")", ";", "context", ".", "put", "(", "ONLY_FAILURES_KEY", ",", "onlyFailures", ")", ";", "generateFile", "(", "new", "File", "(", "outputDirectory", ",", "OUTPUT_FILE", ")", ",", "OUTPUT_FILE", "+", "TEMPLATE_EXTENSION", ",", "context", ")", ";", "}", "}" ]
Generate a groups list for each suite. @param outputDirectory The target directory for the generated file(s).
[ "Generate", "a", "groups", "list", "for", "each", "suite", "." ]
train
https://github.com/dwdyer/reportng/blob/df11f9cd9ab3fb5847fbba94ed3098ae0448f770/reportng/src/java/main/org/uncommons/reportng/HTMLReporter.java#L259-L269
signit-wesign/java-sdk
src/main/java/cn/signit/sdk/util/FastjsonEncoder.java
FastjsonEncoder.encodeAsString
public static String encodeAsString(Object obj,NamingStyle namingStyle,boolean useUnicode) { """ 将指定java对象序列化成相应字符串 @param obj java对象 @param namingStyle 命名风格 @param useUnicode 是否使用unicode编码(当有中文字段时) @return 序列化后的json字符串 @author Zhanghongdong """ SerializeConfig config = SerializeConfig.getGlobalInstance(); config.propertyNamingStrategy = getNamingStrategy(namingStyle); if(useUnicode){ return JSON.toJSONString(obj,config, SerializerFeature.BrowserCompatible, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.NotWriteDefaultValue ); } return JSON.toJSONString(obj,config); }
java
public static String encodeAsString(Object obj,NamingStyle namingStyle,boolean useUnicode){ SerializeConfig config = SerializeConfig.getGlobalInstance(); config.propertyNamingStrategy = getNamingStrategy(namingStyle); if(useUnicode){ return JSON.toJSONString(obj,config, SerializerFeature.BrowserCompatible, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.NotWriteDefaultValue ); } return JSON.toJSONString(obj,config); }
[ "public", "static", "String", "encodeAsString", "(", "Object", "obj", ",", "NamingStyle", "namingStyle", ",", "boolean", "useUnicode", ")", "{", "SerializeConfig", "config", "=", "SerializeConfig", ".", "getGlobalInstance", "(", ")", ";", "config", ".", "propertyNamingStrategy", "=", "getNamingStrategy", "(", "namingStyle", ")", ";", "if", "(", "useUnicode", ")", "{", "return", "JSON", ".", "toJSONString", "(", "obj", ",", "config", ",", "SerializerFeature", ".", "BrowserCompatible", ",", "SerializerFeature", ".", "WriteNullListAsEmpty", ",", "SerializerFeature", ".", "NotWriteDefaultValue", ")", ";", "}", "return", "JSON", ".", "toJSONString", "(", "obj", ",", "config", ")", ";", "}" ]
将指定java对象序列化成相应字符串 @param obj java对象 @param namingStyle 命名风格 @param useUnicode 是否使用unicode编码(当有中文字段时) @return 序列化后的json字符串 @author Zhanghongdong
[ "将指定java对象序列化成相应字符串" ]
train
https://github.com/signit-wesign/java-sdk/blob/6f3196c9d444818a953396fdaa8ffed9794d9530/src/main/java/cn/signit/sdk/util/FastjsonEncoder.java#L20-L31
wcm-io-caravan/caravan-hal
resource/src/main/java/io/wcm/caravan/hal/resource/HalResourceFactory.java
HalResourceFactory.getStateAsObject
@Deprecated public static <T> T getStateAsObject(HalResource halResource, Class<T> type) { """ Converts the JSON model to an object of the given type. @param halResource HAL resource with model to convert @param type Type of the requested object @param <T> Output type @return State as object @deprecated use {@link HalResource#adaptTo(Class)} """ return halResource.adaptTo(type); }
java
@Deprecated public static <T> T getStateAsObject(HalResource halResource, Class<T> type) { return halResource.adaptTo(type); }
[ "@", "Deprecated", "public", "static", "<", "T", ">", "T", "getStateAsObject", "(", "HalResource", "halResource", ",", "Class", "<", "T", ">", "type", ")", "{", "return", "halResource", ".", "adaptTo", "(", "type", ")", ";", "}" ]
Converts the JSON model to an object of the given type. @param halResource HAL resource with model to convert @param type Type of the requested object @param <T> Output type @return State as object @deprecated use {@link HalResource#adaptTo(Class)}
[ "Converts", "the", "JSON", "model", "to", "an", "object", "of", "the", "given", "type", "." ]
train
https://github.com/wcm-io-caravan/caravan-hal/blob/25d58756b58c70c8c48a17fe781e673dd93d5085/resource/src/main/java/io/wcm/caravan/hal/resource/HalResourceFactory.java#L104-L107
phax/ph-pdf-layout
src/main/java/com/helger/pdflayout4/pdfbox/PDPageContentStreamExt.java
PDPageContentStreamExt.setLineDashPattern
public void setLineDashPattern (final float [] pattern, final float phase) throws IOException { """ Set the line dash pattern. @param pattern The pattern array @param phase The phase of the pattern @throws IOException If the content stream could not be written. @throws IllegalStateException If the method was called within a text block. """ if (inTextMode) { throw new IllegalStateException ("Error: setLineDashPattern is not allowed within a text block."); } write ((byte) '['); for (final float value : pattern) { writeOperand (value); } write ((byte) ']', (byte) ' '); writeOperand (phase); writeOperator ((byte) 'd'); }
java
public void setLineDashPattern (final float [] pattern, final float phase) throws IOException { if (inTextMode) { throw new IllegalStateException ("Error: setLineDashPattern is not allowed within a text block."); } write ((byte) '['); for (final float value : pattern) { writeOperand (value); } write ((byte) ']', (byte) ' '); writeOperand (phase); writeOperator ((byte) 'd'); }
[ "public", "void", "setLineDashPattern", "(", "final", "float", "[", "]", "pattern", ",", "final", "float", "phase", ")", "throws", "IOException", "{", "if", "(", "inTextMode", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Error: setLineDashPattern is not allowed within a text block.\"", ")", ";", "}", "write", "(", "(", "byte", ")", "'", "'", ")", ";", "for", "(", "final", "float", "value", ":", "pattern", ")", "{", "writeOperand", "(", "value", ")", ";", "}", "write", "(", "(", "byte", ")", "'", "'", ",", "(", "byte", ")", "'", "'", ")", ";", "writeOperand", "(", "phase", ")", ";", "writeOperator", "(", "(", "byte", ")", "'", "'", ")", ";", "}" ]
Set the line dash pattern. @param pattern The pattern array @param phase The phase of the pattern @throws IOException If the content stream could not be written. @throws IllegalStateException If the method was called within a text block.
[ "Set", "the", "line", "dash", "pattern", "." ]
train
https://github.com/phax/ph-pdf-layout/blob/777d9f3a131cbe8f592c0de1cf554084e541bb54/src/main/java/com/helger/pdflayout4/pdfbox/PDPageContentStreamExt.java#L1494-L1508
tango-controls/JTango
client/src/main/java/fr/soleil/tango/clientapi/util/TypeConversionUtil.java
TypeConversionUtil.getWritePart
public static Object getWritePart(final Object array, final AttrWriteType writeType) { """ Extract the write part of a scalar attribute @param array @param writeType @return """ if (writeType.equals(AttrWriteType.READ_WRITE)) { return Array.get(array, 1); } else { return Array.get(array, 0); } }
java
public static Object getWritePart(final Object array, final AttrWriteType writeType) { if (writeType.equals(AttrWriteType.READ_WRITE)) { return Array.get(array, 1); } else { return Array.get(array, 0); } }
[ "public", "static", "Object", "getWritePart", "(", "final", "Object", "array", ",", "final", "AttrWriteType", "writeType", ")", "{", "if", "(", "writeType", ".", "equals", "(", "AttrWriteType", ".", "READ_WRITE", ")", ")", "{", "return", "Array", ".", "get", "(", "array", ",", "1", ")", ";", "}", "else", "{", "return", "Array", ".", "get", "(", "array", ",", "0", ")", ";", "}", "}" ]
Extract the write part of a scalar attribute @param array @param writeType @return
[ "Extract", "the", "write", "part", "of", "a", "scalar", "attribute" ]
train
https://github.com/tango-controls/JTango/blob/1ccc9dcb83e6de2359a9f1906d170571cacf1345/client/src/main/java/fr/soleil/tango/clientapi/util/TypeConversionUtil.java#L35-L41
undertow-io/undertow
core/src/main/java/io/undertow/websockets/core/protocol/version07/UTF8Checker.java
UTF8Checker.checkUTF8
private void checkUTF8(ByteBuffer buf, int position, int length) throws UnsupportedEncodingException { """ Check if the given ByteBuffer contains non UTF-8 data. @param buf the ByteBuffer to check @param position the index in the {@link ByteBuffer} to start from @param length the number of bytes to operate on @throws UnsupportedEncodingException is thrown if non UTF-8 data is found """ int limit = position + length; for (int i = position; i < limit; i++) { checkUTF8(buf.get(i)); } }
java
private void checkUTF8(ByteBuffer buf, int position, int length) throws UnsupportedEncodingException { int limit = position + length; for (int i = position; i < limit; i++) { checkUTF8(buf.get(i)); } }
[ "private", "void", "checkUTF8", "(", "ByteBuffer", "buf", ",", "int", "position", ",", "int", "length", ")", "throws", "UnsupportedEncodingException", "{", "int", "limit", "=", "position", "+", "length", ";", "for", "(", "int", "i", "=", "position", ";", "i", "<", "limit", ";", "i", "++", ")", "{", "checkUTF8", "(", "buf", ".", "get", "(", "i", ")", ")", ";", "}", "}" ]
Check if the given ByteBuffer contains non UTF-8 data. @param buf the ByteBuffer to check @param position the index in the {@link ByteBuffer} to start from @param length the number of bytes to operate on @throws UnsupportedEncodingException is thrown if non UTF-8 data is found
[ "Check", "if", "the", "given", "ByteBuffer", "contains", "non", "UTF", "-", "8", "data", "." ]
train
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/websockets/core/protocol/version07/UTF8Checker.java#L78-L83
meraki-analytics/datapipelines-java
src/main/java/com/merakianalytics/datapipelines/TypeGraph.java
TypeGraph.getTransform
@SuppressWarnings("unchecked") // Generics are not the strong suit of Hipster4j. public ChainTransform getTransform(final Class from, final Class<?> to) { """ Attempts to find the best {@link com.merakianalytics.datapipelines.ChainTransform} to get from a type to another @param from the type to convert from @param to the type to convert to @return the best {@link com.merakianalytics.datapipelines.ChainTransform} between the types, or null if there is none """ if(from.equals(to)) { return ChainTransform.identity(to); } final SearchProblem problem = GraphSearchProblem.startingFrom(from).in(graph).extractCostFromEdges(new Function<DataTransformer, Double>() { @Override public Double apply(final DataTransformer transformer) { return new Double(transformer.cost()); } }).build(); final List<Class<?>> path = (List<Class<?>>)Hipster.createDijkstra(problem).search(to).getOptimalPaths().get(0); if(path == null || !path.get(path.size() - 1).equals(to)) { return null; } final List<DataTransformer> transform = new LinkedList<>(); for(int i = 1; i < path.size(); i++) { transform.add(cheapest.get(path.get(i - 1)).get(path.get(i))); } return new ChainTransform(from, to, path, transform); }
java
@SuppressWarnings("unchecked") // Generics are not the strong suit of Hipster4j. public ChainTransform getTransform(final Class from, final Class<?> to) { if(from.equals(to)) { return ChainTransform.identity(to); } final SearchProblem problem = GraphSearchProblem.startingFrom(from).in(graph).extractCostFromEdges(new Function<DataTransformer, Double>() { @Override public Double apply(final DataTransformer transformer) { return new Double(transformer.cost()); } }).build(); final List<Class<?>> path = (List<Class<?>>)Hipster.createDijkstra(problem).search(to).getOptimalPaths().get(0); if(path == null || !path.get(path.size() - 1).equals(to)) { return null; } final List<DataTransformer> transform = new LinkedList<>(); for(int i = 1; i < path.size(); i++) { transform.add(cheapest.get(path.get(i - 1)).get(path.get(i))); } return new ChainTransform(from, to, path, transform); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "// Generics are not the strong suit of Hipster4j.", "public", "ChainTransform", "getTransform", "(", "final", "Class", "from", ",", "final", "Class", "<", "?", ">", "to", ")", "{", "if", "(", "from", ".", "equals", "(", "to", ")", ")", "{", "return", "ChainTransform", ".", "identity", "(", "to", ")", ";", "}", "final", "SearchProblem", "problem", "=", "GraphSearchProblem", ".", "startingFrom", "(", "from", ")", ".", "in", "(", "graph", ")", ".", "extractCostFromEdges", "(", "new", "Function", "<", "DataTransformer", ",", "Double", ">", "(", ")", "{", "@", "Override", "public", "Double", "apply", "(", "final", "DataTransformer", "transformer", ")", "{", "return", "new", "Double", "(", "transformer", ".", "cost", "(", ")", ")", ";", "}", "}", ")", ".", "build", "(", ")", ";", "final", "List", "<", "Class", "<", "?", ">", ">", "path", "=", "(", "List", "<", "Class", "<", "?", ">", ">", ")", "Hipster", ".", "createDijkstra", "(", "problem", ")", ".", "search", "(", "to", ")", ".", "getOptimalPaths", "(", ")", ".", "get", "(", "0", ")", ";", "if", "(", "path", "==", "null", "||", "!", "path", ".", "get", "(", "path", ".", "size", "(", ")", "-", "1", ")", ".", "equals", "(", "to", ")", ")", "{", "return", "null", ";", "}", "final", "List", "<", "DataTransformer", ">", "transform", "=", "new", "LinkedList", "<>", "(", ")", ";", "for", "(", "int", "i", "=", "1", ";", "i", "<", "path", ".", "size", "(", ")", ";", "i", "++", ")", "{", "transform", ".", "add", "(", "cheapest", ".", "get", "(", "path", ".", "get", "(", "i", "-", "1", ")", ")", ".", "get", "(", "path", ".", "get", "(", "i", ")", ")", ")", ";", "}", "return", "new", "ChainTransform", "(", "from", ",", "to", ",", "path", ",", "transform", ")", ";", "}" ]
Attempts to find the best {@link com.merakianalytics.datapipelines.ChainTransform} to get from a type to another @param from the type to convert from @param to the type to convert to @return the best {@link com.merakianalytics.datapipelines.ChainTransform} between the types, or null if there is none
[ "Attempts", "to", "find", "the", "best", "{", "@link", "com", ".", "merakianalytics", ".", "datapipelines", ".", "ChainTransform", "}", "to", "get", "from", "a", "type", "to", "another" ]
train
https://github.com/meraki-analytics/datapipelines-java/blob/376ff1e8e1f7c67f2f2a5521d2a66e91467e56b0/src/main/java/com/merakianalytics/datapipelines/TypeGraph.java#L83-L106
jeremybrooks/jinx
src/main/java/net/jeremybrooks/jinx/api/ContactsApi.java
ContactsApi.getPublicList
public Contacts getPublicList(String userId, int page, int perPage) throws JinxException { """ Get the contact list for a user. <br> This method does not require authentication. @param userId Required. The NSID of the user to fetch the contact list for. @param page Optional. The page of results to return. If this argument is &le;= zero, it defaults to 1. @param perPage Optional. Number of photos to return per page. If this argument is &le;= zero, it defaults to 1000. The maximum allowed value is 1000. @return object containing contacts matching the parameters. @throws JinxException if required parameters are null or empty, or if there are any errors. @see <a href="https://www.flickr.com/services/api/flickr.contacts.getPublicList.html">flickr.contacts.getPublicList</a> """ JinxUtils.validateParams(userId); Map<String, String> params = new TreeMap<>(); params.put("method", "flickr.contacts.getPublicList"); params.put("user_id", userId); if (page > 0) { params.put("page", Integer.toString(page)); } if (perPage > 0) { params.put("per_page", Integer.toString(perPage)); } return jinx.flickrGet(params, Contacts.class); }
java
public Contacts getPublicList(String userId, int page, int perPage) throws JinxException { JinxUtils.validateParams(userId); Map<String, String> params = new TreeMap<>(); params.put("method", "flickr.contacts.getPublicList"); params.put("user_id", userId); if (page > 0) { params.put("page", Integer.toString(page)); } if (perPage > 0) { params.put("per_page", Integer.toString(perPage)); } return jinx.flickrGet(params, Contacts.class); }
[ "public", "Contacts", "getPublicList", "(", "String", "userId", ",", "int", "page", ",", "int", "perPage", ")", "throws", "JinxException", "{", "JinxUtils", ".", "validateParams", "(", "userId", ")", ";", "Map", "<", "String", ",", "String", ">", "params", "=", "new", "TreeMap", "<>", "(", ")", ";", "params", ".", "put", "(", "\"method\"", ",", "\"flickr.contacts.getPublicList\"", ")", ";", "params", ".", "put", "(", "\"user_id\"", ",", "userId", ")", ";", "if", "(", "page", ">", "0", ")", "{", "params", ".", "put", "(", "\"page\"", ",", "Integer", ".", "toString", "(", "page", ")", ")", ";", "}", "if", "(", "perPage", ">", "0", ")", "{", "params", ".", "put", "(", "\"per_page\"", ",", "Integer", ".", "toString", "(", "perPage", ")", ")", ";", "}", "return", "jinx", ".", "flickrGet", "(", "params", ",", "Contacts", ".", "class", ")", ";", "}" ]
Get the contact list for a user. <br> This method does not require authentication. @param userId Required. The NSID of the user to fetch the contact list for. @param page Optional. The page of results to return. If this argument is &le;= zero, it defaults to 1. @param perPage Optional. Number of photos to return per page. If this argument is &le;= zero, it defaults to 1000. The maximum allowed value is 1000. @return object containing contacts matching the parameters. @throws JinxException if required parameters are null or empty, or if there are any errors. @see <a href="https://www.flickr.com/services/api/flickr.contacts.getPublicList.html">flickr.contacts.getPublicList</a>
[ "Get", "the", "contact", "list", "for", "a", "user", ".", "<br", ">", "This", "method", "does", "not", "require", "authentication", "." ]
train
https://github.com/jeremybrooks/jinx/blob/ab7a4b7462d08bcbfd9b98bd3f5029771c20f6c6/src/main/java/net/jeremybrooks/jinx/api/ContactsApi.java#L117-L129
tvesalainen/util
util/src/main/java/org/vesalainen/lang/Primitives.java
Primitives.findScientific
public static final double findScientific(CharSequence cs, int beginIndex, int endIndex) { """ Parses next double in scientific form @param cs @param beginIndex @param endIndex @return """ int begin = CharSequences.indexOf(cs, Primitives::isScientificDigit, beginIndex); int end = CharSequences.indexOf(cs, (c)->!Primitives.isScientificDigit(c), begin); return parseDouble(cs, begin, endIndex(end, endIndex)); }
java
public static final double findScientific(CharSequence cs, int beginIndex, int endIndex) { int begin = CharSequences.indexOf(cs, Primitives::isScientificDigit, beginIndex); int end = CharSequences.indexOf(cs, (c)->!Primitives.isScientificDigit(c), begin); return parseDouble(cs, begin, endIndex(end, endIndex)); }
[ "public", "static", "final", "double", "findScientific", "(", "CharSequence", "cs", ",", "int", "beginIndex", ",", "int", "endIndex", ")", "{", "int", "begin", "=", "CharSequences", ".", "indexOf", "(", "cs", ",", "Primitives", "::", "isScientificDigit", ",", "beginIndex", ")", ";", "int", "end", "=", "CharSequences", ".", "indexOf", "(", "cs", ",", "(", "c", ")", "-", ">", "!", "Primitives", ".", "isScientificDigit", "(", "c", ")", ",", "begin", ")", ";", "return", "parseDouble", "(", "cs", ",", "begin", ",", "endIndex", "(", "end", ",", "endIndex", ")", ")", ";", "}" ]
Parses next double in scientific form @param cs @param beginIndex @param endIndex @return
[ "Parses", "next", "double", "in", "scientific", "form" ]
train
https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/util/src/main/java/org/vesalainen/lang/Primitives.java#L1703-L1708
Azure/azure-sdk-for-java
datamigration/resource-manager/v2017_11_15_preview/src/main/java/com/microsoft/azure/management/datamigration/v2017_11_15_preview/implementation/ServicesInner.java
ServicesInner.updateAsync
public Observable<DataMigrationServiceInner> updateAsync(String groupName, String serviceName, DataMigrationServiceInner parameters) { """ Create or update DMS Service Instance. The services resource is the top-level resource that represents the Data Migration Service. The PATCH method updates an existing service. This method can change the kind, SKU, and network of the service, but if tasks are currently running (i.e. the service is busy), this will fail with 400 Bad Request ("ServiceIsBusy"). @param groupName Name of the resource group @param serviceName Name of the service @param parameters Information about the service @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request """ return updateWithServiceResponseAsync(groupName, serviceName, parameters).map(new Func1<ServiceResponse<DataMigrationServiceInner>, DataMigrationServiceInner>() { @Override public DataMigrationServiceInner call(ServiceResponse<DataMigrationServiceInner> response) { return response.body(); } }); }
java
public Observable<DataMigrationServiceInner> updateAsync(String groupName, String serviceName, DataMigrationServiceInner parameters) { return updateWithServiceResponseAsync(groupName, serviceName, parameters).map(new Func1<ServiceResponse<DataMigrationServiceInner>, DataMigrationServiceInner>() { @Override public DataMigrationServiceInner call(ServiceResponse<DataMigrationServiceInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "DataMigrationServiceInner", ">", "updateAsync", "(", "String", "groupName", ",", "String", "serviceName", ",", "DataMigrationServiceInner", "parameters", ")", "{", "return", "updateWithServiceResponseAsync", "(", "groupName", ",", "serviceName", ",", "parameters", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "DataMigrationServiceInner", ">", ",", "DataMigrationServiceInner", ">", "(", ")", "{", "@", "Override", "public", "DataMigrationServiceInner", "call", "(", "ServiceResponse", "<", "DataMigrationServiceInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Create or update DMS Service Instance. The services resource is the top-level resource that represents the Data Migration Service. The PATCH method updates an existing service. This method can change the kind, SKU, and network of the service, but if tasks are currently running (i.e. the service is busy), this will fail with 400 Bad Request ("ServiceIsBusy"). @param groupName Name of the resource group @param serviceName Name of the service @param parameters Information about the service @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request
[ "Create", "or", "update", "DMS", "Service", "Instance", ".", "The", "services", "resource", "is", "the", "top", "-", "level", "resource", "that", "represents", "the", "Data", "Migration", "Service", ".", "The", "PATCH", "method", "updates", "an", "existing", "service", ".", "This", "method", "can", "change", "the", "kind", "SKU", "and", "network", "of", "the", "service", "but", "if", "tasks", "are", "currently", "running", "(", "i", ".", "e", ".", "the", "service", "is", "busy", ")", "this", "will", "fail", "with", "400", "Bad", "Request", "(", "ServiceIsBusy", ")", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/datamigration/resource-manager/v2017_11_15_preview/src/main/java/com/microsoft/azure/management/datamigration/v2017_11_15_preview/implementation/ServicesInner.java#L790-L797
EdwardRaff/JSAT
JSAT/src/jsat/math/optimization/stochastic/AdaDelta.java
AdaDelta.setRho
public void setRho(double rho) { """ Sets the decay rate used by AdaDelta. Lower values focus more on the current gradient, where higher values incorporate a longer history. @param rho the decay rate in (0, 1) to use """ if(rho <= 0 || rho >= 1 || Double.isNaN(rho)) throw new IllegalArgumentException("Rho must be in (0, 1)"); this.rho = rho; }
java
public void setRho(double rho) { if(rho <= 0 || rho >= 1 || Double.isNaN(rho)) throw new IllegalArgumentException("Rho must be in (0, 1)"); this.rho = rho; }
[ "public", "void", "setRho", "(", "double", "rho", ")", "{", "if", "(", "rho", "<=", "0", "||", "rho", ">=", "1", "||", "Double", ".", "isNaN", "(", "rho", ")", ")", "throw", "new", "IllegalArgumentException", "(", "\"Rho must be in (0, 1)\"", ")", ";", "this", ".", "rho", "=", "rho", ";", "}" ]
Sets the decay rate used by AdaDelta. Lower values focus more on the current gradient, where higher values incorporate a longer history. @param rho the decay rate in (0, 1) to use
[ "Sets", "the", "decay", "rate", "used", "by", "AdaDelta", ".", "Lower", "values", "focus", "more", "on", "the", "current", "gradient", "where", "higher", "values", "incorporate", "a", "longer", "history", "." ]
train
https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/math/optimization/stochastic/AdaDelta.java#L70-L75
fhoeben/hsac-fitnesse-fixtures
src/main/java/nl/hsac/fitnesse/fixture/Environment.java
Environment.doDelete
public void doDelete(String url, HttpResponse response, Map<String, Object> headers) { """ DELETEs content at URL. @param url url to send delete to. @param response response to store url and response value in. @param headers http headers to add. """ response.setRequest(url); httpClient.delete(url, response, headers); }
java
public void doDelete(String url, HttpResponse response, Map<String, Object> headers) { response.setRequest(url); httpClient.delete(url, response, headers); }
[ "public", "void", "doDelete", "(", "String", "url", ",", "HttpResponse", "response", ",", "Map", "<", "String", ",", "Object", ">", "headers", ")", "{", "response", ".", "setRequest", "(", "url", ")", ";", "httpClient", ".", "delete", "(", "url", ",", "response", ",", "headers", ")", ";", "}" ]
DELETEs content at URL. @param url url to send delete to. @param response response to store url and response value in. @param headers http headers to add.
[ "DELETEs", "content", "at", "URL", "." ]
train
https://github.com/fhoeben/hsac-fitnesse-fixtures/blob/4e9018d7386a9aa65bfcbf07eb28ae064edd1732/src/main/java/nl/hsac/fitnesse/fixture/Environment.java#L427-L430
alkacon/opencms-core
src-gwt/org/opencms/ade/containerpage/client/CmsContainerpageUtil.java
CmsContainerpageUtil.createElement
public CmsContainerPageElementPanel createElement( CmsContainerElementData containerElement, I_CmsDropContainer container, boolean isNew) throws Exception { """ Creates an drag container element.<p> @param containerElement the container element data @param container the container parent @param isNew in case of a newly created element @return the draggable element @throws Exception if something goes wrong """ if (containerElement.isGroupContainer() || containerElement.isInheritContainer()) { List<CmsContainerElementData> subElements = new ArrayList<CmsContainerElementData>(); for (String subId : containerElement.getSubItems()) { CmsContainerElementData element = m_controller.getCachedElement(subId); if (element != null) { subElements.add(element); } else { CmsDebugLog.getInstance().printLine("Cached element not found"); } } return createGroupcontainerElement(containerElement, subElements, container); } Element element = CmsDomUtil.createElement(containerElement.getContents().get(container.getContainerId())); // ensure any embedded flash players are set opaque so UI elements may be placed above them CmsDomUtil.fixFlashZindex(element); if (isNew) { CmsContentEditor.replaceResourceIds( element, CmsUUID.getNullUUID().toString(), CmsContainerpageController.getServerId(containerElement.getClientId())); } CmsContainerPageElementPanel result = createElement(element, container, containerElement); if (!CmsContainerpageController.get().shouldShowInContext(containerElement)) { result.getElement().getStyle().setDisplay(Style.Display.NONE); result.addStyleName(CmsTemplateContextInfo.DUMMY_ELEMENT_MARKER); } return result; }
java
public CmsContainerPageElementPanel createElement( CmsContainerElementData containerElement, I_CmsDropContainer container, boolean isNew) throws Exception { if (containerElement.isGroupContainer() || containerElement.isInheritContainer()) { List<CmsContainerElementData> subElements = new ArrayList<CmsContainerElementData>(); for (String subId : containerElement.getSubItems()) { CmsContainerElementData element = m_controller.getCachedElement(subId); if (element != null) { subElements.add(element); } else { CmsDebugLog.getInstance().printLine("Cached element not found"); } } return createGroupcontainerElement(containerElement, subElements, container); } Element element = CmsDomUtil.createElement(containerElement.getContents().get(container.getContainerId())); // ensure any embedded flash players are set opaque so UI elements may be placed above them CmsDomUtil.fixFlashZindex(element); if (isNew) { CmsContentEditor.replaceResourceIds( element, CmsUUID.getNullUUID().toString(), CmsContainerpageController.getServerId(containerElement.getClientId())); } CmsContainerPageElementPanel result = createElement(element, container, containerElement); if (!CmsContainerpageController.get().shouldShowInContext(containerElement)) { result.getElement().getStyle().setDisplay(Style.Display.NONE); result.addStyleName(CmsTemplateContextInfo.DUMMY_ELEMENT_MARKER); } return result; }
[ "public", "CmsContainerPageElementPanel", "createElement", "(", "CmsContainerElementData", "containerElement", ",", "I_CmsDropContainer", "container", ",", "boolean", "isNew", ")", "throws", "Exception", "{", "if", "(", "containerElement", ".", "isGroupContainer", "(", ")", "||", "containerElement", ".", "isInheritContainer", "(", ")", ")", "{", "List", "<", "CmsContainerElementData", ">", "subElements", "=", "new", "ArrayList", "<", "CmsContainerElementData", ">", "(", ")", ";", "for", "(", "String", "subId", ":", "containerElement", ".", "getSubItems", "(", ")", ")", "{", "CmsContainerElementData", "element", "=", "m_controller", ".", "getCachedElement", "(", "subId", ")", ";", "if", "(", "element", "!=", "null", ")", "{", "subElements", ".", "add", "(", "element", ")", ";", "}", "else", "{", "CmsDebugLog", ".", "getInstance", "(", ")", ".", "printLine", "(", "\"Cached element not found\"", ")", ";", "}", "}", "return", "createGroupcontainerElement", "(", "containerElement", ",", "subElements", ",", "container", ")", ";", "}", "Element", "element", "=", "CmsDomUtil", ".", "createElement", "(", "containerElement", ".", "getContents", "(", ")", ".", "get", "(", "container", ".", "getContainerId", "(", ")", ")", ")", ";", "// ensure any embedded flash players are set opaque so UI elements may be placed above them", "CmsDomUtil", ".", "fixFlashZindex", "(", "element", ")", ";", "if", "(", "isNew", ")", "{", "CmsContentEditor", ".", "replaceResourceIds", "(", "element", ",", "CmsUUID", ".", "getNullUUID", "(", ")", ".", "toString", "(", ")", ",", "CmsContainerpageController", ".", "getServerId", "(", "containerElement", ".", "getClientId", "(", ")", ")", ")", ";", "}", "CmsContainerPageElementPanel", "result", "=", "createElement", "(", "element", ",", "container", ",", "containerElement", ")", ";", "if", "(", "!", "CmsContainerpageController", ".", "get", "(", ")", ".", "shouldShowInContext", "(", "containerElement", ")", ")", "{", "result", ".", "getElement", "(", ")", ".", "getStyle", "(", ")", ".", "setDisplay", "(", "Style", ".", "Display", ".", "NONE", ")", ";", "result", ".", "addStyleName", "(", "CmsTemplateContextInfo", ".", "DUMMY_ELEMENT_MARKER", ")", ";", "}", "return", "result", ";", "}" ]
Creates an drag container element.<p> @param containerElement the container element data @param container the container parent @param isNew in case of a newly created element @return the draggable element @throws Exception if something goes wrong
[ "Creates", "an", "drag", "container", "element", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/containerpage/client/CmsContainerpageUtil.java#L334-L368
TheCoder4eu/BootsFaces-OSP
src/main/java/net/bootsfaces/component/slider/SliderRenderer.java
SliderRenderer.decode
@Override public void decode(FacesContext context, UIComponent component) { """ This methods receives and processes input made by the user. More specifically, it ckecks whether the user has interacted with the current b:slider. The default implementation simply stores the input value in the list of submitted values. If the validation checks are passed, the values in the <code>submittedValues</code> list are store in the backend bean. @param context the FacesContext. @param component the current b:slider. """ Slider slider = (Slider) component; if (slider.isDisabled() || slider.isReadonly()) { return; } decodeBehaviors(context, slider); String clientId = slider.getClientId(context); String submittedValue = (String) context.getExternalContext().getRequestParameterMap().get(clientId); if (submittedValue != null) { slider.setSubmittedValue(submittedValue); slider.setValid(true); } }
java
@Override public void decode(FacesContext context, UIComponent component) { Slider slider = (Slider) component; if (slider.isDisabled() || slider.isReadonly()) { return; } decodeBehaviors(context, slider); String clientId = slider.getClientId(context); String submittedValue = (String) context.getExternalContext().getRequestParameterMap().get(clientId); if (submittedValue != null) { slider.setSubmittedValue(submittedValue); slider.setValid(true); } }
[ "@", "Override", "public", "void", "decode", "(", "FacesContext", "context", ",", "UIComponent", "component", ")", "{", "Slider", "slider", "=", "(", "Slider", ")", "component", ";", "if", "(", "slider", ".", "isDisabled", "(", ")", "||", "slider", ".", "isReadonly", "(", ")", ")", "{", "return", ";", "}", "decodeBehaviors", "(", "context", ",", "slider", ")", ";", "String", "clientId", "=", "slider", ".", "getClientId", "(", "context", ")", ";", "String", "submittedValue", "=", "(", "String", ")", "context", ".", "getExternalContext", "(", ")", ".", "getRequestParameterMap", "(", ")", ".", "get", "(", "clientId", ")", ";", "if", "(", "submittedValue", "!=", "null", ")", "{", "slider", ".", "setSubmittedValue", "(", "submittedValue", ")", ";", "slider", ".", "setValid", "(", "true", ")", ";", "}", "}" ]
This methods receives and processes input made by the user. More specifically, it ckecks whether the user has interacted with the current b:slider. The default implementation simply stores the input value in the list of submitted values. If the validation checks are passed, the values in the <code>submittedValues</code> list are store in the backend bean. @param context the FacesContext. @param component the current b:slider.
[ "This", "methods", "receives", "and", "processes", "input", "made", "by", "the", "user", ".", "More", "specifically", "it", "ckecks", "whether", "the", "user", "has", "interacted", "with", "the", "current", "b", ":", "slider", ".", "The", "default", "implementation", "simply", "stores", "the", "input", "value", "in", "the", "list", "of", "submitted", "values", ".", "If", "the", "validation", "checks", "are", "passed", "the", "values", "in", "the", "<code", ">", "submittedValues<", "/", "code", ">", "list", "are", "store", "in", "the", "backend", "bean", "." ]
train
https://github.com/TheCoder4eu/BootsFaces-OSP/blob/d1a70952bc240979b5272fa4fe1c7f100873add0/src/main/java/net/bootsfaces/component/slider/SliderRenderer.java#L52-L69
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/com/send/authentication/ed25519/math/GroupElement.java
GroupElement.dbl
public org.mariadb.jdbc.internal.com.send.authentication.ed25519.math.GroupElement dbl() { """ Doubles a given group element $p$ in $P^2$ or $P^3$ representation and returns the result in $P \times P$ representation. $r = 2 * p$ where $p = (X : Y : Z)$ or $p = (X : Y : Z : T)$ <p> $r$ in $P \times P$ representation: <p> $r = ((X' : Z'), (Y' : T'))$ where </p><ul> <li>$X' = (X + Y)^2 - (Y^2 + X^2)$ <li>$Y' = Y^2 + X^2$ <li>$Z' = y^2 - X^2$ <li>$T' = 2 * Z^2 - (y^2 - X^2)$ </ul><p> $r$ converted from $P \times P$ to $P^2$ representation: <p> $r = (X'' : Y'' : Z'')$ where </p><ul> <li>$X'' = X' * Z' = ((X + Y)^2 - Y^2 - X^2) * (2 * Z^2 - (y^2 - X^2))$ <li>$Y'' = Y' * T' = (Y^2 + X^2) * (2 * Z^2 - (y^2 - X^2))$ <li>$Z'' = Z' * T' = (y^2 - X^2) * (2 * Z^2 - (y^2 - X^2))$ </ul><p> Formula for the $P^2$ representation is in agreement with the formula given in [4] page 12 (with $a = -1$) up to a common factor -1 which does not matter: <p> $$ B = (X + Y)^2; C = X^2; D = Y^2; E = -C = -X^2; F := E + D = Y^2 - X^2; H = Z^2; J = F − 2 * H; \\ X3 = (B − C − D) · J = X' * (-T'); \\ Y3 = F · (E − D) = Z' * (-Y'); \\ Z3 = F · J = Z' * (-T'). $$ @return The P1P1 representation """ switch (this.repr) { case P2: case P3: // Ignore T for P3 representation FieldElement XX, YY, B, A, AA, Yn, Zn; XX = this.X.square(); YY = this.Y.square(); B = this.Z.squareAndDouble(); A = this.X.add(this.Y); AA = A.square(); Yn = YY.add(XX); Zn = YY.subtract(XX); return p1p1(this.curve, AA.subtract(Yn), Yn, Zn, B.subtract(Zn)); default: throw new UnsupportedOperationException(); } }
java
public org.mariadb.jdbc.internal.com.send.authentication.ed25519.math.GroupElement dbl() { switch (this.repr) { case P2: case P3: // Ignore T for P3 representation FieldElement XX, YY, B, A, AA, Yn, Zn; XX = this.X.square(); YY = this.Y.square(); B = this.Z.squareAndDouble(); A = this.X.add(this.Y); AA = A.square(); Yn = YY.add(XX); Zn = YY.subtract(XX); return p1p1(this.curve, AA.subtract(Yn), Yn, Zn, B.subtract(Zn)); default: throw new UnsupportedOperationException(); } }
[ "public", "org", ".", "mariadb", ".", "jdbc", ".", "internal", ".", "com", ".", "send", ".", "authentication", ".", "ed25519", ".", "math", ".", "GroupElement", "dbl", "(", ")", "{", "switch", "(", "this", ".", "repr", ")", "{", "case", "P2", ":", "case", "P3", ":", "// Ignore T for P3 representation", "FieldElement", "XX", ",", "YY", ",", "B", ",", "A", ",", "AA", ",", "Yn", ",", "Zn", ";", "XX", "=", "this", ".", "X", ".", "square", "(", ")", ";", "YY", "=", "this", ".", "Y", ".", "square", "(", ")", ";", "B", "=", "this", ".", "Z", ".", "squareAndDouble", "(", ")", ";", "A", "=", "this", ".", "X", ".", "add", "(", "this", ".", "Y", ")", ";", "AA", "=", "A", ".", "square", "(", ")", ";", "Yn", "=", "YY", ".", "add", "(", "XX", ")", ";", "Zn", "=", "YY", ".", "subtract", "(", "XX", ")", ";", "return", "p1p1", "(", "this", ".", "curve", ",", "AA", ".", "subtract", "(", "Yn", ")", ",", "Yn", ",", "Zn", ",", "B", ".", "subtract", "(", "Zn", ")", ")", ";", "default", ":", "throw", "new", "UnsupportedOperationException", "(", ")", ";", "}", "}" ]
Doubles a given group element $p$ in $P^2$ or $P^3$ representation and returns the result in $P \times P$ representation. $r = 2 * p$ where $p = (X : Y : Z)$ or $p = (X : Y : Z : T)$ <p> $r$ in $P \times P$ representation: <p> $r = ((X' : Z'), (Y' : T'))$ where </p><ul> <li>$X' = (X + Y)^2 - (Y^2 + X^2)$ <li>$Y' = Y^2 + X^2$ <li>$Z' = y^2 - X^2$ <li>$T' = 2 * Z^2 - (y^2 - X^2)$ </ul><p> $r$ converted from $P \times P$ to $P^2$ representation: <p> $r = (X'' : Y'' : Z'')$ where </p><ul> <li>$X'' = X' * Z' = ((X + Y)^2 - Y^2 - X^2) * (2 * Z^2 - (y^2 - X^2))$ <li>$Y'' = Y' * T' = (Y^2 + X^2) * (2 * Z^2 - (y^2 - X^2))$ <li>$Z'' = Z' * T' = (y^2 - X^2) * (2 * Z^2 - (y^2 - X^2))$ </ul><p> Formula for the $P^2$ representation is in agreement with the formula given in [4] page 12 (with $a = -1$) up to a common factor -1 which does not matter: <p> $$ B = (X + Y)^2; C = X^2; D = Y^2; E = -C = -X^2; F := E + D = Y^2 - X^2; H = Z^2; J = F − 2 * H; \\ X3 = (B − C − D) · J = X' * (-T'); \\ Y3 = F · (E − D) = Z' * (-Y'); \\ Z3 = F · J = Z' * (-T'). $$ @return The P1P1 representation
[ "Doubles", "a", "given", "group", "element", "$p$", "in", "$P^2$", "or", "$P^3$", "representation", "and", "returns", "the", "result", "in", "$P", "\\", "times", "P$", "representation", ".", "$r", "=", "2", "*", "p$", "where", "$p", "=", "(", "X", ":", "Y", ":", "Z", ")", "$", "or", "$p", "=", "(", "X", ":", "Y", ":", "Z", ":", "T", ")", "$", "<p", ">", "$r$", "in", "$P", "\\", "times", "P$", "representation", ":", "<p", ">", "$r", "=", "((", "X", ":", "Z", ")", "(", "Y", ":", "T", "))", "$", "where", "<", "/", "p", ">", "<ul", ">", "<li", ">", "$X", "=", "(", "X", "+", "Y", ")", "^2", "-", "(", "Y^2", "+", "X^2", ")", "$", "<li", ">", "$Y", "=", "Y^2", "+", "X^2$", "<li", ">", "$Z", "=", "y^2", "-", "X^2$", "<li", ">", "$T", "=", "2", "*", "Z^2", "-", "(", "y^2", "-", "X^2", ")", "$", "<", "/", "ul", ">", "<p", ">", "$r$", "converted", "from", "$P", "\\", "times", "P$", "to", "$P^2$", "representation", ":", "<p", ">", "$r", "=", "(", "X", ":", "Y", ":", "Z", ")", "$", "where", "<", "/", "p", ">", "<ul", ">", "<li", ">", "$X", "=", "X", "*", "Z", "=", "((", "X", "+", "Y", ")", "^2", "-", "Y^2", "-", "X^2", ")", "*", "(", "2", "*", "Z^2", "-", "(", "y^2", "-", "X^2", "))", "$", "<li", ">", "$Y", "=", "Y", "*", "T", "=", "(", "Y^2", "+", "X^2", ")", "*", "(", "2", "*", "Z^2", "-", "(", "y^2", "-", "X^2", "))", "$", "<li", ">", "$Z", "=", "Z", "*", "T", "=", "(", "y^2", "-", "X^2", ")", "*", "(", "2", "*", "Z^2", "-", "(", "y^2", "-", "X^2", "))", "$", "<", "/", "ul", ">", "<p", ">", "Formula", "for", "the", "$P^2$", "representation", "is", "in", "agreement", "with", "the", "formula", "given", "in", "[", "4", "]", "page", "12", "(", "with", "$a", "=", "-", "1$", ")", "up", "to", "a", "common", "factor", "-", "1", "which", "does", "not", "matter", ":", "<p", ">", "$$", "B", "=", "(", "X", "+", "Y", ")", "^2", ";", "C", "=", "X^2", ";", "D", "=", "Y^2", ";", "E", "=", "-", "C", "=", "-", "X^2", ";", "F", ":", "=", "E", "+", "D", "=", "Y^2", "-", "X^2", ";", "H", "=", "Z^2", ";", "J", "=", "F", "−", "2", "*", "H", ";", "\\\\", "X3", "=", "(", "B", "−", "C", "−", "D", ")", "·", "J", "=", "X", "*", "(", "-", "T", ")", ";", "\\\\", "Y3", "=", "F", "·", "(", "E", "−", "D", ")", "=", "Z", "*", "(", "-", "Y", ")", ";", "\\\\", "Z3", "=", "F", "·", "J", "=", "Z", "*", "(", "-", "T", ")", ".", "$$" ]
train
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/com/send/authentication/ed25519/math/GroupElement.java#L591-L607
GeoLatte/geolatte-common
src/main/java/org/geolatte/common/dataformats/json/jackson/AbstractJsonDeserializer.java
AbstractJsonDeserializer.getIntParam
protected Integer getIntParam(String paramName, String errorMessage) throws IOException { """ Convenience method for subclasses. @param paramName the name of the parameter @param errorMessage the errormessage to add to the exception if the param does not exist. @return a stringparameter with given name. If it does not exist and the errormessage is provided, an IOException is thrown with that message. if the errormessage is not provided, null is returned. @throws IOException Exception if the paramname does not exist and an errormessage is provided. """ return getIntParam(paramName, errorMessage, (Map<String, Object>) inputParams.get()); }
java
protected Integer getIntParam(String paramName, String errorMessage) throws IOException { return getIntParam(paramName, errorMessage, (Map<String, Object>) inputParams.get()); }
[ "protected", "Integer", "getIntParam", "(", "String", "paramName", ",", "String", "errorMessage", ")", "throws", "IOException", "{", "return", "getIntParam", "(", "paramName", ",", "errorMessage", ",", "(", "Map", "<", "String", ",", "Object", ">", ")", "inputParams", ".", "get", "(", ")", ")", ";", "}" ]
Convenience method for subclasses. @param paramName the name of the parameter @param errorMessage the errormessage to add to the exception if the param does not exist. @return a stringparameter with given name. If it does not exist and the errormessage is provided, an IOException is thrown with that message. if the errormessage is not provided, null is returned. @throws IOException Exception if the paramname does not exist and an errormessage is provided.
[ "Convenience", "method", "for", "subclasses", "." ]
train
https://github.com/GeoLatte/geolatte-common/blob/dc7f92b04d8c6cb706e78cb95e746d8f12089d95/src/main/java/org/geolatte/common/dataformats/json/jackson/AbstractJsonDeserializer.java#L224-L226
baratine/baratine
web/src/main/java/com/caucho/v5/http/protocol/RequestHttp1.java
RequestHttp1.setHeader
@Override public void setHeader(String key, String value) { """ Adds a new header. Used only by the caching to simulate If-Modified-Since. @param key the key of the new header @param value the value for the new header """ int tail; if (_headerSize > 0) { tail = (_headerValues[_headerSize - 1].offset() + _headerValues[_headerSize - 1].length()); } else { tail = 0; } int keyLength = key.length(); int valueLength = value.length(); char []headerBuffer = _headerBuffer; for (int i = keyLength - 1; i >= 0; i--) { headerBuffer[tail + i] = key.charAt(i); } _headerKeys[_headerSize].init(headerBuffer, tail, keyLength); tail += keyLength; for (int i = valueLength - 1; i >= 0; i--) { headerBuffer[tail + i] = value.charAt(i); } _headerValues[_headerSize].init(headerBuffer, tail, valueLength); _headerSize++; // XXX: size }
java
@Override public void setHeader(String key, String value) { int tail; if (_headerSize > 0) { tail = (_headerValues[_headerSize - 1].offset() + _headerValues[_headerSize - 1].length()); } else { tail = 0; } int keyLength = key.length(); int valueLength = value.length(); char []headerBuffer = _headerBuffer; for (int i = keyLength - 1; i >= 0; i--) { headerBuffer[tail + i] = key.charAt(i); } _headerKeys[_headerSize].init(headerBuffer, tail, keyLength); tail += keyLength; for (int i = valueLength - 1; i >= 0; i--) { headerBuffer[tail + i] = value.charAt(i); } _headerValues[_headerSize].init(headerBuffer, tail, valueLength); _headerSize++; // XXX: size }
[ "@", "Override", "public", "void", "setHeader", "(", "String", "key", ",", "String", "value", ")", "{", "int", "tail", ";", "if", "(", "_headerSize", ">", "0", ")", "{", "tail", "=", "(", "_headerValues", "[", "_headerSize", "-", "1", "]", ".", "offset", "(", ")", "+", "_headerValues", "[", "_headerSize", "-", "1", "]", ".", "length", "(", ")", ")", ";", "}", "else", "{", "tail", "=", "0", ";", "}", "int", "keyLength", "=", "key", ".", "length", "(", ")", ";", "int", "valueLength", "=", "value", ".", "length", "(", ")", ";", "char", "[", "]", "headerBuffer", "=", "_headerBuffer", ";", "for", "(", "int", "i", "=", "keyLength", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "headerBuffer", "[", "tail", "+", "i", "]", "=", "key", ".", "charAt", "(", "i", ")", ";", "}", "_headerKeys", "[", "_headerSize", "]", ".", "init", "(", "headerBuffer", ",", "tail", ",", "keyLength", ")", ";", "tail", "+=", "keyLength", ";", "for", "(", "int", "i", "=", "valueLength", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "headerBuffer", "[", "tail", "+", "i", "]", "=", "value", ".", "charAt", "(", "i", ")", ";", "}", "_headerValues", "[", "_headerSize", "]", ".", "init", "(", "headerBuffer", ",", "tail", ",", "valueLength", ")", ";", "_headerSize", "++", ";", "// XXX: size", "}" ]
Adds a new header. Used only by the caching to simulate If-Modified-Since. @param key the key of the new header @param value the value for the new header
[ "Adds", "a", "new", "header", ".", "Used", "only", "by", "the", "caching", "to", "simulate", "If", "-", "Modified", "-", "Since", "." ]
train
https://github.com/baratine/baratine/blob/db34b45c03c5a5e930d8142acc72319125569fcf/web/src/main/java/com/caucho/v5/http/protocol/RequestHttp1.java#L609-L641
threerings/nenya
core/src/main/java/com/threerings/miso/client/MisoScenePanel.java
MisoScenePanel.updateTileCoords
protected boolean updateTileCoords (int sx, int sy, Point tpos) { """ Converts the supplied screen coordinates into tile coordinates, writing the values into the supplied {@link Point} instance and returning true if the screen coordinates translated into a different set of tile coordinates than were already contained in the point (so that the caller can know to update a highlight, for example). @return true if the tile coordinates have changed. """ Point npos = MisoUtil.screenToTile(_metrics, sx, sy, new Point()); if (!tpos.equals(npos)) { tpos.setLocation(npos.x, npos.y); return true; } else { return false; } }
java
protected boolean updateTileCoords (int sx, int sy, Point tpos) { Point npos = MisoUtil.screenToTile(_metrics, sx, sy, new Point()); if (!tpos.equals(npos)) { tpos.setLocation(npos.x, npos.y); return true; } else { return false; } }
[ "protected", "boolean", "updateTileCoords", "(", "int", "sx", ",", "int", "sy", ",", "Point", "tpos", ")", "{", "Point", "npos", "=", "MisoUtil", ".", "screenToTile", "(", "_metrics", ",", "sx", ",", "sy", ",", "new", "Point", "(", ")", ")", ";", "if", "(", "!", "tpos", ".", "equals", "(", "npos", ")", ")", "{", "tpos", ".", "setLocation", "(", "npos", ".", "x", ",", "npos", ".", "y", ")", ";", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Converts the supplied screen coordinates into tile coordinates, writing the values into the supplied {@link Point} instance and returning true if the screen coordinates translated into a different set of tile coordinates than were already contained in the point (so that the caller can know to update a highlight, for example). @return true if the tile coordinates have changed.
[ "Converts", "the", "supplied", "screen", "coordinates", "into", "tile", "coordinates", "writing", "the", "values", "into", "the", "supplied", "{", "@link", "Point", "}", "instance", "and", "returning", "true", "if", "the", "screen", "coordinates", "translated", "into", "a", "different", "set", "of", "tile", "coordinates", "than", "were", "already", "contained", "in", "the", "point", "(", "so", "that", "the", "caller", "can", "know", "to", "update", "a", "highlight", "for", "example", ")", "." ]
train
https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/miso/client/MisoScenePanel.java#L1196-L1205
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/Vector.java
Vector.addAll
public synchronized boolean addAll(int index, Collection<? extends E> c) { """ Inserts all of the elements in the specified Collection into this Vector at the specified position. Shifts the element currently at that position (if any) and any subsequent elements to the right (increases their indices). The new elements will appear in the Vector in the order that they are returned by the specified Collection's iterator. @param index index at which to insert the first element from the specified collection @param c elements to be inserted into this Vector @return {@code true} if this Vector changed as a result of the call @throws ArrayIndexOutOfBoundsException if the index is out of range ({@code index < 0 || index > size()}) @throws NullPointerException if the specified collection is null @since 1.2 """ modCount++; if (index < 0 || index > elementCount) throw new ArrayIndexOutOfBoundsException(index); Object[] a = c.toArray(); int numNew = a.length; ensureCapacityHelper(elementCount + numNew); int numMoved = elementCount - index; if (numMoved > 0) System.arraycopy(elementData, index, elementData, index + numNew, numMoved); System.arraycopy(a, 0, elementData, index, numNew); elementCount += numNew; return numNew != 0; }
java
public synchronized boolean addAll(int index, Collection<? extends E> c) { modCount++; if (index < 0 || index > elementCount) throw new ArrayIndexOutOfBoundsException(index); Object[] a = c.toArray(); int numNew = a.length; ensureCapacityHelper(elementCount + numNew); int numMoved = elementCount - index; if (numMoved > 0) System.arraycopy(elementData, index, elementData, index + numNew, numMoved); System.arraycopy(a, 0, elementData, index, numNew); elementCount += numNew; return numNew != 0; }
[ "public", "synchronized", "boolean", "addAll", "(", "int", "index", ",", "Collection", "<", "?", "extends", "E", ">", "c", ")", "{", "modCount", "++", ";", "if", "(", "index", "<", "0", "||", "index", ">", "elementCount", ")", "throw", "new", "ArrayIndexOutOfBoundsException", "(", "index", ")", ";", "Object", "[", "]", "a", "=", "c", ".", "toArray", "(", ")", ";", "int", "numNew", "=", "a", ".", "length", ";", "ensureCapacityHelper", "(", "elementCount", "+", "numNew", ")", ";", "int", "numMoved", "=", "elementCount", "-", "index", ";", "if", "(", "numMoved", ">", "0", ")", "System", ".", "arraycopy", "(", "elementData", ",", "index", ",", "elementData", ",", "index", "+", "numNew", ",", "numMoved", ")", ";", "System", ".", "arraycopy", "(", "a", ",", "0", ",", "elementData", ",", "index", ",", "numNew", ")", ";", "elementCount", "+=", "numNew", ";", "return", "numNew", "!=", "0", ";", "}" ]
Inserts all of the elements in the specified Collection into this Vector at the specified position. Shifts the element currently at that position (if any) and any subsequent elements to the right (increases their indices). The new elements will appear in the Vector in the order that they are returned by the specified Collection's iterator. @param index index at which to insert the first element from the specified collection @param c elements to be inserted into this Vector @return {@code true} if this Vector changed as a result of the call @throws ArrayIndexOutOfBoundsException if the index is out of range ({@code index < 0 || index > size()}) @throws NullPointerException if the specified collection is null @since 1.2
[ "Inserts", "all", "of", "the", "elements", "in", "the", "specified", "Collection", "into", "this", "Vector", "at", "the", "specified", "position", ".", "Shifts", "the", "element", "currently", "at", "that", "position", "(", "if", "any", ")", "and", "any", "subsequent", "elements", "to", "the", "right", "(", "increases", "their", "indices", ")", ".", "The", "new", "elements", "will", "appear", "in", "the", "Vector", "in", "the", "order", "that", "they", "are", "returned", "by", "the", "specified", "Collection", "s", "iterator", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/Vector.java#L953-L970
tvesalainen/util
util/src/main/java/org/vesalainen/util/Recycler.java
Recycler.get
public static final <T extends Recyclable> T get(Class<T> cls, Consumer<T> initializer) { """ Returns new or recycled initialized object. @param <T> @param cls @param initializer @return """ T recyclable = null; lock.lock(); try { List<Recyclable> list = mapList.get(cls); if (list != null && !list.isEmpty()) { recyclable = (T) list.remove(list.size()-1); log.debug("get recycled %s", recyclable); } } finally { lock.unlock(); } if (recyclable == null) { try { recyclable = cls.newInstance(); log.debug("create new recycled %s", recyclable); } catch (InstantiationException | IllegalAccessException ex) { throw new IllegalArgumentException(ex); } } if (initializer != null) { initializer.accept(recyclable); } return (T) recyclable; }
java
public static final <T extends Recyclable> T get(Class<T> cls, Consumer<T> initializer) { T recyclable = null; lock.lock(); try { List<Recyclable> list = mapList.get(cls); if (list != null && !list.isEmpty()) { recyclable = (T) list.remove(list.size()-1); log.debug("get recycled %s", recyclable); } } finally { lock.unlock(); } if (recyclable == null) { try { recyclable = cls.newInstance(); log.debug("create new recycled %s", recyclable); } catch (InstantiationException | IllegalAccessException ex) { throw new IllegalArgumentException(ex); } } if (initializer != null) { initializer.accept(recyclable); } return (T) recyclable; }
[ "public", "static", "final", "<", "T", "extends", "Recyclable", ">", "T", "get", "(", "Class", "<", "T", ">", "cls", ",", "Consumer", "<", "T", ">", "initializer", ")", "{", "T", "recyclable", "=", "null", ";", "lock", ".", "lock", "(", ")", ";", "try", "{", "List", "<", "Recyclable", ">", "list", "=", "mapList", ".", "get", "(", "cls", ")", ";", "if", "(", "list", "!=", "null", "&&", "!", "list", ".", "isEmpty", "(", ")", ")", "{", "recyclable", "=", "(", "T", ")", "list", ".", "remove", "(", "list", ".", "size", "(", ")", "-", "1", ")", ";", "log", ".", "debug", "(", "\"get recycled %s\"", ",", "recyclable", ")", ";", "}", "}", "finally", "{", "lock", ".", "unlock", "(", ")", ";", "}", "if", "(", "recyclable", "==", "null", ")", "{", "try", "{", "recyclable", "=", "cls", ".", "newInstance", "(", ")", ";", "log", ".", "debug", "(", "\"create new recycled %s\"", ",", "recyclable", ")", ";", "}", "catch", "(", "InstantiationException", "|", "IllegalAccessException", "ex", ")", "{", "throw", "new", "IllegalArgumentException", "(", "ex", ")", ";", "}", "}", "if", "(", "initializer", "!=", "null", ")", "{", "initializer", ".", "accept", "(", "recyclable", ")", ";", "}", "return", "(", "T", ")", "recyclable", ";", "}" ]
Returns new or recycled initialized object. @param <T> @param cls @param initializer @return
[ "Returns", "new", "or", "recycled", "initialized", "object", "." ]
train
https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/util/src/main/java/org/vesalainen/util/Recycler.java#L70-L104
JRebirth/JRebirth
org.jrebirth.af/core/src/main/java/org/jrebirth/af/core/concurrent/JRebirth.java
JRebirth.runIntoJITSync
public static void runIntoJITSync(final JRebirthRunnable runnable, final long... timeout) { """ Run the task into the JRebirth Internal Thread [JIT] <b>Synchronously</b>. @param runnable the task to run @param timeout the optional timeout value after which the thread will be released (default is 1000 ms) """ final SyncRunnable sync = new SyncRunnable(runnable); if (JRebirth.isJIT()) { // We are into a JIT so just run it synchronously sync.run(); // Be careful in this case no timeout protection is achieved } else { // The runnable will be run into the JIT during the next round according to existing runnable priorities JRebirthThread.getThread().runLater(sync); // Wait the end of the runnable execution sync.waitEnd(timeout); } }
java
public static void runIntoJITSync(final JRebirthRunnable runnable, final long... timeout) { final SyncRunnable sync = new SyncRunnable(runnable); if (JRebirth.isJIT()) { // We are into a JIT so just run it synchronously sync.run(); // Be careful in this case no timeout protection is achieved } else { // The runnable will be run into the JIT during the next round according to existing runnable priorities JRebirthThread.getThread().runLater(sync); // Wait the end of the runnable execution sync.waitEnd(timeout); } }
[ "public", "static", "void", "runIntoJITSync", "(", "final", "JRebirthRunnable", "runnable", ",", "final", "long", "...", "timeout", ")", "{", "final", "SyncRunnable", "sync", "=", "new", "SyncRunnable", "(", "runnable", ")", ";", "if", "(", "JRebirth", ".", "isJIT", "(", ")", ")", "{", "// We are into a JIT so just run it synchronously", "sync", ".", "run", "(", ")", ";", "// Be careful in this case no timeout protection is achieved", "}", "else", "{", "// The runnable will be run into the JIT during the next round according to existing runnable priorities", "JRebirthThread", ".", "getThread", "(", ")", ".", "runLater", "(", "sync", ")", ";", "// Wait the end of the runnable execution", "sync", ".", "waitEnd", "(", "timeout", ")", ";", "}", "}" ]
Run the task into the JRebirth Internal Thread [JIT] <b>Synchronously</b>. @param runnable the task to run @param timeout the optional timeout value after which the thread will be released (default is 1000 ms)
[ "Run", "the", "task", "into", "the", "JRebirth", "Internal", "Thread", "[", "JIT", "]", "<b", ">", "Synchronously<", "/", "b", ">", "." ]
train
https://github.com/JRebirth/JRebirth/blob/93f4fc087b83c73db540333b9686e97b4cec694d/org.jrebirth.af/core/src/main/java/org/jrebirth/af/core/concurrent/JRebirth.java#L305-L318
BranchMetrics/android-branch-deep-linking
Branch-SDK/src/io/branch/referral/ApkParser.java
ApkParser.LEW
private int LEW(byte[] arr, int off) { """ Gets the LEW (Little-Endian Word) from a {@link Byte} array, at the position defined by the offset {@link Integer} provided. @param arr The {@link Byte} array to process. @param off An {@link int} value indicating the offset from which the return value should be taken. @return The {@link Integer} Little Endian 32 bit word taken from the input {@link Byte} array at the offset supplied as a parameter. """ return arr[off + 3] << 24 & 0xff000000 | arr[off + 2] << 16 & 0xff0000 | arr[off + 1] << 8 & 0xff00 | arr[off] & 0xFF; }
java
private int LEW(byte[] arr, int off) { return arr[off + 3] << 24 & 0xff000000 | arr[off + 2] << 16 & 0xff0000 | arr[off + 1] << 8 & 0xff00 | arr[off] & 0xFF; }
[ "private", "int", "LEW", "(", "byte", "[", "]", "arr", ",", "int", "off", ")", "{", "return", "arr", "[", "off", "+", "3", "]", "<<", "24", "&", "0xff000000", "|", "arr", "[", "off", "+", "2", "]", "<<", "16", "&", "0xff0000", "|", "arr", "[", "off", "+", "1", "]", "<<", "8", "&", "0xff00", "|", "arr", "[", "off", "]", "&", "0xFF", ";", "}" ]
Gets the LEW (Little-Endian Word) from a {@link Byte} array, at the position defined by the offset {@link Integer} provided. @param arr The {@link Byte} array to process. @param off An {@link int} value indicating the offset from which the return value should be taken. @return The {@link Integer} Little Endian 32 bit word taken from the input {@link Byte} array at the offset supplied as a parameter.
[ "Gets", "the", "LEW", "(", "Little", "-", "Endian", "Word", ")", "from", "a", "{", "@link", "Byte", "}", "array", "at", "the", "position", "defined", "by", "the", "offset", "{", "@link", "Integer", "}", "provided", "." ]
train
https://github.com/BranchMetrics/android-branch-deep-linking/blob/e3bee2ccfcbf6d4bf1a5815b5b86666e4ff8f848/Branch-SDK/src/io/branch/referral/ApkParser.java#L280-L282
febit/wit
wit-core/src/main/java/org/febit/wit/global/GlobalManager.java
GlobalManager.forEachGlobal
public void forEachGlobal(BiConsumer<String, Object> action) { """ Performs the given action for each global vars until all have been processed or the action throws an exception. @param action @since 2.5.0 """ Objects.requireNonNull(action); this.globalVars.forEach(action); }
java
public void forEachGlobal(BiConsumer<String, Object> action) { Objects.requireNonNull(action); this.globalVars.forEach(action); }
[ "public", "void", "forEachGlobal", "(", "BiConsumer", "<", "String", ",", "Object", ">", "action", ")", "{", "Objects", ".", "requireNonNull", "(", "action", ")", ";", "this", ".", "globalVars", ".", "forEach", "(", "action", ")", ";", "}" ]
Performs the given action for each global vars until all have been processed or the action throws an exception. @param action @since 2.5.0
[ "Performs", "the", "given", "action", "for", "each", "global", "vars", "until", "all", "have", "been", "processed", "or", "the", "action", "throws", "an", "exception", "." ]
train
https://github.com/febit/wit/blob/89ee29efbc5633b79c30c3c7b953c9f4130575af/wit-core/src/main/java/org/febit/wit/global/GlobalManager.java#L61-L64
citrusframework/citrus
modules/citrus-jms/src/main/java/com/consol/citrus/jms/actions/PurgeJmsQueuesAction.java
PurgeJmsQueuesAction.getDestination
private Destination getDestination(Session session, String queueName) throws JMSException { """ Resolves destination by given name. @param session @param queueName @return @throws JMSException """ return new DynamicDestinationResolver().resolveDestinationName(session, queueName, false); }
java
private Destination getDestination(Session session, String queueName) throws JMSException { return new DynamicDestinationResolver().resolveDestinationName(session, queueName, false); }
[ "private", "Destination", "getDestination", "(", "Session", "session", ",", "String", "queueName", ")", "throws", "JMSException", "{", "return", "new", "DynamicDestinationResolver", "(", ")", ".", "resolveDestinationName", "(", "session", ",", "queueName", ",", "false", ")", ";", "}" ]
Resolves destination by given name. @param session @param queueName @return @throws JMSException
[ "Resolves", "destination", "by", "given", "name", "." ]
train
https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-jms/src/main/java/com/consol/citrus/jms/actions/PurgeJmsQueuesAction.java#L167-L169
guardtime/ksi-java-sdk
ksi-api/src/main/java/com/guardtime/ksi/unisignature/verifier/policies/ContextAwarePolicyAdapter.java
ContextAwarePolicyAdapter.createDefaultPolicy
public static ContextAwarePolicy createDefaultPolicy(PublicationsHandler handler, Extender extender) { """ Creates context aware policy using {@link DefaultVerificationPolicy} for verification. If extender is set, signature is extended within verification process. @param handler Publications handler. @param extender Extender. @return Context aware verification policy for default verification. """ Util.notNull(handler, "Publications handler"); return new ContextAwarePolicyAdapter(new DefaultVerificationPolicy(), new PolicyContext(handler, extender != null ? extender.getExtendingService() : null)); }
java
public static ContextAwarePolicy createDefaultPolicy(PublicationsHandler handler, Extender extender) { Util.notNull(handler, "Publications handler"); return new ContextAwarePolicyAdapter(new DefaultVerificationPolicy(), new PolicyContext(handler, extender != null ? extender.getExtendingService() : null)); }
[ "public", "static", "ContextAwarePolicy", "createDefaultPolicy", "(", "PublicationsHandler", "handler", ",", "Extender", "extender", ")", "{", "Util", ".", "notNull", "(", "handler", ",", "\"Publications handler\"", ")", ";", "return", "new", "ContextAwarePolicyAdapter", "(", "new", "DefaultVerificationPolicy", "(", ")", ",", "new", "PolicyContext", "(", "handler", ",", "extender", "!=", "null", "?", "extender", ".", "getExtendingService", "(", ")", ":", "null", ")", ")", ";", "}" ]
Creates context aware policy using {@link DefaultVerificationPolicy} for verification. If extender is set, signature is extended within verification process. @param handler Publications handler. @param extender Extender. @return Context aware verification policy for default verification.
[ "Creates", "context", "aware", "policy", "using", "{", "@link", "DefaultVerificationPolicy", "}", "for", "verification", ".", "If", "extender", "is", "set", "signature", "is", "extended", "within", "verification", "process", "." ]
train
https://github.com/guardtime/ksi-java-sdk/blob/b2cd877050f0f392657c724452318d10a1002171/ksi-api/src/main/java/com/guardtime/ksi/unisignature/verifier/policies/ContextAwarePolicyAdapter.java#L144-L148
facebookarchive/hadoop-20
src/hdfs/org/apache/hadoop/hdfs/qjournal/server/Journal.java
Journal.syncLog
File syncLog(RequestInfo reqInfo, final SegmentStateProto segment, final URL url) throws IOException { """ Synchronize a log segment from another JournalNode. The log is downloaded from the provided URL into a temporary location on disk, which is named based on the current request's epoch. @return the temporary location of the downloaded file """ long startTxId = segment.getStartTxId(); long epoch = reqInfo.getEpoch(); return syncLog(epoch, segment.getStartTxId(), url, segment.toString(), journalStorage.getSyncLogTemporaryFile(startTxId, epoch)); }
java
File syncLog(RequestInfo reqInfo, final SegmentStateProto segment, final URL url) throws IOException { long startTxId = segment.getStartTxId(); long epoch = reqInfo.getEpoch(); return syncLog(epoch, segment.getStartTxId(), url, segment.toString(), journalStorage.getSyncLogTemporaryFile(startTxId, epoch)); }
[ "File", "syncLog", "(", "RequestInfo", "reqInfo", ",", "final", "SegmentStateProto", "segment", ",", "final", "URL", "url", ")", "throws", "IOException", "{", "long", "startTxId", "=", "segment", ".", "getStartTxId", "(", ")", ";", "long", "epoch", "=", "reqInfo", ".", "getEpoch", "(", ")", ";", "return", "syncLog", "(", "epoch", ",", "segment", ".", "getStartTxId", "(", ")", ",", "url", ",", "segment", ".", "toString", "(", ")", ",", "journalStorage", ".", "getSyncLogTemporaryFile", "(", "startTxId", ",", "epoch", ")", ")", ";", "}" ]
Synchronize a log segment from another JournalNode. The log is downloaded from the provided URL into a temporary location on disk, which is named based on the current request's epoch. @return the temporary location of the downloaded file
[ "Synchronize", "a", "log", "segment", "from", "another", "JournalNode", ".", "The", "log", "is", "downloaded", "from", "the", "provided", "URL", "into", "a", "temporary", "location", "on", "disk", "which", "is", "named", "based", "on", "the", "current", "request", "s", "epoch", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/qjournal/server/Journal.java#L1166-L1172
febit/wit
wit-core/src/main/java/org/febit/wit_shaded/asm/ClassWriter.java
ClassWriter.newString
private Item newString(final String value) { """ Adds a string to the constant pool of the class being build. Does nothing if the constant pool already contains a similar item. @param value the String value. @return a new or already existing string item. """ Item result = get(key2.set(STR, value, null, null)); if (result == null) { pool.putBS(STR, newUTF8(value)); result = new Item(poolIndex++, key2); put(result); } return result; }
java
private Item newString(final String value) { Item result = get(key2.set(STR, value, null, null)); if (result == null) { pool.putBS(STR, newUTF8(value)); result = new Item(poolIndex++, key2); put(result); } return result; }
[ "private", "Item", "newString", "(", "final", "String", "value", ")", "{", "Item", "result", "=", "get", "(", "key2", ".", "set", "(", "STR", ",", "value", ",", "null", ",", "null", ")", ")", ";", "if", "(", "result", "==", "null", ")", "{", "pool", ".", "putBS", "(", "STR", ",", "newUTF8", "(", "value", ")", ")", ";", "result", "=", "new", "Item", "(", "poolIndex", "++", ",", "key2", ")", ";", "put", "(", "result", ")", ";", "}", "return", "result", ";", "}" ]
Adds a string to the constant pool of the class being build. Does nothing if the constant pool already contains a similar item. @param value the String value. @return a new or already existing string item.
[ "Adds", "a", "string", "to", "the", "constant", "pool", "of", "the", "class", "being", "build", ".", "Does", "nothing", "if", "the", "constant", "pool", "already", "contains", "a", "similar", "item", "." ]
train
https://github.com/febit/wit/blob/89ee29efbc5633b79c30c3c7b953c9f4130575af/wit-core/src/main/java/org/febit/wit_shaded/asm/ClassWriter.java#L684-L692
jbundle/jbundle
thin/base/screen/cal/other/src/main/java/org/jbundle/thin/base/screen/cal/popup/JBasePopupPanel.java
JBasePopupPanel.createComponentButton
public JComponent createComponentButton(String strProductType, BaseApplet applet) { """ Create the button/panel for this menu item. @param record The menu record. @return The component to add to this panel. """ ProductTypeInfo productType = ProductTypeInfo.getProductType(strProductType); if (productType == null) { ImageIcon icon = null; if (applet != null) icon = applet.loadImageIcon(strProductType, null); productType = new ProductTypeInfo(strProductType, icon, icon, 0x00c0c0c0, Colors.NULL); } JUnderlinedButton button = new JUnderlinedButton(productType.getDescription(), productType.getStartIcon()); String strLink = strProductType; button.setName(strLink); button.setOpaque(false); Color colorBackground = new Color(productType.getSelectColor()); button.setBackground(colorBackground); // Since the button is opaque, this is only needed for those look and feels that want their own background color. button.setBorderPainted(false); button.addActionListener(m_actionListener); button.addActionListener(this); return button; }
java
public JComponent createComponentButton(String strProductType, BaseApplet applet) { ProductTypeInfo productType = ProductTypeInfo.getProductType(strProductType); if (productType == null) { ImageIcon icon = null; if (applet != null) icon = applet.loadImageIcon(strProductType, null); productType = new ProductTypeInfo(strProductType, icon, icon, 0x00c0c0c0, Colors.NULL); } JUnderlinedButton button = new JUnderlinedButton(productType.getDescription(), productType.getStartIcon()); String strLink = strProductType; button.setName(strLink); button.setOpaque(false); Color colorBackground = new Color(productType.getSelectColor()); button.setBackground(colorBackground); // Since the button is opaque, this is only needed for those look and feels that want their own background color. button.setBorderPainted(false); button.addActionListener(m_actionListener); button.addActionListener(this); return button; }
[ "public", "JComponent", "createComponentButton", "(", "String", "strProductType", ",", "BaseApplet", "applet", ")", "{", "ProductTypeInfo", "productType", "=", "ProductTypeInfo", ".", "getProductType", "(", "strProductType", ")", ";", "if", "(", "productType", "==", "null", ")", "{", "ImageIcon", "icon", "=", "null", ";", "if", "(", "applet", "!=", "null", ")", "icon", "=", "applet", ".", "loadImageIcon", "(", "strProductType", ",", "null", ")", ";", "productType", "=", "new", "ProductTypeInfo", "(", "strProductType", ",", "icon", ",", "icon", ",", "0x00c0c0c0", ",", "Colors", ".", "NULL", ")", ";", "}", "JUnderlinedButton", "button", "=", "new", "JUnderlinedButton", "(", "productType", ".", "getDescription", "(", ")", ",", "productType", ".", "getStartIcon", "(", ")", ")", ";", "String", "strLink", "=", "strProductType", ";", "button", ".", "setName", "(", "strLink", ")", ";", "button", ".", "setOpaque", "(", "false", ")", ";", "Color", "colorBackground", "=", "new", "Color", "(", "productType", ".", "getSelectColor", "(", ")", ")", ";", "button", ".", "setBackground", "(", "colorBackground", ")", ";", "// Since the button is opaque, this is only needed for those look and feels that want their own background color.", "button", ".", "setBorderPainted", "(", "false", ")", ";", "button", ".", "addActionListener", "(", "m_actionListener", ")", ";", "button", ".", "addActionListener", "(", "this", ")", ";", "return", "button", ";", "}" ]
Create the button/panel for this menu item. @param record The menu record. @return The component to add to this panel.
[ "Create", "the", "button", "/", "panel", "for", "this", "menu", "item", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/thin/base/screen/cal/other/src/main/java/org/jbundle/thin/base/screen/cal/popup/JBasePopupPanel.java#L79-L101
apache/flink
flink-core/src/main/java/org/apache/flink/util/StringUtils.java
StringUtils.concatenateWithAnd
@Nullable public static String concatenateWithAnd(@Nullable String s1, @Nullable String s2) { """ If both string arguments are non-null, this method concatenates them with ' and '. If only one of the arguments is non-null, this method returns the non-null argument. If both arguments are null, this method returns null. @param s1 The first string argument @param s2 The second string argument @return The concatenated string, or non-null argument, or null """ if (s1 != null) { return s2 == null ? s1 : s1 + " and " + s2; } else { return s2; } }
java
@Nullable public static String concatenateWithAnd(@Nullable String s1, @Nullable String s2) { if (s1 != null) { return s2 == null ? s1 : s1 + " and " + s2; } else { return s2; } }
[ "@", "Nullable", "public", "static", "String", "concatenateWithAnd", "(", "@", "Nullable", "String", "s1", ",", "@", "Nullable", "String", "s2", ")", "{", "if", "(", "s1", "!=", "null", ")", "{", "return", "s2", "==", "null", "?", "s1", ":", "s1", "+", "\" and \"", "+", "s2", ";", "}", "else", "{", "return", "s2", ";", "}", "}" ]
If both string arguments are non-null, this method concatenates them with ' and '. If only one of the arguments is non-null, this method returns the non-null argument. If both arguments are null, this method returns null. @param s1 The first string argument @param s2 The second string argument @return The concatenated string, or non-null argument, or null
[ "If", "both", "string", "arguments", "are", "non", "-", "null", "this", "method", "concatenates", "them", "with", "and", ".", "If", "only", "one", "of", "the", "arguments", "is", "non", "-", "null", "this", "method", "returns", "the", "non", "-", "null", "argument", ".", "If", "both", "arguments", "are", "null", "this", "method", "returns", "null", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/util/StringUtils.java#L376-L384
cubedtear/aritzh
aritzh-core/src/main/java/io/github/aritzhack/aritzh/config/Configuration.java
Configuration.setDefault
public void setDefault(String category, String key, String value) { """ Sets the property, unless it already had a value @param category The category of the property @param key The identifier of the property @param value The value to set to the property """ if (this.hasProperty(category, key)) return; this.setProperty(category, key, value); }
java
public void setDefault(String category, String key, String value) { if (this.hasProperty(category, key)) return; this.setProperty(category, key, value); }
[ "public", "void", "setDefault", "(", "String", "category", ",", "String", "key", ",", "String", "value", ")", "{", "if", "(", "this", ".", "hasProperty", "(", "category", ",", "key", ")", ")", "return", ";", "this", ".", "setProperty", "(", "category", ",", "key", ",", "value", ")", ";", "}" ]
Sets the property, unless it already had a value @param category The category of the property @param key The identifier of the property @param value The value to set to the property
[ "Sets", "the", "property", "unless", "it", "already", "had", "a", "value" ]
train
https://github.com/cubedtear/aritzh/blob/bc7493447a1a6088c4a7306ca4d0f0c20278364f/aritzh-core/src/main/java/io/github/aritzhack/aritzh/config/Configuration.java#L250-L253
VoltDB/voltdb
src/frontend/org/voltcore/logging/VoltLogger.java
VoltLogger.execute
private void execute(final Level level, final Object message, final Throwable t) { """ /* Submit a task asynchronously to the thread to preserve message order, but don't wait for the task to complete for info, debug, trace, and warn """ if (!m_logger.isEnabledFor(level)) return; if (m_asynchLoggerPool == null) { m_logger.log(level, message, t); return; } final Runnable runnableLoggingTask = createRunnableLoggingTask(level, message, t); try { m_asynchLoggerPool.execute(runnableLoggingTask); } catch (RejectedExecutionException e) { m_logger.log(Level.DEBUG, "Failed to execute logging task. Running in-line", e); runnableLoggingTask.run(); } }
java
private void execute(final Level level, final Object message, final Throwable t) { if (!m_logger.isEnabledFor(level)) return; if (m_asynchLoggerPool == null) { m_logger.log(level, message, t); return; } final Runnable runnableLoggingTask = createRunnableLoggingTask(level, message, t); try { m_asynchLoggerPool.execute(runnableLoggingTask); } catch (RejectedExecutionException e) { m_logger.log(Level.DEBUG, "Failed to execute logging task. Running in-line", e); runnableLoggingTask.run(); } }
[ "private", "void", "execute", "(", "final", "Level", "level", ",", "final", "Object", "message", ",", "final", "Throwable", "t", ")", "{", "if", "(", "!", "m_logger", ".", "isEnabledFor", "(", "level", ")", ")", "return", ";", "if", "(", "m_asynchLoggerPool", "==", "null", ")", "{", "m_logger", ".", "log", "(", "level", ",", "message", ",", "t", ")", ";", "return", ";", "}", "final", "Runnable", "runnableLoggingTask", "=", "createRunnableLoggingTask", "(", "level", ",", "message", ",", "t", ")", ";", "try", "{", "m_asynchLoggerPool", ".", "execute", "(", "runnableLoggingTask", ")", ";", "}", "catch", "(", "RejectedExecutionException", "e", ")", "{", "m_logger", ".", "log", "(", "Level", ".", "DEBUG", ",", "\"Failed to execute logging task. Running in-line\"", ",", "e", ")", ";", "runnableLoggingTask", ".", "run", "(", ")", ";", "}", "}" ]
/* Submit a task asynchronously to the thread to preserve message order, but don't wait for the task to complete for info, debug, trace, and warn
[ "/", "*", "Submit", "a", "task", "asynchronously", "to", "the", "thread", "to", "preserve", "message", "order", "but", "don", "t", "wait", "for", "the", "task", "to", "complete", "for", "info", "debug", "trace", "and", "warn" ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltcore/logging/VoltLogger.java#L168-L183
gmessner/gitlab4j-api
src/main/java/org/gitlab4j/api/ProjectApi.java
ProjectApi.deleteHook
public void deleteHook(Object projectIdOrPath, Integer hookId) throws GitLabApiException { """ Deletes a hook from the project. <pre><code>DELETE /projects/:id/hooks/:hook_id</code></pre> @param projectIdOrPath projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance, required @param hookId the project hook ID to delete @throws GitLabApiException if any exception occurs """ Response.Status expectedStatus = (isApiVersion(ApiVersion.V3) ? Response.Status.OK : Response.Status.NO_CONTENT); delete(expectedStatus, null, "projects", getProjectIdOrPath(projectIdOrPath), "hooks", hookId); }
java
public void deleteHook(Object projectIdOrPath, Integer hookId) throws GitLabApiException { Response.Status expectedStatus = (isApiVersion(ApiVersion.V3) ? Response.Status.OK : Response.Status.NO_CONTENT); delete(expectedStatus, null, "projects", getProjectIdOrPath(projectIdOrPath), "hooks", hookId); }
[ "public", "void", "deleteHook", "(", "Object", "projectIdOrPath", ",", "Integer", "hookId", ")", "throws", "GitLabApiException", "{", "Response", ".", "Status", "expectedStatus", "=", "(", "isApiVersion", "(", "ApiVersion", ".", "V3", ")", "?", "Response", ".", "Status", ".", "OK", ":", "Response", ".", "Status", ".", "NO_CONTENT", ")", ";", "delete", "(", "expectedStatus", ",", "null", ",", "\"projects\"", ",", "getProjectIdOrPath", "(", "projectIdOrPath", ")", ",", "\"hooks\"", ",", "hookId", ")", ";", "}" ]
Deletes a hook from the project. <pre><code>DELETE /projects/:id/hooks/:hook_id</code></pre> @param projectIdOrPath projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance, required @param hookId the project hook ID to delete @throws GitLabApiException if any exception occurs
[ "Deletes", "a", "hook", "from", "the", "project", "." ]
train
https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/ProjectApi.java#L1738-L1741
leancloud/java-sdk-all
realtime/src/main/java/cn/leancloud/im/v2/AVIMConversation.java
AVIMConversation.queryBlockedMembers
public void queryBlockedMembers(int offset, int limit, final AVIMConversationSimpleResultCallback callback) { """ 查询黑名单的成员列表 @param offset 查询结果的起始点 @param limit 查询结果集上限 @param callback 结果回调函数 """ if (null == callback) { return; } else if (offset < 0 || limit > 100) { callback.internalDone(null, new AVIMException(new IllegalArgumentException("offset/limit is illegal."))); return; } Map<String, Object> params = new HashMap<String, Object>(); params.put(Conversation.QUERY_PARAM_LIMIT, limit); params.put(Conversation.QUERY_PARAM_OFFSET, offset); boolean ret = InternalConfiguration.getOperationTube().processMembers(this.client.getClientId(), this.conversationId, getType(), JSON.toJSONString(params), Conversation.AVIMOperation.CONVERSATION_BLOCKED_MEMBER_QUERY, callback); if (!ret) { callback.internalDone(null, new AVException(AVException.OPERATION_FORBIDDEN, "couldn't start service in background.")); } }
java
public void queryBlockedMembers(int offset, int limit, final AVIMConversationSimpleResultCallback callback) { if (null == callback) { return; } else if (offset < 0 || limit > 100) { callback.internalDone(null, new AVIMException(new IllegalArgumentException("offset/limit is illegal."))); return; } Map<String, Object> params = new HashMap<String, Object>(); params.put(Conversation.QUERY_PARAM_LIMIT, limit); params.put(Conversation.QUERY_PARAM_OFFSET, offset); boolean ret = InternalConfiguration.getOperationTube().processMembers(this.client.getClientId(), this.conversationId, getType(), JSON.toJSONString(params), Conversation.AVIMOperation.CONVERSATION_BLOCKED_MEMBER_QUERY, callback); if (!ret) { callback.internalDone(null, new AVException(AVException.OPERATION_FORBIDDEN, "couldn't start service in background.")); } }
[ "public", "void", "queryBlockedMembers", "(", "int", "offset", ",", "int", "limit", ",", "final", "AVIMConversationSimpleResultCallback", "callback", ")", "{", "if", "(", "null", "==", "callback", ")", "{", "return", ";", "}", "else", "if", "(", "offset", "<", "0", "||", "limit", ">", "100", ")", "{", "callback", ".", "internalDone", "(", "null", ",", "new", "AVIMException", "(", "new", "IllegalArgumentException", "(", "\"offset/limit is illegal.\"", ")", ")", ")", ";", "return", ";", "}", "Map", "<", "String", ",", "Object", ">", "params", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "params", ".", "put", "(", "Conversation", ".", "QUERY_PARAM_LIMIT", ",", "limit", ")", ";", "params", ".", "put", "(", "Conversation", ".", "QUERY_PARAM_OFFSET", ",", "offset", ")", ";", "boolean", "ret", "=", "InternalConfiguration", ".", "getOperationTube", "(", ")", ".", "processMembers", "(", "this", ".", "client", ".", "getClientId", "(", ")", ",", "this", ".", "conversationId", ",", "getType", "(", ")", ",", "JSON", ".", "toJSONString", "(", "params", ")", ",", "Conversation", ".", "AVIMOperation", ".", "CONVERSATION_BLOCKED_MEMBER_QUERY", ",", "callback", ")", ";", "if", "(", "!", "ret", ")", "{", "callback", ".", "internalDone", "(", "null", ",", "new", "AVException", "(", "AVException", ".", "OPERATION_FORBIDDEN", ",", "\"couldn't start service in background.\"", ")", ")", ";", "}", "}" ]
查询黑名单的成员列表 @param offset 查询结果的起始点 @param limit 查询结果集上限 @param callback 结果回调函数
[ "查询黑名单的成员列表" ]
train
https://github.com/leancloud/java-sdk-all/blob/323f8e7ee38051b1350790e5192304768c5c9f5f/realtime/src/main/java/cn/leancloud/im/v2/AVIMConversation.java#L1337-L1353
elki-project/elki
addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/svg/SVGPath.java
SVGPath.relativeCubicTo
public SVGPath relativeCubicTo(double[] c1xy, double[] c2xy, double[] xy) { """ Cubic Bezier line to the given relative coordinates. @param c1xy first control point @param c2xy second control point @param xy new coordinates @return path object, for compact syntax. """ return append(PATH_CUBIC_TO_RELATIVE).append(c1xy[0]).append(c1xy[1]).append(c2xy[0]).append(c2xy[1]).append(xy[0]).append(xy[1]); }
java
public SVGPath relativeCubicTo(double[] c1xy, double[] c2xy, double[] xy) { return append(PATH_CUBIC_TO_RELATIVE).append(c1xy[0]).append(c1xy[1]).append(c2xy[0]).append(c2xy[1]).append(xy[0]).append(xy[1]); }
[ "public", "SVGPath", "relativeCubicTo", "(", "double", "[", "]", "c1xy", ",", "double", "[", "]", "c2xy", ",", "double", "[", "]", "xy", ")", "{", "return", "append", "(", "PATH_CUBIC_TO_RELATIVE", ")", ".", "append", "(", "c1xy", "[", "0", "]", ")", ".", "append", "(", "c1xy", "[", "1", "]", ")", ".", "append", "(", "c2xy", "[", "0", "]", ")", ".", "append", "(", "c2xy", "[", "1", "]", ")", ".", "append", "(", "xy", "[", "0", "]", ")", ".", "append", "(", "xy", "[", "1", "]", ")", ";", "}" ]
Cubic Bezier line to the given relative coordinates. @param c1xy first control point @param c2xy second control point @param xy new coordinates @return path object, for compact syntax.
[ "Cubic", "Bezier", "line", "to", "the", "given", "relative", "coordinates", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/svg/SVGPath.java#L396-L398
j-easy/easy-batch
easybatch-extensions/easybatch-quartz/src/main/java/org/easybatch/extensions/quartz/JobScheduler.java
JobScheduler.scheduleAtWithInterval
public void scheduleAtWithInterval(final org.easybatch.core.job.Job job, final Date startTime, final int interval) throws JobSchedulerException { """ Schedule a job to start at a fixed point of time and repeat with interval period. @param job the job to schedule @param startTime the start time @param interval the repeat interval in seconds """ checkNotNull(job, "job"); checkNotNull(startTime, "startTime"); String name = job.getName(); String jobName = JOB_NAME_PREFIX + name; String triggerName = TRIGGER_NAME_PREFIX + name; SimpleScheduleBuilder scheduleBuilder = simpleSchedule() .withIntervalInSeconds(interval) .repeatForever(); Trigger trigger = newTrigger() .withIdentity(triggerName) .startAt(startTime) .withSchedule(scheduleBuilder) .forJob(jobName) .build(); JobDetail jobDetail = getJobDetail(job, jobName); try { LOGGER.info("Scheduling job ''{}'' to start at {} and every {} second(s)", name, startTime, interval); scheduler.scheduleJob(jobDetail, trigger); } catch (SchedulerException e) { throw new JobSchedulerException(format("Unable to schedule job '%s'", name), e); } }
java
public void scheduleAtWithInterval(final org.easybatch.core.job.Job job, final Date startTime, final int interval) throws JobSchedulerException { checkNotNull(job, "job"); checkNotNull(startTime, "startTime"); String name = job.getName(); String jobName = JOB_NAME_PREFIX + name; String triggerName = TRIGGER_NAME_PREFIX + name; SimpleScheduleBuilder scheduleBuilder = simpleSchedule() .withIntervalInSeconds(interval) .repeatForever(); Trigger trigger = newTrigger() .withIdentity(triggerName) .startAt(startTime) .withSchedule(scheduleBuilder) .forJob(jobName) .build(); JobDetail jobDetail = getJobDetail(job, jobName); try { LOGGER.info("Scheduling job ''{}'' to start at {} and every {} second(s)", name, startTime, interval); scheduler.scheduleJob(jobDetail, trigger); } catch (SchedulerException e) { throw new JobSchedulerException(format("Unable to schedule job '%s'", name), e); } }
[ "public", "void", "scheduleAtWithInterval", "(", "final", "org", ".", "easybatch", ".", "core", ".", "job", ".", "Job", "job", ",", "final", "Date", "startTime", ",", "final", "int", "interval", ")", "throws", "JobSchedulerException", "{", "checkNotNull", "(", "job", ",", "\"job\"", ")", ";", "checkNotNull", "(", "startTime", ",", "\"startTime\"", ")", ";", "String", "name", "=", "job", ".", "getName", "(", ")", ";", "String", "jobName", "=", "JOB_NAME_PREFIX", "+", "name", ";", "String", "triggerName", "=", "TRIGGER_NAME_PREFIX", "+", "name", ";", "SimpleScheduleBuilder", "scheduleBuilder", "=", "simpleSchedule", "(", ")", ".", "withIntervalInSeconds", "(", "interval", ")", ".", "repeatForever", "(", ")", ";", "Trigger", "trigger", "=", "newTrigger", "(", ")", ".", "withIdentity", "(", "triggerName", ")", ".", "startAt", "(", "startTime", ")", ".", "withSchedule", "(", "scheduleBuilder", ")", ".", "forJob", "(", "jobName", ")", ".", "build", "(", ")", ";", "JobDetail", "jobDetail", "=", "getJobDetail", "(", "job", ",", "jobName", ")", ";", "try", "{", "LOGGER", ".", "info", "(", "\"Scheduling job ''{}'' to start at {} and every {} second(s)\"", ",", "name", ",", "startTime", ",", "interval", ")", ";", "scheduler", ".", "scheduleJob", "(", "jobDetail", ",", "trigger", ")", ";", "}", "catch", "(", "SchedulerException", "e", ")", "{", "throw", "new", "JobSchedulerException", "(", "format", "(", "\"Unable to schedule job '%s'\"", ",", "name", ")", ",", "e", ")", ";", "}", "}" ]
Schedule a job to start at a fixed point of time and repeat with interval period. @param job the job to schedule @param startTime the start time @param interval the repeat interval in seconds
[ "Schedule", "a", "job", "to", "start", "at", "a", "fixed", "point", "of", "time", "and", "repeat", "with", "interval", "period", "." ]
train
https://github.com/j-easy/easy-batch/blob/46286e1091dae1206674e2a30e0609c31feae36c/easybatch-extensions/easybatch-quartz/src/main/java/org/easybatch/extensions/quartz/JobScheduler.java#L174-L201
RobotiumTech/robotium
robotium-solo/src/main/java/com/robotium/solo/Solo.java
Solo.startScreenshotSequence
public void startScreenshotSequence(String name, int quality, int frameDelay, int maxFrames) { """ Takes a screenshot sequence and saves the images with the specified name prefix in the {@link Config} objects save path (default set to: /sdcard/Robotium-Screenshots/). The name prefix is appended with "_" + sequence_number for each image in the sequence, where numbering starts at 0. Requires write permission (android.permission.WRITE_EXTERNAL_STORAGE) in the AndroidManifest.xml of the application under test. Taking a screenshot will take on the order of 40-100 milliseconds of time on the main UI thread. Therefore it is possible to mess up the timing of tests if the frameDelay value is set too small. At present multiple simultaneous screenshot sequences are not supported. This method will throw an exception if stopScreenshotSequence() has not been called to finish any prior sequences. @param name the name prefix to give the screenshot @param quality the compression rate. From 0 (compress for lowest size) to 100 (compress for maximum quality) @param frameDelay the time in milliseconds to wait between each frame @param maxFrames the maximum number of frames that will comprise this sequence """ if(config.commandLogging){ Log.d(config.commandLoggingTag, "startScreenshotSequence(\""+name+"\", "+quality+", "+frameDelay+", "+maxFrames+")"); } screenshotTaker.startScreenshotSequence(name, quality, frameDelay, maxFrames); }
java
public void startScreenshotSequence(String name, int quality, int frameDelay, int maxFrames) { if(config.commandLogging){ Log.d(config.commandLoggingTag, "startScreenshotSequence(\""+name+"\", "+quality+", "+frameDelay+", "+maxFrames+")"); } screenshotTaker.startScreenshotSequence(name, quality, frameDelay, maxFrames); }
[ "public", "void", "startScreenshotSequence", "(", "String", "name", ",", "int", "quality", ",", "int", "frameDelay", ",", "int", "maxFrames", ")", "{", "if", "(", "config", ".", "commandLogging", ")", "{", "Log", ".", "d", "(", "config", ".", "commandLoggingTag", ",", "\"startScreenshotSequence(\\\"\"", "+", "name", "+", "\"\\\", \"", "+", "quality", "+", "\", \"", "+", "frameDelay", "+", "\", \"", "+", "maxFrames", "+", "\")\"", ")", ";", "}", "screenshotTaker", ".", "startScreenshotSequence", "(", "name", ",", "quality", ",", "frameDelay", ",", "maxFrames", ")", ";", "}" ]
Takes a screenshot sequence and saves the images with the specified name prefix in the {@link Config} objects save path (default set to: /sdcard/Robotium-Screenshots/). The name prefix is appended with "_" + sequence_number for each image in the sequence, where numbering starts at 0. Requires write permission (android.permission.WRITE_EXTERNAL_STORAGE) in the AndroidManifest.xml of the application under test. Taking a screenshot will take on the order of 40-100 milliseconds of time on the main UI thread. Therefore it is possible to mess up the timing of tests if the frameDelay value is set too small. At present multiple simultaneous screenshot sequences are not supported. This method will throw an exception if stopScreenshotSequence() has not been called to finish any prior sequences. @param name the name prefix to give the screenshot @param quality the compression rate. From 0 (compress for lowest size) to 100 (compress for maximum quality) @param frameDelay the time in milliseconds to wait between each frame @param maxFrames the maximum number of frames that will comprise this sequence
[ "Takes", "a", "screenshot", "sequence", "and", "saves", "the", "images", "with", "the", "specified", "name", "prefix", "in", "the", "{", "@link", "Config", "}", "objects", "save", "path", "(", "default", "set", "to", ":", "/", "sdcard", "/", "Robotium", "-", "Screenshots", "/", ")", "." ]
train
https://github.com/RobotiumTech/robotium/blob/75e567c38f26a6a87dc8bef90b3886a20e28d291/robotium-solo/src/main/java/com/robotium/solo/Solo.java#L3934-L3940
fozziethebeat/S-Space
src/main/java/edu/ucla/sspace/matrix/AtomicGrowingSparseHashMatrix.java
AtomicGrowingSparseHashMatrix.lockColumn
private void lockColumn(int col, int rowsToLock) { """ Locks all the row entries for this column, thereby preventing write or read access to the values. Note that the number of rows to lock <b>must</b> be the same value used with {@link #unlockColumn(int,int)}, otherwise the unlock may potentially unlock matrix entries associated with this lock call. @param col the column to lock @param rowsToLock the number of rows to lock. This value should be the number of {@link #rows} at the time of the call. """ // Put in an entry for all the columns's rows for (int row = 0; row < rowsToLock; ++row) { Entry e = new Entry(row, col); // Spin waiting for the entry to be unlocked while (lockedEntries.putIfAbsent(e, new Object()) != null) ; } }
java
private void lockColumn(int col, int rowsToLock) { // Put in an entry for all the columns's rows for (int row = 0; row < rowsToLock; ++row) { Entry e = new Entry(row, col); // Spin waiting for the entry to be unlocked while (lockedEntries.putIfAbsent(e, new Object()) != null) ; } }
[ "private", "void", "lockColumn", "(", "int", "col", ",", "int", "rowsToLock", ")", "{", "// Put in an entry for all the columns's rows", "for", "(", "int", "row", "=", "0", ";", "row", "<", "rowsToLock", ";", "++", "row", ")", "{", "Entry", "e", "=", "new", "Entry", "(", "row", ",", "col", ")", ";", "// Spin waiting for the entry to be unlocked", "while", "(", "lockedEntries", ".", "putIfAbsent", "(", "e", ",", "new", "Object", "(", ")", ")", "!=", "null", ")", ";", "}", "}" ]
Locks all the row entries for this column, thereby preventing write or read access to the values. Note that the number of rows to lock <b>must</b> be the same value used with {@link #unlockColumn(int,int)}, otherwise the unlock may potentially unlock matrix entries associated with this lock call. @param col the column to lock @param rowsToLock the number of rows to lock. This value should be the number of {@link #rows} at the time of the call.
[ "Locks", "all", "the", "row", "entries", "for", "this", "column", "thereby", "preventing", "write", "or", "read", "access", "to", "the", "values", ".", "Note", "that", "the", "number", "of", "rows", "to", "lock", "<b", ">", "must<", "/", "b", ">", "be", "the", "same", "value", "used", "with", "{", "@link", "#unlockColumn", "(", "int", "int", ")", "}", "otherwise", "the", "unlock", "may", "potentially", "unlock", "matrix", "entries", "associated", "with", "this", "lock", "call", "." ]
train
https://github.com/fozziethebeat/S-Space/blob/a608102737dfd3d59038a9ead33fe60356bc6029/src/main/java/edu/ucla/sspace/matrix/AtomicGrowingSparseHashMatrix.java#L380-L388
Omertron/api-themoviedb
src/main/java/com/omertron/themoviedbapi/methods/TmdbMovies.java
TmdbMovies.postMovieRating
public StatusCode postMovieRating(int movieId, int rating, String sessionId, String guestSessionId) throws MovieDbException { """ This method lets users rate a movie. A valid session id or guest session id is required. @param sessionId @param movieId @param rating @param guestSessionId @return @throws MovieDbException """ if (rating < 0 || rating > RATING_MAX) { throw new MovieDbException(ApiExceptionType.UNKNOWN_CAUSE, "Rating out of range"); } TmdbParameters parameters = new TmdbParameters(); parameters.add(Param.ID, movieId); parameters.add(Param.SESSION_ID, sessionId); parameters.add(Param.GUEST_SESSION_ID, guestSessionId); URL url = new ApiUrl(apiKey, MethodBase.MOVIE).subMethod(MethodSub.RATING).buildUrl(parameters); String jsonBody = new PostTools() .add(PostBody.VALUE, rating) .build(); String webpage = httpTools.postRequest(url, jsonBody); try { return MAPPER.readValue(webpage, StatusCode.class); } catch (IOException ex) { throw new MovieDbException(ApiExceptionType.MAPPING_FAILED, "Failed to post rating", url, ex); } }
java
public StatusCode postMovieRating(int movieId, int rating, String sessionId, String guestSessionId) throws MovieDbException { if (rating < 0 || rating > RATING_MAX) { throw new MovieDbException(ApiExceptionType.UNKNOWN_CAUSE, "Rating out of range"); } TmdbParameters parameters = new TmdbParameters(); parameters.add(Param.ID, movieId); parameters.add(Param.SESSION_ID, sessionId); parameters.add(Param.GUEST_SESSION_ID, guestSessionId); URL url = new ApiUrl(apiKey, MethodBase.MOVIE).subMethod(MethodSub.RATING).buildUrl(parameters); String jsonBody = new PostTools() .add(PostBody.VALUE, rating) .build(); String webpage = httpTools.postRequest(url, jsonBody); try { return MAPPER.readValue(webpage, StatusCode.class); } catch (IOException ex) { throw new MovieDbException(ApiExceptionType.MAPPING_FAILED, "Failed to post rating", url, ex); } }
[ "public", "StatusCode", "postMovieRating", "(", "int", "movieId", ",", "int", "rating", ",", "String", "sessionId", ",", "String", "guestSessionId", ")", "throws", "MovieDbException", "{", "if", "(", "rating", "<", "0", "||", "rating", ">", "RATING_MAX", ")", "{", "throw", "new", "MovieDbException", "(", "ApiExceptionType", ".", "UNKNOWN_CAUSE", ",", "\"Rating out of range\"", ")", ";", "}", "TmdbParameters", "parameters", "=", "new", "TmdbParameters", "(", ")", ";", "parameters", ".", "add", "(", "Param", ".", "ID", ",", "movieId", ")", ";", "parameters", ".", "add", "(", "Param", ".", "SESSION_ID", ",", "sessionId", ")", ";", "parameters", ".", "add", "(", "Param", ".", "GUEST_SESSION_ID", ",", "guestSessionId", ")", ";", "URL", "url", "=", "new", "ApiUrl", "(", "apiKey", ",", "MethodBase", ".", "MOVIE", ")", ".", "subMethod", "(", "MethodSub", ".", "RATING", ")", ".", "buildUrl", "(", "parameters", ")", ";", "String", "jsonBody", "=", "new", "PostTools", "(", ")", ".", "add", "(", "PostBody", ".", "VALUE", ",", "rating", ")", ".", "build", "(", ")", ";", "String", "webpage", "=", "httpTools", ".", "postRequest", "(", "url", ",", "jsonBody", ")", ";", "try", "{", "return", "MAPPER", ".", "readValue", "(", "webpage", ",", "StatusCode", ".", "class", ")", ";", "}", "catch", "(", "IOException", "ex", ")", "{", "throw", "new", "MovieDbException", "(", "ApiExceptionType", ".", "MAPPING_FAILED", ",", "\"Failed to post rating\"", ",", "url", ",", "ex", ")", ";", "}", "}" ]
This method lets users rate a movie. A valid session id or guest session id is required. @param sessionId @param movieId @param rating @param guestSessionId @return @throws MovieDbException
[ "This", "method", "lets", "users", "rate", "a", "movie", "." ]
train
https://github.com/Omertron/api-themoviedb/blob/bf132d7c7271734e13b58ba3bc92bba46f220118/src/main/java/com/omertron/themoviedbapi/methods/TmdbMovies.java#L476-L498
dbracewell/mango
src/main/java/com/davidbracewell/json/JsonReader.java
JsonReader.nextSimpleValue
protected Val nextSimpleValue() throws IOException { """ Next simple value val. @return the val @throws IOException the io exception """ switch (currentValue.getKey()) { case NULL: case STRING: case BOOLEAN: case NUMBER: Val object = currentValue.v2; consume(); return object; default: throw new IOException("Expecting VALUE, but found " + jsonTokenToStructuredElement(null)); } }
java
protected Val nextSimpleValue() throws IOException { switch (currentValue.getKey()) { case NULL: case STRING: case BOOLEAN: case NUMBER: Val object = currentValue.v2; consume(); return object; default: throw new IOException("Expecting VALUE, but found " + jsonTokenToStructuredElement(null)); } }
[ "protected", "Val", "nextSimpleValue", "(", ")", "throws", "IOException", "{", "switch", "(", "currentValue", ".", "getKey", "(", ")", ")", "{", "case", "NULL", ":", "case", "STRING", ":", "case", "BOOLEAN", ":", "case", "NUMBER", ":", "Val", "object", "=", "currentValue", ".", "v2", ";", "consume", "(", ")", ";", "return", "object", ";", "default", ":", "throw", "new", "IOException", "(", "\"Expecting VALUE, but found \"", "+", "jsonTokenToStructuredElement", "(", "null", ")", ")", ";", "}", "}" ]
Next simple value val. @return the val @throws IOException the io exception
[ "Next", "simple", "value", "val", "." ]
train
https://github.com/dbracewell/mango/blob/2cec08826f1fccd658694dd03abce10fc97618ec/src/main/java/com/davidbracewell/json/JsonReader.java#L567-L579
whitesource/agents
wss-agent-report/src/main/java/org/whitesource/agent/report/FileUtils.java
FileUtils.packDirectory
public static void packDirectory(File dir, ZipOutputStream zos) throws IOException { """ Pack a directory into a single zip file. <p> <b>Note:</b> The implementation is based on the packZip method in jetbrains openAPI. original author is Maxim Podkolzine ([email protected]) </p> @param dir input @param zos output stream @throws IOException exception1 """ byte[] buffer = new byte[64 * 1024]; // a reusable buffer try { traverseAndWrite(dir, zos, new StringBuilder(), true, buffer); } finally { close(zos); } }
java
public static void packDirectory(File dir, ZipOutputStream zos) throws IOException { byte[] buffer = new byte[64 * 1024]; // a reusable buffer try { traverseAndWrite(dir, zos, new StringBuilder(), true, buffer); } finally { close(zos); } }
[ "public", "static", "void", "packDirectory", "(", "File", "dir", ",", "ZipOutputStream", "zos", ")", "throws", "IOException", "{", "byte", "[", "]", "buffer", "=", "new", "byte", "[", "64", "*", "1024", "]", ";", "// a reusable buffer\r", "try", "{", "traverseAndWrite", "(", "dir", ",", "zos", ",", "new", "StringBuilder", "(", ")", ",", "true", ",", "buffer", ")", ";", "}", "finally", "{", "close", "(", "zos", ")", ";", "}", "}" ]
Pack a directory into a single zip file. <p> <b>Note:</b> The implementation is based on the packZip method in jetbrains openAPI. original author is Maxim Podkolzine ([email protected]) </p> @param dir input @param zos output stream @throws IOException exception1
[ "Pack", "a", "directory", "into", "a", "single", "zip", "file", ".", "<p", ">", "<b", ">", "Note", ":", "<", "/", "b", ">", "The", "implementation", "is", "based", "on", "the", "packZip", "method", "in", "jetbrains", "openAPI", ".", "original", "author", "is", "Maxim", "Podkolzine", "(", "maxim", ".", "podkolzine@jetbrains", ".", "com", ")", "<", "/", "p", ">" ]
train
https://github.com/whitesource/agents/blob/8a947a3dbad257aff70f23f79fb3a55ca90b765f/wss-agent-report/src/main/java/org/whitesource/agent/report/FileUtils.java#L84-L91
codeprimate-software/cp-elements
src/main/java/org/cp/elements/lang/Assert.java
Assert.notEmpty
public static void notEmpty(String value, Supplier<String> message) { """ Asserts that the given {@link String} is not empty. The assertion holds if and only if the {@link String String} is not the {@link String#isEmpty() empty String}. @param value {@link String} to evaluate. @param message {@link Supplier} containing the message used in the {@link IllegalArgumentException} thrown if the assertion fails. @throws java.lang.IllegalArgumentException if the {@link String} is empty. @see java.lang.String """ if (isEmpty(value)) { throw new IllegalArgumentException(message.get()); } }
java
public static void notEmpty(String value, Supplier<String> message) { if (isEmpty(value)) { throw new IllegalArgumentException(message.get()); } }
[ "public", "static", "void", "notEmpty", "(", "String", "value", ",", "Supplier", "<", "String", ">", "message", ")", "{", "if", "(", "isEmpty", "(", "value", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "message", ".", "get", "(", ")", ")", ";", "}", "}" ]
Asserts that the given {@link String} is not empty. The assertion holds if and only if the {@link String String} is not the {@link String#isEmpty() empty String}. @param value {@link String} to evaluate. @param message {@link Supplier} containing the message used in the {@link IllegalArgumentException} thrown if the assertion fails. @throws java.lang.IllegalArgumentException if the {@link String} is empty. @see java.lang.String
[ "Asserts", "that", "the", "given", "{", "@link", "String", "}", "is", "not", "empty", "." ]
train
https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/lang/Assert.java#L896-L900
UrielCh/ovh-java-sdk
ovh-java-sdk-price/src/main/java/net/minidev/ovh/api/ApiOvhPrice.java
ApiOvhPrice.hosting_web_extraSqlPerso_extraSqlPersoName_GET
public OvhPrice hosting_web_extraSqlPerso_extraSqlPersoName_GET(net.minidev.ovh.api.price.hosting.web.OvhExtraSqlPersoEnum extraSqlPersoName) throws IOException { """ Get the price for extra sql perso option REST: GET /price/hosting/web/extraSqlPerso/{extraSqlPersoName} @param extraSqlPersoName [required] ExtraSqlPerso """ String qPath = "/price/hosting/web/extraSqlPerso/{extraSqlPersoName}"; StringBuilder sb = path(qPath, extraSqlPersoName); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhPrice.class); }
java
public OvhPrice hosting_web_extraSqlPerso_extraSqlPersoName_GET(net.minidev.ovh.api.price.hosting.web.OvhExtraSqlPersoEnum extraSqlPersoName) throws IOException { String qPath = "/price/hosting/web/extraSqlPerso/{extraSqlPersoName}"; StringBuilder sb = path(qPath, extraSqlPersoName); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhPrice.class); }
[ "public", "OvhPrice", "hosting_web_extraSqlPerso_extraSqlPersoName_GET", "(", "net", ".", "minidev", ".", "ovh", ".", "api", ".", "price", ".", "hosting", ".", "web", ".", "OvhExtraSqlPersoEnum", "extraSqlPersoName", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/price/hosting/web/extraSqlPerso/{extraSqlPersoName}\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "extraSqlPersoName", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"GET\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhPrice", ".", "class", ")", ";", "}" ]
Get the price for extra sql perso option REST: GET /price/hosting/web/extraSqlPerso/{extraSqlPersoName} @param extraSqlPersoName [required] ExtraSqlPerso
[ "Get", "the", "price", "for", "extra", "sql", "perso", "option" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-price/src/main/java/net/minidev/ovh/api/ApiOvhPrice.java#L258-L263
canoo/dolphin-platform
platform/dolphin-platform-remoting-server/src/main/java/com/canoo/dp/impl/server/gc/GarbageCollector.java
GarbageCollector.onPropertyValueChanged
public synchronized void onPropertyValueChanged(Property property, Object oldValue, Object newValue) { """ This method must be called for each value change of a {@link Property} @param property the property @param oldValue the old value @param newValue the new value """ if (!configuration.isUseGc()) { return; } removeReferenceAndCheckForGC(property, oldValue); if (newValue != null && DolphinUtils.isDolphinBean(newValue.getClass())) { Instance instance = getInstance(newValue); Reference reference = new PropertyReference(propertyToParent.get(property), property, instance); if (reference.hasCircularReference()) { throw new CircularDependencyException("Circular dependency detected!"); } instance.getReferences().add(reference); removeFromGC(instance); } }
java
public synchronized void onPropertyValueChanged(Property property, Object oldValue, Object newValue) { if (!configuration.isUseGc()) { return; } removeReferenceAndCheckForGC(property, oldValue); if (newValue != null && DolphinUtils.isDolphinBean(newValue.getClass())) { Instance instance = getInstance(newValue); Reference reference = new PropertyReference(propertyToParent.get(property), property, instance); if (reference.hasCircularReference()) { throw new CircularDependencyException("Circular dependency detected!"); } instance.getReferences().add(reference); removeFromGC(instance); } }
[ "public", "synchronized", "void", "onPropertyValueChanged", "(", "Property", "property", ",", "Object", "oldValue", ",", "Object", "newValue", ")", "{", "if", "(", "!", "configuration", ".", "isUseGc", "(", ")", ")", "{", "return", ";", "}", "removeReferenceAndCheckForGC", "(", "property", ",", "oldValue", ")", ";", "if", "(", "newValue", "!=", "null", "&&", "DolphinUtils", ".", "isDolphinBean", "(", "newValue", ".", "getClass", "(", ")", ")", ")", "{", "Instance", "instance", "=", "getInstance", "(", "newValue", ")", ";", "Reference", "reference", "=", "new", "PropertyReference", "(", "propertyToParent", ".", "get", "(", "property", ")", ",", "property", ",", "instance", ")", ";", "if", "(", "reference", ".", "hasCircularReference", "(", ")", ")", "{", "throw", "new", "CircularDependencyException", "(", "\"Circular dependency detected!\"", ")", ";", "}", "instance", ".", "getReferences", "(", ")", ".", "add", "(", "reference", ")", ";", "removeFromGC", "(", "instance", ")", ";", "}", "}" ]
This method must be called for each value change of a {@link Property} @param property the property @param oldValue the old value @param newValue the new value
[ "This", "method", "must", "be", "called", "for", "each", "value", "change", "of", "a", "{", "@link", "Property", "}" ]
train
https://github.com/canoo/dolphin-platform/blob/fb99c1fab24df80d2fa094d8688b546140146874/platform/dolphin-platform-remoting-server/src/main/java/com/canoo/dp/impl/server/gc/GarbageCollector.java#L149-L164
couchbase/couchbase-java-client
src/main/java/com/couchbase/client/java/query/dsl/functions/ConditionalFunctions.java
ConditionalFunctions.nullIf
public static Expression nullIf(Expression expression1, Expression expression2) { """ Returned expression results in NULL if expression1 = expression2, otherwise returns expression1. Returns MISSING or NULL if either input is MISSING or NULL.. """ return x("NULLIF(" + expression1.toString() + ", " + expression2.toString() + ")"); }
java
public static Expression nullIf(Expression expression1, Expression expression2) { return x("NULLIF(" + expression1.toString() + ", " + expression2.toString() + ")"); }
[ "public", "static", "Expression", "nullIf", "(", "Expression", "expression1", ",", "Expression", "expression2", ")", "{", "return", "x", "(", "\"NULLIF(\"", "+", "expression1", ".", "toString", "(", ")", "+", "\", \"", "+", "expression2", ".", "toString", "(", ")", "+", "\")\"", ")", ";", "}" ]
Returned expression results in NULL if expression1 = expression2, otherwise returns expression1. Returns MISSING or NULL if either input is MISSING or NULL..
[ "Returned", "expression", "results", "in", "NULL", "if", "expression1", "=", "expression2", "otherwise", "returns", "expression1", ".", "Returns", "MISSING", "or", "NULL", "if", "either", "input", "is", "MISSING", "or", "NULL", ".." ]
train
https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/query/dsl/functions/ConditionalFunctions.java#L91-L93
googleapis/cloud-bigtable-client
bigtable-hbase-1.x-parent/bigtable-hbase-1.x-mapreduce/src/main/java/com/google/cloud/bigtable/mapreduce/Import.java
Import.filterKv
public static Cell filterKv(Filter filter, Cell kv) throws IOException { """ Attempt to filter out the keyvalue @param kv {@link org.apache.hadoop.hbase.KeyValue} on which to apply the filter @return <tt>null</tt> if the key should not be written, otherwise returns the original {@link org.apache.hadoop.hbase.KeyValue} @param filter a {@link org.apache.hadoop.hbase.filter.Filter} object. @throws java.io.IOException if any. """ // apply the filter and skip this kv if the filter doesn't apply if (filter != null) { Filter.ReturnCode code = filter.filterKeyValue(kv); if (LOG.isTraceEnabled()) { LOG.trace("Filter returned:" + code + " for the key value:" + kv); } // if its not an accept type, then skip this kv if (!(code.equals(Filter.ReturnCode.INCLUDE) || code .equals(Filter.ReturnCode.INCLUDE_AND_NEXT_COL))) { return null; } } return kv; }
java
public static Cell filterKv(Filter filter, Cell kv) throws IOException { // apply the filter and skip this kv if the filter doesn't apply if (filter != null) { Filter.ReturnCode code = filter.filterKeyValue(kv); if (LOG.isTraceEnabled()) { LOG.trace("Filter returned:" + code + " for the key value:" + kv); } // if its not an accept type, then skip this kv if (!(code.equals(Filter.ReturnCode.INCLUDE) || code .equals(Filter.ReturnCode.INCLUDE_AND_NEXT_COL))) { return null; } } return kv; }
[ "public", "static", "Cell", "filterKv", "(", "Filter", "filter", ",", "Cell", "kv", ")", "throws", "IOException", "{", "// apply the filter and skip this kv if the filter doesn't apply", "if", "(", "filter", "!=", "null", ")", "{", "Filter", ".", "ReturnCode", "code", "=", "filter", ".", "filterKeyValue", "(", "kv", ")", ";", "if", "(", "LOG", ".", "isTraceEnabled", "(", ")", ")", "{", "LOG", ".", "trace", "(", "\"Filter returned:\"", "+", "code", "+", "\" for the key value:\"", "+", "kv", ")", ";", "}", "// if its not an accept type, then skip this kv", "if", "(", "!", "(", "code", ".", "equals", "(", "Filter", ".", "ReturnCode", ".", "INCLUDE", ")", "||", "code", ".", "equals", "(", "Filter", ".", "ReturnCode", ".", "INCLUDE_AND_NEXT_COL", ")", ")", ")", "{", "return", "null", ";", "}", "}", "return", "kv", ";", "}" ]
Attempt to filter out the keyvalue @param kv {@link org.apache.hadoop.hbase.KeyValue} on which to apply the filter @return <tt>null</tt> if the key should not be written, otherwise returns the original {@link org.apache.hadoop.hbase.KeyValue} @param filter a {@link org.apache.hadoop.hbase.filter.Filter} object. @throws java.io.IOException if any.
[ "Attempt", "to", "filter", "out", "the", "keyvalue" ]
train
https://github.com/googleapis/cloud-bigtable-client/blob/53543f36e4d6f9ed1963640d91a35be2a2047656/bigtable-hbase-1.x-parent/bigtable-hbase-1.x-mapreduce/src/main/java/com/google/cloud/bigtable/mapreduce/Import.java#L289-L303
jirkapinkas/jsitemapgenerator
src/main/java/cz/jiripinkas/jsitemapgenerator/AbstractSitemapGenerator.java
AbstractSitemapGenerator.saveSitemap
@Deprecated public void saveSitemap(File file, String[] sitemap) throws IOException { """ Save sitemap to output file @param file Output file @param sitemap Sitemap as array of Strings (created by constructSitemap() method) @throws IOException when error @deprecated Use {@link #toFile(Path)} instead """ try(BufferedWriter writer = new BufferedWriter(new FileWriter(file))) { for (String string : sitemap) { writer.write(string); } } }
java
@Deprecated public void saveSitemap(File file, String[] sitemap) throws IOException { try(BufferedWriter writer = new BufferedWriter(new FileWriter(file))) { for (String string : sitemap) { writer.write(string); } } }
[ "@", "Deprecated", "public", "void", "saveSitemap", "(", "File", "file", ",", "String", "[", "]", "sitemap", ")", "throws", "IOException", "{", "try", "(", "BufferedWriter", "writer", "=", "new", "BufferedWriter", "(", "new", "FileWriter", "(", "file", ")", ")", ")", "{", "for", "(", "String", "string", ":", "sitemap", ")", "{", "writer", ".", "write", "(", "string", ")", ";", "}", "}", "}" ]
Save sitemap to output file @param file Output file @param sitemap Sitemap as array of Strings (created by constructSitemap() method) @throws IOException when error @deprecated Use {@link #toFile(Path)} instead
[ "Save", "sitemap", "to", "output", "file" ]
train
https://github.com/jirkapinkas/jsitemapgenerator/blob/42e1f57bd936e21fe9df642e722726e71f667442/src/main/java/cz/jiripinkas/jsitemapgenerator/AbstractSitemapGenerator.java#L115-L122
davidmoten/ppk
ppk/src/main/java/com/github/davidmoten/security/PPK.java
PPK.publicKey
public static final Builder publicKey(Class<?> cls, String resource) { """ Returns a builder having loaded the public key from the classpath relative to the classloader used by {@code cls}. @param cls the class whose classloader is used to load the resource @param resource the resource path @return the PPK builder """ return new Builder().publicKey(cls, resource); }
java
public static final Builder publicKey(Class<?> cls, String resource) { return new Builder().publicKey(cls, resource); }
[ "public", "static", "final", "Builder", "publicKey", "(", "Class", "<", "?", ">", "cls", ",", "String", "resource", ")", "{", "return", "new", "Builder", "(", ")", ".", "publicKey", "(", "cls", ",", "resource", ")", ";", "}" ]
Returns a builder having loaded the public key from the classpath relative to the classloader used by {@code cls}. @param cls the class whose classloader is used to load the resource @param resource the resource path @return the PPK builder
[ "Returns", "a", "builder", "having", "loaded", "the", "public", "key", "from", "the", "classpath", "relative", "to", "the", "classloader", "used", "by", "{", "@code", "cls", "}", "." ]
train
https://github.com/davidmoten/ppk/blob/7506ed490445927fbdeec2fe9c70b4a589a951cb/ppk/src/main/java/com/github/davidmoten/security/PPK.java#L184-L186
apache/incubator-gobblin
gobblin-modules/gobblin-metrics-influxdb/src/main/java/org/apache/gobblin/metrics/influxdb/InfluxDBEventReporter.java
InfluxDBEventReporter.convertValue
private Object convertValue(String field, String value) { """ Convert the event value taken from the metadata to double (default type). It falls back to string type if the value is missing or it is non-numeric is of string or missing Metadata entries are emitted as distinct events (see {@link MultiPartEvent}) @param field {@link GobblinTrackingEvent} metadata key @param value {@link GobblinTrackingEvent} metadata value @return The converted event value """ if (value == null) return EMTPY_VALUE; if (METADATA_DURATION.equals(field)) { return convertDuration(TimeUnit.MILLISECONDS.toNanos(Long.parseLong(value))); } else { Double doubleValue = Doubles.tryParse(value); return (doubleValue == null) ? value : doubleValue; } }
java
private Object convertValue(String field, String value) { if (value == null) return EMTPY_VALUE; if (METADATA_DURATION.equals(field)) { return convertDuration(TimeUnit.MILLISECONDS.toNanos(Long.parseLong(value))); } else { Double doubleValue = Doubles.tryParse(value); return (doubleValue == null) ? value : doubleValue; } }
[ "private", "Object", "convertValue", "(", "String", "field", ",", "String", "value", ")", "{", "if", "(", "value", "==", "null", ")", "return", "EMTPY_VALUE", ";", "if", "(", "METADATA_DURATION", ".", "equals", "(", "field", ")", ")", "{", "return", "convertDuration", "(", "TimeUnit", ".", "MILLISECONDS", ".", "toNanos", "(", "Long", ".", "parseLong", "(", "value", ")", ")", ")", ";", "}", "else", "{", "Double", "doubleValue", "=", "Doubles", ".", "tryParse", "(", "value", ")", ";", "return", "(", "doubleValue", "==", "null", ")", "?", "value", ":", "doubleValue", ";", "}", "}" ]
Convert the event value taken from the metadata to double (default type). It falls back to string type if the value is missing or it is non-numeric is of string or missing Metadata entries are emitted as distinct events (see {@link MultiPartEvent}) @param field {@link GobblinTrackingEvent} metadata key @param value {@link GobblinTrackingEvent} metadata value @return The converted event value
[ "Convert", "the", "event", "value", "taken", "from", "the", "metadata", "to", "double", "(", "default", "type", ")", ".", "It", "falls", "back", "to", "string", "type", "if", "the", "value", "is", "missing", "or", "it", "is", "non", "-", "numeric", "is", "of", "string", "or", "missing", "Metadata", "entries", "are", "emitted", "as", "distinct", "events", "(", "see", "{", "@link", "MultiPartEvent", "}", ")" ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-metrics-influxdb/src/main/java/org/apache/gobblin/metrics/influxdb/InfluxDBEventReporter.java#L116-L125
Pi4J/pi4j
pi4j-core/src/main/java/com/pi4j/io/serial/SerialDataEvent.java
SerialDataEvent.getHexByteString
public String getHexByteString(CharSequence prefix, CharSequence separator, CharSequence suffix) throws IOException { """ Get a HEX string representation of the bytes available in the serial data receive buffer @param prefix optional prefix string to append before each data byte @param separator optional separator string to append in between each data byte sequence @param suffix optional suffix string to append after each data byte @return HEX string of data bytes from serial data receive buffer @throws IOException """ byte data[] = getBytes(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < data.length; i++) { if(i > 0) sb.append(separator); int v = data[i] & 0xff; if(prefix != null) sb.append(prefix); sb.append(hexArray[v >> 4]); sb.append(hexArray[v & 0xf]); if(suffix != null) sb.append(suffix); } return sb.toString(); }
java
public String getHexByteString(CharSequence prefix, CharSequence separator, CharSequence suffix) throws IOException { byte data[] = getBytes(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < data.length; i++) { if(i > 0) sb.append(separator); int v = data[i] & 0xff; if(prefix != null) sb.append(prefix); sb.append(hexArray[v >> 4]); sb.append(hexArray[v & 0xf]); if(suffix != null) sb.append(suffix); } return sb.toString(); }
[ "public", "String", "getHexByteString", "(", "CharSequence", "prefix", ",", "CharSequence", "separator", ",", "CharSequence", "suffix", ")", "throws", "IOException", "{", "byte", "data", "[", "]", "=", "getBytes", "(", ")", ";", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "data", ".", "length", ";", "i", "++", ")", "{", "if", "(", "i", ">", "0", ")", "sb", ".", "append", "(", "separator", ")", ";", "int", "v", "=", "data", "[", "i", "]", "&", "0xff", ";", "if", "(", "prefix", "!=", "null", ")", "sb", ".", "append", "(", "prefix", ")", ";", "sb", ".", "append", "(", "hexArray", "[", "v", ">>", "4", "]", ")", ";", "sb", ".", "append", "(", "hexArray", "[", "v", "&", "0xf", "]", ")", ";", "if", "(", "suffix", "!=", "null", ")", "sb", ".", "append", "(", "suffix", ")", ";", "}", "return", "sb", ".", "toString", "(", ")", ";", "}" ]
Get a HEX string representation of the bytes available in the serial data receive buffer @param prefix optional prefix string to append before each data byte @param separator optional separator string to append in between each data byte sequence @param suffix optional suffix string to append after each data byte @return HEX string of data bytes from serial data receive buffer @throws IOException
[ "Get", "a", "HEX", "string", "representation", "of", "the", "bytes", "available", "in", "the", "serial", "data", "receive", "buffer" ]
train
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-core/src/main/java/com/pi4j/io/serial/SerialDataEvent.java#L187-L200
m-m-m/util
exception/src/main/java/net/sf/mmm/util/exception/api/NlsNullPointerException.java
NlsNullPointerException.checkNotNull
public static <O> void checkNotNull(Class<O> type, O object) throws NlsNullPointerException { """ This method checks if the given {@code object} is {@code null}. <br> <b>ATTENTION:</b><br> This method is only intended to be used for specific types. It then not only saves you from a single {@code if} -statement, but also defines a common pattern that is refactoring-safe. <br> Anyhow you should never use this method with generic {@link Class}es for {@code type} such as {@link Object}, {@link String}, {@link Integer}, etc. <br> <br> Here is an example: <pre> public void myMethod(MySpecificBusinessObject businessObject, String someParameter) { {@link NlsNullPointerException}.checkNotNull(MySpecificBusinessObject.class, businessObject); {@link NlsNullPointerException}.checkNotNull("someParameter", someParameter); doTheWork(); } </pre> @param <O> is the generic type of the {@code object}. @param type is the class reflecting the {@code object}. Its {@link Class#getSimpleName() simple name} will be used in the exception-message if {@code object} is {@code null}. @param object is the object that is checked and should NOT be {@code null}. @throws NlsNullPointerException if the given {@code object} is {@code null}. """ if (object == null) { throw new NlsNullPointerException(type.getSimpleName()); } }
java
public static <O> void checkNotNull(Class<O> type, O object) throws NlsNullPointerException { if (object == null) { throw new NlsNullPointerException(type.getSimpleName()); } }
[ "public", "static", "<", "O", ">", "void", "checkNotNull", "(", "Class", "<", "O", ">", "type", ",", "O", "object", ")", "throws", "NlsNullPointerException", "{", "if", "(", "object", "==", "null", ")", "{", "throw", "new", "NlsNullPointerException", "(", "type", ".", "getSimpleName", "(", ")", ")", ";", "}", "}" ]
This method checks if the given {@code object} is {@code null}. <br> <b>ATTENTION:</b><br> This method is only intended to be used for specific types. It then not only saves you from a single {@code if} -statement, but also defines a common pattern that is refactoring-safe. <br> Anyhow you should never use this method with generic {@link Class}es for {@code type} such as {@link Object}, {@link String}, {@link Integer}, etc. <br> <br> Here is an example: <pre> public void myMethod(MySpecificBusinessObject businessObject, String someParameter) { {@link NlsNullPointerException}.checkNotNull(MySpecificBusinessObject.class, businessObject); {@link NlsNullPointerException}.checkNotNull("someParameter", someParameter); doTheWork(); } </pre> @param <O> is the generic type of the {@code object}. @param type is the class reflecting the {@code object}. Its {@link Class#getSimpleName() simple name} will be used in the exception-message if {@code object} is {@code null}. @param object is the object that is checked and should NOT be {@code null}. @throws NlsNullPointerException if the given {@code object} is {@code null}.
[ "This", "method", "checks", "if", "the", "given", "{", "@code", "object", "}", "is", "{", "@code", "null", "}", ".", "<br", ">", "<b", ">", "ATTENTION", ":", "<", "/", "b", ">", "<br", ">", "This", "method", "is", "only", "intended", "to", "be", "used", "for", "specific", "types", ".", "It", "then", "not", "only", "saves", "you", "from", "a", "single", "{", "@code", "if", "}", "-", "statement", "but", "also", "defines", "a", "common", "pattern", "that", "is", "refactoring", "-", "safe", ".", "<br", ">", "Anyhow", "you", "should", "never", "use", "this", "method", "with", "generic", "{", "@link", "Class", "}", "es", "for", "{", "@code", "type", "}", "such", "as", "{", "@link", "Object", "}", "{", "@link", "String", "}", "{", "@link", "Integer", "}", "etc", ".", "<br", ">", "<br", ">", "Here", "is", "an", "example", ":" ]
train
https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/exception/src/main/java/net/sf/mmm/util/exception/api/NlsNullPointerException.java#L73-L78
nguillaumin/slick2d-maven
slick2d-core/src/main/java/org/newdawn/slick/GameContainer.java
GameContainer.initSystem
protected void initSystem() throws SlickException { """ Initialise the system components, OpenGL and OpenAL. @throws SlickException Indicates a failure to create a native handler """ initGL(); setMusicVolume(1.0f); setSoundVolume(1.0f); graphics = new Graphics(width, height); defaultFont = graphics.getFont(); }
java
protected void initSystem() throws SlickException { initGL(); setMusicVolume(1.0f); setSoundVolume(1.0f); graphics = new Graphics(width, height); defaultFont = graphics.getFont(); }
[ "protected", "void", "initSystem", "(", ")", "throws", "SlickException", "{", "initGL", "(", ")", ";", "setMusicVolume", "(", "1.0f", ")", ";", "setSoundVolume", "(", "1.0f", ")", ";", "graphics", "=", "new", "Graphics", "(", "width", ",", "height", ")", ";", "defaultFont", "=", "graphics", ".", "getFont", "(", ")", ";", "}" ]
Initialise the system components, OpenGL and OpenAL. @throws SlickException Indicates a failure to create a native handler
[ "Initialise", "the", "system", "components", "OpenGL", "and", "OpenAL", "." ]
train
https://github.com/nguillaumin/slick2d-maven/blob/8251f88a0ed6a70e726d2468842455cd1f80893f/slick2d-core/src/main/java/org/newdawn/slick/GameContainer.java#L754-L761