repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
18
201
func_name
stringlengths
4
126
whole_func_string
stringlengths
75
3.57k
language
stringclasses
1 value
func_code_string
stringlengths
75
3.57k
func_code_tokens
listlengths
21
599
func_documentation_string
stringlengths
61
1.95k
func_documentation_tokens
listlengths
1
478
split_name
stringclasses
1 value
func_code_url
stringlengths
111
308
elki-project/elki
addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/projections/AbstractFullProjection.java
AbstractFullProjection.projectRenderToDataSpace
@Override public <NV extends NumberVector> NV projectRenderToDataSpace(double[] v, NumberVector.Factory<NV> prototype) { final int dim = v.length; double[] vec = projectRenderToScaled(v); // Not calling {@link #projectScaledToDataSpace} to avoid extra copy of // vector. for(int d = 0; d < dim; d++) { vec[d] = scales[d].getUnscaled(vec[d]); } return prototype.newNumberVector(vec); }
java
@Override public <NV extends NumberVector> NV projectRenderToDataSpace(double[] v, NumberVector.Factory<NV> prototype) { final int dim = v.length; double[] vec = projectRenderToScaled(v); // Not calling {@link #projectScaledToDataSpace} to avoid extra copy of // vector. for(int d = 0; d < dim; d++) { vec[d] = scales[d].getUnscaled(vec[d]); } return prototype.newNumberVector(vec); }
[ "@", "Override", "public", "<", "NV", "extends", "NumberVector", ">", "NV", "projectRenderToDataSpace", "(", "double", "[", "]", "v", ",", "NumberVector", ".", "Factory", "<", "NV", ">", "prototype", ")", "{", "final", "int", "dim", "=", "v", ".", "lengt...
Project a vector from rendering space to data space. @param <NV> Vector type @param v vector in rendering space @param prototype Object factory @return vector in data space
[ "Project", "a", "vector", "from", "rendering", "space", "to", "data", "space", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/projections/AbstractFullProjection.java#L181-L191
Carbonado/Carbonado
src/main/java/com/amazon/carbonado/qe/JoinedQueryExecutor.java
JoinedQueryExecutor.mostOrdering
private static <T extends Storable> OrderingList mostOrdering(StorableProperty<T> primeTarget, OrderingList<T> targetOrdering) { OrderingList handledOrdering = OrderingList.emptyList(); for (OrderedProperty<T> targetProp : targetOrdering) { ChainedProperty<T> chainedProp = targetProp.getChainedProperty(); if (chainedProp.getPrimeProperty().equals(primeTarget)) { handledOrdering = handledOrdering // I hate Java generics. Note the stupid cast. I have finally // realized the core problem: the wildcard model is broken. .concat(OrderedProperty .get((ChainedProperty) chainedProp.tail(), targetProp.getDirection())); } else { break; } } return handledOrdering; }
java
private static <T extends Storable> OrderingList mostOrdering(StorableProperty<T> primeTarget, OrderingList<T> targetOrdering) { OrderingList handledOrdering = OrderingList.emptyList(); for (OrderedProperty<T> targetProp : targetOrdering) { ChainedProperty<T> chainedProp = targetProp.getChainedProperty(); if (chainedProp.getPrimeProperty().equals(primeTarget)) { handledOrdering = handledOrdering // I hate Java generics. Note the stupid cast. I have finally // realized the core problem: the wildcard model is broken. .concat(OrderedProperty .get((ChainedProperty) chainedProp.tail(), targetProp.getDirection())); } else { break; } } return handledOrdering; }
[ "private", "static", "<", "T", "extends", "Storable", ">", "OrderingList", "mostOrdering", "(", "StorableProperty", "<", "T", ">", "primeTarget", ",", "OrderingList", "<", "T", ">", "targetOrdering", ")", "{", "OrderingList", "handledOrdering", "=", "OrderingList"...
Given a list of chained ordering properties, returns the properties stripped of the matching chain prefix for the targetToSourceProperty. As the target ordering is scanned left-to-right, if any property is found which doesn't match the targetToSourceProperty, the building of the new list stops. In other words, it returns a consecutive run of matching properties.
[ "Given", "a", "list", "of", "chained", "ordering", "properties", "returns", "the", "properties", "stripped", "of", "the", "matching", "chain", "prefix", "for", "the", "targetToSourceProperty", ".", "As", "the", "target", "ordering", "is", "scanned", "left", "-",...
train
https://github.com/Carbonado/Carbonado/blob/eee29b365a61c8f03e1a1dc6bed0692e6b04b1db/src/main/java/com/amazon/carbonado/qe/JoinedQueryExecutor.java#L386-L405
meertensinstituut/mtas
src/main/java/mtas/codec/util/CodecInfo.java
CodecInfo.getNextDoc
public IndexDoc getNextDoc(String field, int previousDocId) { if (fieldReferences.containsKey(field)) { FieldReferences fr = fieldReferences.get(field); try { if (previousDocId < 0) { return new IndexDoc(fr.refIndexDoc); } else { int nextDocId = previousDocId + 1; IndexInput inIndexDocId = indexInputList.get("indexDocId"); ArrayList<MtasTreeHit<?>> list = CodecSearchTree.advanceMtasTree( nextDocId, inIndexDocId, fr.refIndexDocId, fr.refIndexDoc); if (list.size() == 1) { IndexInput inDoc = indexInputList.get("doc"); inDoc.seek(list.get(0).ref); return new IndexDoc(inDoc.getFilePointer()); } } } catch (IOException e) { log.debug(e); return null; } } return null; }
java
public IndexDoc getNextDoc(String field, int previousDocId) { if (fieldReferences.containsKey(field)) { FieldReferences fr = fieldReferences.get(field); try { if (previousDocId < 0) { return new IndexDoc(fr.refIndexDoc); } else { int nextDocId = previousDocId + 1; IndexInput inIndexDocId = indexInputList.get("indexDocId"); ArrayList<MtasTreeHit<?>> list = CodecSearchTree.advanceMtasTree( nextDocId, inIndexDocId, fr.refIndexDocId, fr.refIndexDoc); if (list.size() == 1) { IndexInput inDoc = indexInputList.get("doc"); inDoc.seek(list.get(0).ref); return new IndexDoc(inDoc.getFilePointer()); } } } catch (IOException e) { log.debug(e); return null; } } return null; }
[ "public", "IndexDoc", "getNextDoc", "(", "String", "field", ",", "int", "previousDocId", ")", "{", "if", "(", "fieldReferences", ".", "containsKey", "(", "field", ")", ")", "{", "FieldReferences", "fr", "=", "fieldReferences", ".", "get", "(", "field", ")", ...
Gets the next doc. @param field the field @param previousDocId the previous doc id @return the next doc
[ "Gets", "the", "next", "doc", "." ]
train
https://github.com/meertensinstituut/mtas/blob/f02ae730848616bd88b553efa7f9eddc32818e64/src/main/java/mtas/codec/util/CodecInfo.java#L593-L616
gmessner/gitlab4j-api
src/main/java/org/gitlab4j/api/utils/FileUtils.java
FileUtils.createUniqueFile
public static File createUniqueFile(File directory, String filename) throws IOException { File uniqueFile = new File(directory, filename); if (uniqueFile.createNewFile()) { return (uniqueFile); } String extension = ""; int dotIndex = filename.lastIndexOf('.'); if (dotIndex >= 0) { extension = filename.substring(dotIndex); filename = filename.substring(0, dotIndex); } int fileNumber = 0; while (!uniqueFile.createNewFile()) { fileNumber++; String numberedFilename = String.format("%s-%d%s", filename, fileNumber, extension); uniqueFile = new File(directory, numberedFilename); } return (uniqueFile); }
java
public static File createUniqueFile(File directory, String filename) throws IOException { File uniqueFile = new File(directory, filename); if (uniqueFile.createNewFile()) { return (uniqueFile); } String extension = ""; int dotIndex = filename.lastIndexOf('.'); if (dotIndex >= 0) { extension = filename.substring(dotIndex); filename = filename.substring(0, dotIndex); } int fileNumber = 0; while (!uniqueFile.createNewFile()) { fileNumber++; String numberedFilename = String.format("%s-%d%s", filename, fileNumber, extension); uniqueFile = new File(directory, numberedFilename); } return (uniqueFile); }
[ "public", "static", "File", "createUniqueFile", "(", "File", "directory", ",", "String", "filename", ")", "throws", "IOException", "{", "File", "uniqueFile", "=", "new", "File", "(", "directory", ",", "filename", ")", ";", "if", "(", "uniqueFile", ".", "crea...
Creates a File that is unique in the specified directory. If the specified filename exists in the directory, "-#" will be appended to the filename until a unique filename can be created. @param directory the directory to create the file in @param filename the base filename with extension @return a File that is unique in the specified directory @throws IOException if any error occurs during file creation
[ "Creates", "a", "File", "that", "is", "unique", "in", "the", "specified", "directory", ".", "If", "the", "specified", "filename", "exists", "in", "the", "directory", "-", "#", "will", "be", "appended", "to", "the", "filename", "until", "a", "unique", "file...
train
https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/utils/FileUtils.java#L24-L46
jblas-project/jblas
src/main/java/org/jblas/Eigen.java
Eigen.symmetricGeneralizedEigenvectors
public static DoubleMatrix[] symmetricGeneralizedEigenvectors(DoubleMatrix A, DoubleMatrix B, double vl, double vu) { A.assertSquare(); B.assertSquare(); A.assertSameSize(B); if (vu <= vl) { throw new IllegalArgumentException("Bound exception: make sure vu > vl"); } double abstol = (double) 1e-9; // What is a good tolerance? int[] m = new int[1]; DoubleMatrix W = new DoubleMatrix(A.rows); DoubleMatrix Z = new DoubleMatrix(A.rows, A.columns); SimpleBlas.sygvx(1, 'V', 'V', 'U', A.dup(), B.dup(), vl, vu, 0, 0, abstol, m, W, Z); if (m[0] == 0) { throw new NoEigenResultException("No eigenvalues found for selected range"); } DoubleMatrix[] result = new DoubleMatrix[2]; Range r = new IntervalRange(0, m[0]); result[0] = Z.get(new IntervalRange(0, A.rows), r); result[1] = W.get(r, 0); return result; }
java
public static DoubleMatrix[] symmetricGeneralizedEigenvectors(DoubleMatrix A, DoubleMatrix B, double vl, double vu) { A.assertSquare(); B.assertSquare(); A.assertSameSize(B); if (vu <= vl) { throw new IllegalArgumentException("Bound exception: make sure vu > vl"); } double abstol = (double) 1e-9; // What is a good tolerance? int[] m = new int[1]; DoubleMatrix W = new DoubleMatrix(A.rows); DoubleMatrix Z = new DoubleMatrix(A.rows, A.columns); SimpleBlas.sygvx(1, 'V', 'V', 'U', A.dup(), B.dup(), vl, vu, 0, 0, abstol, m, W, Z); if (m[0] == 0) { throw new NoEigenResultException("No eigenvalues found for selected range"); } DoubleMatrix[] result = new DoubleMatrix[2]; Range r = new IntervalRange(0, m[0]); result[0] = Z.get(new IntervalRange(0, A.rows), r); result[1] = W.get(r, 0); return result; }
[ "public", "static", "DoubleMatrix", "[", "]", "symmetricGeneralizedEigenvectors", "(", "DoubleMatrix", "A", ",", "DoubleMatrix", "B", ",", "double", "vl", ",", "double", "vu", ")", "{", "A", ".", "assertSquare", "(", ")", ";", "B", ".", "assertSquare", "(", ...
Computes selected eigenvalues and their corresponding eigenvectors of the real generalized symmetric-definite eigenproblem of the form A x = L B x or, equivalently, (A - L B)x = 0. Here A and B are assumed to be symmetric and B is also positive definite. The selection is based on the given range of values for the desired eigenvalues. The range is half open: (vl,vu]. @param A symmetric Matrix A. Only the upper triangle will be considered. @param B symmetric Matrix B. Only the upper triangle will be considered. @param vl lower bound of the smallest eigenvalue to return @param vu upper bound of the largest eigenvalue to return @return an array of matrices of length two. The first one is an array of the eigenvectors x. The second one is a vector containing the corresponding eigenvalues L. @throws IllegalArgumentException if <code>vl &gt; vu</code> @throws NoEigenResultException if no eigevalues are found for the selected range: (vl,vu]
[ "Computes", "selected", "eigenvalues", "and", "their", "corresponding", "eigenvectors", "of", "the", "real", "generalized", "symmetric", "-", "definite", "eigenproblem", "of", "the", "form", "A", "x", "=", "L", "B", "x", "or", "equivalently", "(", "A", "-", ...
train
https://github.com/jblas-project/jblas/blob/2818f231228e655cda80dfd8e0b87709fdfd8a70/src/main/java/org/jblas/Eigen.java#L245-L265
OpenLiberty/open-liberty
dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ejs/csi/FileBeanStore.java
FileBeanStore.getGZIPOutputStream
public GZIPOutputStream getGZIPOutputStream(BeanId beanId) throws CSIException { final boolean isTraceOn = TraceComponent.isAnyTracingEnabled(); if (isTraceOn && tc.isEntryEnabled()) Tr.entry(tc, "getOutputStream", beanId); final String fileName = getPortableFilename(beanId); final long beanTimeoutTime = getBeanTimeoutTime(beanId); GZIPOutputStream result = null; try { result = (GZIPOutputStream) AccessController.doPrivileged(new PrivilegedExceptionAction<GZIPOutputStream>() { public GZIPOutputStream run() throws IOException { File statefulBeanFile = getStatefulBeanFile(fileName, false); FileOutputStream fos = EJSPlatformHelper.isZOS() ? new WSFileOutputStream(statefulBeanFile, beanTimeoutTime) : new FileOutputStream(statefulBeanFile); return new GZIPOutputStream(fos); // d651126 } }); } catch (PrivilegedActionException ex2) { Exception ex = ex2.getException(); FFDCFilter.processException(ex, CLASS_NAME + ".getOutputStream", "127", this); Tr.warning(tc, "IOEXCEPTION_WRITING_FILE_FOR_STATEFUL_SESSION_BEAN_CNTR0025W", new Object[] { fileName, this, ex }); //p111002.3 throw new CSIException("Unable to open output stream", ex); } if (isTraceOn && tc.isEntryEnabled()) Tr.exit(tc, "getOutputStream"); return result; }
java
public GZIPOutputStream getGZIPOutputStream(BeanId beanId) throws CSIException { final boolean isTraceOn = TraceComponent.isAnyTracingEnabled(); if (isTraceOn && tc.isEntryEnabled()) Tr.entry(tc, "getOutputStream", beanId); final String fileName = getPortableFilename(beanId); final long beanTimeoutTime = getBeanTimeoutTime(beanId); GZIPOutputStream result = null; try { result = (GZIPOutputStream) AccessController.doPrivileged(new PrivilegedExceptionAction<GZIPOutputStream>() { public GZIPOutputStream run() throws IOException { File statefulBeanFile = getStatefulBeanFile(fileName, false); FileOutputStream fos = EJSPlatformHelper.isZOS() ? new WSFileOutputStream(statefulBeanFile, beanTimeoutTime) : new FileOutputStream(statefulBeanFile); return new GZIPOutputStream(fos); // d651126 } }); } catch (PrivilegedActionException ex2) { Exception ex = ex2.getException(); FFDCFilter.processException(ex, CLASS_NAME + ".getOutputStream", "127", this); Tr.warning(tc, "IOEXCEPTION_WRITING_FILE_FOR_STATEFUL_SESSION_BEAN_CNTR0025W", new Object[] { fileName, this, ex }); //p111002.3 throw new CSIException("Unable to open output stream", ex); } if (isTraceOn && tc.isEntryEnabled()) Tr.exit(tc, "getOutputStream"); return result; }
[ "public", "GZIPOutputStream", "getGZIPOutputStream", "(", "BeanId", "beanId", ")", "throws", "CSIException", "{", "final", "boolean", "isTraceOn", "=", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", ";", "if", "(", "isTraceOn", "&&", "tc", ".", "isEntryEn...
Get object ouput stream suitable for reading persistent state associated with given key.
[ "Get", "object", "ouput", "stream", "suitable", "for", "reading", "persistent", "state", "associated", "with", "given", "key", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ejs/csi/FileBeanStore.java#L273-L310
zalando-stups/spring-boot-etcd
zalando-boot-etcd/src/main/java/org/zalando/boot/etcd/EtcdClient.java
EtcdClient.listMembers
public EtcdMemberResponse listMembers() throws EtcdException { UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(MEMBERSPACE); return execute(builder, HttpMethod.GET, null, EtcdMemberResponse.class); }
java
public EtcdMemberResponse listMembers() throws EtcdException { UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(MEMBERSPACE); return execute(builder, HttpMethod.GET, null, EtcdMemberResponse.class); }
[ "public", "EtcdMemberResponse", "listMembers", "(", ")", "throws", "EtcdException", "{", "UriComponentsBuilder", "builder", "=", "UriComponentsBuilder", ".", "fromUriString", "(", "MEMBERSPACE", ")", ";", "return", "execute", "(", "builder", ",", "HttpMethod", ".", ...
Returns a representation of all members in the etcd cluster. @return the members @throws EtcdException in case etcd returned an error
[ "Returns", "a", "representation", "of", "all", "members", "in", "the", "etcd", "cluster", "." ]
train
https://github.com/zalando-stups/spring-boot-etcd/blob/6b4f48663d424777326c38b1e7da75c8b68a3841/zalando-boot-etcd/src/main/java/org/zalando/boot/etcd/EtcdClient.java#L581-L584
RuedigerMoeller/kontraktor
modules/reactive-streams/src/main/java/org/nustaq/kontraktor/reactivestreams/KxReactiveStreams.java
KxReactiveStreams.stream
public <T> Stream<T> stream( Publisher<T> pub ) { return stream(pub, batchSize); }
java
public <T> Stream<T> stream( Publisher<T> pub ) { return stream(pub, batchSize); }
[ "public", "<", "T", ">", "Stream", "<", "T", ">", "stream", "(", "Publisher", "<", "T", ">", "pub", ")", "{", "return", "stream", "(", "pub", ",", "batchSize", ")", ";", "}" ]
warning: blocks the calling thread. Need to execute in a separate thread if called from within a callback
[ "warning", ":", "blocks", "the", "calling", "thread", ".", "Need", "to", "execute", "in", "a", "separate", "thread", "if", "called", "from", "within", "a", "callback" ]
train
https://github.com/RuedigerMoeller/kontraktor/blob/d5f3817f9476f3786187b8ef00400b7a4f25a404/modules/reactive-streams/src/main/java/org/nustaq/kontraktor/reactivestreams/KxReactiveStreams.java#L244-L246
GoSimpleLLC/nbvcxz
src/main/java/me/gosimple/nbvcxz/matching/match/BaseMatch.java
BaseMatch.nCk
protected static long nCk(int n, int k) { if (k > n) { return 0; } long result = 1; for (int i = 1; i <= k; i++) { result *= n--; result /= i; } return result; }
java
protected static long nCk(int n, int k) { if (k > n) { return 0; } long result = 1; for (int i = 1; i <= k; i++) { result *= n--; result /= i; } return result; }
[ "protected", "static", "long", "nCk", "(", "int", "n", ",", "int", "k", ")", "{", "if", "(", "k", ">", "n", ")", "{", "return", "0", ";", "}", "long", "result", "=", "1", ";", "for", "(", "int", "i", "=", "1", ";", "i", "<=", "k", ";", "i...
Calculate binomial coefficients (the number of possible "choose k among n") @param n the total size of the set @param k the size of the selection @return the binomial coefficient
[ "Calculate", "binomial", "coefficients", "(", "the", "number", "of", "possible", "choose", "k", "among", "n", ")" ]
train
https://github.com/GoSimpleLLC/nbvcxz/blob/a86fb24680e646efdf78d6fda9d68a5410145f56/src/main/java/me/gosimple/nbvcxz/matching/match/BaseMatch.java#L70-L83
j-a-w-r/jawr-main-repo
jawr/jawr-core/src/main/java/net/jawr/web/servlet/RendererRequestUtils.java
RendererRequestUtils.getContextPathOverride
private static String getContextPathOverride(boolean isSslRequest, JawrConfig config) { String contextPathOverride = null; if (isSslRequest) { contextPathOverride = config.getContextPathSslOverride(); } else { contextPathOverride = config.getContextPathOverride(); } return contextPathOverride; }
java
private static String getContextPathOverride(boolean isSslRequest, JawrConfig config) { String contextPathOverride = null; if (isSslRequest) { contextPathOverride = config.getContextPathSslOverride(); } else { contextPathOverride = config.getContextPathOverride(); } return contextPathOverride; }
[ "private", "static", "String", "getContextPathOverride", "(", "boolean", "isSslRequest", ",", "JawrConfig", "config", ")", "{", "String", "contextPathOverride", "=", "null", ";", "if", "(", "isSslRequest", ")", "{", "contextPathOverride", "=", "config", ".", "getC...
Returns the context path depending on the request mode (SSL or not) @param isSslRequest the flag indicating that the request is an SSL request @return the context path depending on the request mode
[ "Returns", "the", "context", "path", "depending", "on", "the", "request", "mode", "(", "SSL", "or", "not", ")" ]
train
https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr/jawr-core/src/main/java/net/jawr/web/servlet/RendererRequestUtils.java#L361-L369
tvesalainen/util
util/src/main/java/org/vesalainen/math/LevenbergMarquardt.java
LevenbergMarquardt.computeNumericalJacobian
protected void computeNumericalJacobian( DenseMatrix64F param , DenseMatrix64F pt , DenseMatrix64F deriv ) { double invDelta = 1.0/DELTA; func.compute(param,pt, temp0); // compute the jacobian by perturbing the parameters slightly // then seeing how it effects the results. for( int i = 0; i < param.numRows; i++ ) { param.data[i] += DELTA; func.compute(param,pt, temp1); // compute the difference between the two parameters and divide by the delta add(invDelta,temp1,-invDelta,temp0,temp1); // copy the results into the jacobian matrix System.arraycopy(temp1.data,0,deriv.data,i*pt.numRows,pt.numRows); param.data[i] -= DELTA; } }
java
protected void computeNumericalJacobian( DenseMatrix64F param , DenseMatrix64F pt , DenseMatrix64F deriv ) { double invDelta = 1.0/DELTA; func.compute(param,pt, temp0); // compute the jacobian by perturbing the parameters slightly // then seeing how it effects the results. for( int i = 0; i < param.numRows; i++ ) { param.data[i] += DELTA; func.compute(param,pt, temp1); // compute the difference between the two parameters and divide by the delta add(invDelta,temp1,-invDelta,temp0,temp1); // copy the results into the jacobian matrix System.arraycopy(temp1.data,0,deriv.data,i*pt.numRows,pt.numRows); param.data[i] -= DELTA; } }
[ "protected", "void", "computeNumericalJacobian", "(", "DenseMatrix64F", "param", ",", "DenseMatrix64F", "pt", ",", "DenseMatrix64F", "deriv", ")", "{", "double", "invDelta", "=", "1.0", "/", "DELTA", ";", "func", ".", "compute", "(", "param", ",", "pt", ",", ...
Computes a simple numerical Jacobian. @param param The set of parameters that the Jacobian is to be computed at. @param pt The point around which the Jacobian is to be computed. @param deriv Where the jacobian will be stored
[ "Computes", "a", "simple", "numerical", "Jacobian", "." ]
train
https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/util/src/main/java/org/vesalainen/math/LevenbergMarquardt.java#L309-L329
facebookarchive/hadoop-20
src/core/org/apache/hadoop/fs/LocalFileSystem.java
LocalFileSystem.reportChecksumFailure
public boolean reportChecksumFailure(Path p, FSDataInputStream in, long inPos, FSDataInputStream sums, long sumsPos) { try { // canonicalize f File f = ((RawLocalFileSystem)fs).pathToFile(p).getCanonicalFile(); // find highest writable parent dir of f on the same device String device = new DF(f, getConf()).getMount(); File parent = f.getParentFile(); File dir = null; while (parent!=null && parent.canWrite() && parent.toString().startsWith(device)) { dir = parent; parent = parent.getParentFile(); } if (dir==null) { throw new IOException( "not able to find the highest writable parent dir"); } // move the file there File badDir = new File(dir, "bad_files"); if (!badDir.mkdirs()) { if (!badDir.isDirectory()) { throw new IOException("Mkdirs failed to create " + badDir.toString()); } } String suffix = "." + rand.nextInt(); File badFile = new File(badDir, f.getName()+suffix); LOG.warn("Moving bad file " + f + " to " + badFile); in.close(); // close it first f.renameTo(badFile); // rename it // move checksum file too File checkFile = ((RawLocalFileSystem)fs).pathToFile(getChecksumFile(p)); checkFile.renameTo(new File(badDir, checkFile.getName()+suffix)); } catch (IOException e) { LOG.warn("Error moving bad file " + p + ": " + e); } return false; }
java
public boolean reportChecksumFailure(Path p, FSDataInputStream in, long inPos, FSDataInputStream sums, long sumsPos) { try { // canonicalize f File f = ((RawLocalFileSystem)fs).pathToFile(p).getCanonicalFile(); // find highest writable parent dir of f on the same device String device = new DF(f, getConf()).getMount(); File parent = f.getParentFile(); File dir = null; while (parent!=null && parent.canWrite() && parent.toString().startsWith(device)) { dir = parent; parent = parent.getParentFile(); } if (dir==null) { throw new IOException( "not able to find the highest writable parent dir"); } // move the file there File badDir = new File(dir, "bad_files"); if (!badDir.mkdirs()) { if (!badDir.isDirectory()) { throw new IOException("Mkdirs failed to create " + badDir.toString()); } } String suffix = "." + rand.nextInt(); File badFile = new File(badDir, f.getName()+suffix); LOG.warn("Moving bad file " + f + " to " + badFile); in.close(); // close it first f.renameTo(badFile); // rename it // move checksum file too File checkFile = ((RawLocalFileSystem)fs).pathToFile(getChecksumFile(p)); checkFile.renameTo(new File(badDir, checkFile.getName()+suffix)); } catch (IOException e) { LOG.warn("Error moving bad file " + p + ": " + e); } return false; }
[ "public", "boolean", "reportChecksumFailure", "(", "Path", "p", ",", "FSDataInputStream", "in", ",", "long", "inPos", ",", "FSDataInputStream", "sums", ",", "long", "sumsPos", ")", "{", "try", "{", "// canonicalize f", "File", "f", "=", "(", "(", "RawLocalFile...
Moves files to a bad file directory on the same device, so that their storage will not be reused.
[ "Moves", "files", "to", "a", "bad", "file", "directory", "on", "the", "same", "device", "so", "that", "their", "storage", "will", "not", "be", "reused", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/fs/LocalFileSystem.java#L68-L110
Azure/azure-sdk-for-java
postgresql/resource-manager/v2017_12_01/src/main/java/com/microsoft/azure/management/postgresql/v2017_12_01/implementation/ServerSecurityAlertPoliciesInner.java
ServerSecurityAlertPoliciesInner.createOrUpdate
public ServerSecurityAlertPolicyInner createOrUpdate(String resourceGroupName, String serverName, ServerSecurityAlertPolicyInner parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, parameters).toBlocking().last().body(); }
java
public ServerSecurityAlertPolicyInner createOrUpdate(String resourceGroupName, String serverName, ServerSecurityAlertPolicyInner parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, parameters).toBlocking().last().body(); }
[ "public", "ServerSecurityAlertPolicyInner", "createOrUpdate", "(", "String", "resourceGroupName", ",", "String", "serverName", ",", "ServerSecurityAlertPolicyInner", "parameters", ")", "{", "return", "createOrUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "serv...
Creates or updates a threat detection policy. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param serverName The name of the server. @param parameters The server security alert policy. @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 ServerSecurityAlertPolicyInner object if successful.
[ "Creates", "or", "updates", "a", "threat", "detection", "policy", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/postgresql/resource-manager/v2017_12_01/src/main/java/com/microsoft/azure/management/postgresql/v2017_12_01/implementation/ServerSecurityAlertPoliciesInner.java#L169-L171
JodaOrg/joda-time
src/main/java/org/joda/time/DateTime.java
DateTime.withPeriodAdded
public DateTime withPeriodAdded(ReadablePeriod period, int scalar) { if (period == null || scalar == 0) { return this; } long instant = getChronology().add(period, getMillis(), scalar); return withMillis(instant); }
java
public DateTime withPeriodAdded(ReadablePeriod period, int scalar) { if (period == null || scalar == 0) { return this; } long instant = getChronology().add(period, getMillis(), scalar); return withMillis(instant); }
[ "public", "DateTime", "withPeriodAdded", "(", "ReadablePeriod", "period", ",", "int", "scalar", ")", "{", "if", "(", "period", "==", "null", "||", "scalar", "==", "0", ")", "{", "return", "this", ";", "}", "long", "instant", "=", "getChronology", "(", ")...
Returns a copy of this datetime with the specified period added. <p> If the addition is zero, then <code>this</code> is returned. <p> This method is typically used to add multiple copies of complex period instances. Adding one field is best achieved using methods like {@link #withFieldAdded(DurationFieldType, int)} or {@link #plusYears(int)}. @param period the period to add to this one, null means zero @param scalar the amount of times to add, such as -1 to subtract once @return a copy of this datetime with the period added @throws ArithmeticException if the new datetime exceeds the capacity of a long
[ "Returns", "a", "copy", "of", "this", "datetime", "with", "the", "specified", "period", "added", ".", "<p", ">", "If", "the", "addition", "is", "zero", "then", "<code", ">", "this<", "/", "code", ">", "is", "returned", ".", "<p", ">", "This", "method",...
train
https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/DateTime.java#L937-L943
ibm-bluemix-mobile-services/bms-clientsdk-android-core
lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/security/mca/internal/Utils.java
Utils.getParameterValueFromQuery
public static String getParameterValueFromQuery(String query, String paramName) { String[] components = query.split("&"); for (String keyValuePair : components) { String[] pairComponents = keyValuePair.split("="); if (pairComponents.length == 2) { try { String key = URLDecoder.decode(pairComponents[0], "utf-8"); if (key.compareTo(paramName) == 0) { return URLDecoder.decode(pairComponents[1], "utf-8"); } } catch (UnsupportedEncodingException e) { logger.error("getParameterValueFromQuery failed with exception: " + e.getLocalizedMessage(), e); } } } return null; }
java
public static String getParameterValueFromQuery(String query, String paramName) { String[] components = query.split("&"); for (String keyValuePair : components) { String[] pairComponents = keyValuePair.split("="); if (pairComponents.length == 2) { try { String key = URLDecoder.decode(pairComponents[0], "utf-8"); if (key.compareTo(paramName) == 0) { return URLDecoder.decode(pairComponents[1], "utf-8"); } } catch (UnsupportedEncodingException e) { logger.error("getParameterValueFromQuery failed with exception: " + e.getLocalizedMessage(), e); } } } return null; }
[ "public", "static", "String", "getParameterValueFromQuery", "(", "String", "query", ",", "String", "paramName", ")", "{", "String", "[", "]", "components", "=", "query", ".", "split", "(", "\"&\"", ")", ";", "for", "(", "String", "keyValuePair", ":", "compon...
Obtains a parameter with specified name from from query string. The query should be in format param=value&param=value ... @param query Queery in "url" format. @param paramName Parameter name. @return Parameter value, or null.
[ "Obtains", "a", "parameter", "with", "specified", "name", "from", "from", "query", "string", ".", "The", "query", "should", "be", "in", "format", "param", "=", "value&param", "=", "value", "..." ]
train
https://github.com/ibm-bluemix-mobile-services/bms-clientsdk-android-core/blob/8db4f00d0d564792397bfc0e5bd57d52a238b858/lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/security/mca/internal/Utils.java#L48-L68
dspinellis/UMLGraph
src/main/java/org/umlgraph/doclet/ClassGraph.java
ClassGraph.qualifiedName
private static String qualifiedName(Options opt, String r) { if (opt.hideGenerics) r = removeTemplate(r); // Fast path - nothing to do: if (opt.showQualified && (opt.showQualifiedGenerics || r.indexOf('<') < 0)) return r; StringBuilder buf = new StringBuilder(r.length()); qualifiedNameInner(opt, r, buf, 0, !opt.showQualified); return buf.toString(); }
java
private static String qualifiedName(Options opt, String r) { if (opt.hideGenerics) r = removeTemplate(r); // Fast path - nothing to do: if (opt.showQualified && (opt.showQualifiedGenerics || r.indexOf('<') < 0)) return r; StringBuilder buf = new StringBuilder(r.length()); qualifiedNameInner(opt, r, buf, 0, !opt.showQualified); return buf.toString(); }
[ "private", "static", "String", "qualifiedName", "(", "Options", "opt", ",", "String", "r", ")", "{", "if", "(", "opt", ".", "hideGenerics", ")", "r", "=", "removeTemplate", "(", "r", ")", ";", "// Fast path - nothing to do:", "if", "(", "opt", ".", "showQu...
Return the class's name, possibly by stripping the leading path
[ "Return", "the", "class", "s", "name", "possibly", "by", "stripping", "the", "leading", "path" ]
train
https://github.com/dspinellis/UMLGraph/blob/09576db5ae0ea63bfe30ef9fce88a513f9a8d843/src/main/java/org/umlgraph/doclet/ClassGraph.java#L136-L145
biojava/biojava
biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/MMCIFFileTools.java
MMCIFFileTools.toMMCIF
public static String toMMCIF(String categoryName, Object o) { StringBuilder sb = new StringBuilder(); Class<?> c = o.getClass(); Field[] fields = getFields(c); String[] names = getFieldNames(fields); int maxFieldNameLength = getMaxStringLength(names); for (int i=0;i<fields.length;i++) { Field f = fields[i]; String name = names[i]; sb.append(categoryName).append(".").append(name); int spacing = maxFieldNameLength - name.length() + 3; try { Object obj = f.get(o); String val; if (obj==null) { logger.debug("Field {} is null, will write it out as {}",name,MMCIF_MISSING_VALUE); val = MMCIF_MISSING_VALUE; } else { val = (String) obj; } for (int j=0;j<spacing;j++) sb.append(' '); sb.append(addMmCifQuoting(val)); sb.append(newline); } catch (IllegalAccessException e) { logger.warn("Field {} is inaccessible", name); continue; } catch (ClassCastException e) { logger.warn("Could not cast value to String for field {}",name); continue; } } sb.append(SimpleMMcifParser.COMMENT_CHAR+newline); return sb.toString(); }
java
public static String toMMCIF(String categoryName, Object o) { StringBuilder sb = new StringBuilder(); Class<?> c = o.getClass(); Field[] fields = getFields(c); String[] names = getFieldNames(fields); int maxFieldNameLength = getMaxStringLength(names); for (int i=0;i<fields.length;i++) { Field f = fields[i]; String name = names[i]; sb.append(categoryName).append(".").append(name); int spacing = maxFieldNameLength - name.length() + 3; try { Object obj = f.get(o); String val; if (obj==null) { logger.debug("Field {} is null, will write it out as {}",name,MMCIF_MISSING_VALUE); val = MMCIF_MISSING_VALUE; } else { val = (String) obj; } for (int j=0;j<spacing;j++) sb.append(' '); sb.append(addMmCifQuoting(val)); sb.append(newline); } catch (IllegalAccessException e) { logger.warn("Field {} is inaccessible", name); continue; } catch (ClassCastException e) { logger.warn("Could not cast value to String for field {}",name); continue; } } sb.append(SimpleMMcifParser.COMMENT_CHAR+newline); return sb.toString(); }
[ "public", "static", "String", "toMMCIF", "(", "String", "categoryName", ",", "Object", "o", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "Class", "<", "?", ">", "c", "=", "o", ".", "getClass", "(", ")", ";", "Field", "...
Converts a mmCIF bean (see {@link org.biojava.nbio.structure.io.mmcif.model} to a String representing it in mmCIF (single-record) format. @param categoryName @param o @return
[ "Converts", "a", "mmCIF", "bean", "(", "see", "{" ]
train
https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/MMCIFFileTools.java#L108-L154
raydac/java-binary-block-parser
jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPUtils.java
JBBPUtils.reverseByteOrder
public static long reverseByteOrder(long value, int numOfLowerBytesToInvert) { if (numOfLowerBytesToInvert < 1 || numOfLowerBytesToInvert > 8) { throw new IllegalArgumentException("Wrong number of bytes [" + numOfLowerBytesToInvert + ']'); } long result = 0; int offsetInResult = (numOfLowerBytesToInvert - 1) * 8; while (numOfLowerBytesToInvert-- > 0) { final long thebyte = value & 0xFF; value >>>= 8; result |= (thebyte << offsetInResult); offsetInResult -= 8; } return result; }
java
public static long reverseByteOrder(long value, int numOfLowerBytesToInvert) { if (numOfLowerBytesToInvert < 1 || numOfLowerBytesToInvert > 8) { throw new IllegalArgumentException("Wrong number of bytes [" + numOfLowerBytesToInvert + ']'); } long result = 0; int offsetInResult = (numOfLowerBytesToInvert - 1) * 8; while (numOfLowerBytesToInvert-- > 0) { final long thebyte = value & 0xFF; value >>>= 8; result |= (thebyte << offsetInResult); offsetInResult -= 8; } return result; }
[ "public", "static", "long", "reverseByteOrder", "(", "long", "value", ",", "int", "numOfLowerBytesToInvert", ")", "{", "if", "(", "numOfLowerBytesToInvert", "<", "1", "||", "numOfLowerBytesToInvert", ">", "8", ")", "{", "throw", "new", "IllegalArgumentException", ...
Revert order for defined number of bytes in a value. @param value the value which bytes should be reordered @param numOfLowerBytesToInvert number of lower bytes to be reverted in their order, must be 1..8 @return new value which has reverted order for defined number of lower bytes @since 1.1
[ "Revert", "order", "for", "defined", "number", "of", "bytes", "in", "a", "value", "." ]
train
https://github.com/raydac/java-binary-block-parser/blob/6d98abcab01e0c72d525ebcc9e7b694f9ce49f5b/jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPUtils.java#L676-L693
james-hu/jabb-core
src/main/java/net/sf/jabb/spring/rest/AbstractRestClient.java
AbstractRestClient.buildBasicAuthValue
protected String buildBasicAuthValue(String key){ String base64Creds; try { base64Creds = key == null ? "" : Base64.encodeBase64String(key.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("Failed to encode", e); } return "Basic " + base64Creds; }
java
protected String buildBasicAuthValue(String key){ String base64Creds; try { base64Creds = key == null ? "" : Base64.encodeBase64String(key.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("Failed to encode", e); } return "Basic " + base64Creds; }
[ "protected", "String", "buildBasicAuthValue", "(", "String", "key", ")", "{", "String", "base64Creds", ";", "try", "{", "base64Creds", "=", "key", "==", "null", "?", "\"\"", ":", "Base64", ".", "encodeBase64String", "(", "key", ".", "getBytes", "(", "\"UTF-8...
Build the value to be used in HTTP Basic Authentication header @param key the API key @return the value to be used for header 'Authorization'
[ "Build", "the", "value", "to", "be", "used", "in", "HTTP", "Basic", "Authentication", "header" ]
train
https://github.com/james-hu/jabb-core/blob/bceed441595c5e5195a7418795f03b69fa7b61e4/src/main/java/net/sf/jabb/spring/rest/AbstractRestClient.java#L561-L569
deeplearning4j/deeplearning4j
nd4j/nd4j-tensorflow/src/main/java/org/nd4j/tensorflow/conversion/TensorflowConversion.java
TensorflowConversion.loadSavedModel
public TF_Session loadSavedModel(SavedModelConfig savedModelConfig, TF_SessionOptions options, TF_Buffer runOptions, TF_Graph graph, Map<String, String> inputsMap, Map<String, String> outputsMap, TF_Status status) { TF_Buffer metaGraph = TF_Buffer.newBuffer(); TF_Session session = TF_LoadSessionFromSavedModel(options, runOptions, new BytePointer(savedModelConfig.getSavedModelPath()), new BytePointer(savedModelConfig.getModelTag()), 1, graph, metaGraph, status); if (TF_GetCode(status) != TF_OK) { throw new IllegalStateException("ERROR: Unable to import model " + TF_Message(status).getString()); } MetaGraphDef metaGraphDef; try { metaGraphDef = MetaGraphDef.parseFrom(metaGraph.data().capacity(metaGraph.length()).asByteBuffer()); } catch (InvalidProtocolBufferException ex) { throw new IllegalStateException("ERROR: Unable to import model " + ex); } Map<String, SignatureDef> signatureDefMap = metaGraphDef.getSignatureDefMap(); SignatureDef signatureDef = signatureDefMap.get(savedModelConfig.getSignatureKey()); Map<String, TensorInfo> inputs = signatureDef.getInputsMap(); for (Map.Entry<String, TensorInfo> e : inputs.entrySet()) { inputsMap.put(e.getKey(), e.getValue().getName()); } Map<String, TensorInfo> outputs = signatureDef.getOutputsMap(); for (Map.Entry<String, TensorInfo> e : outputs.entrySet()) { outputsMap.put(e.getKey(), e.getValue().getName()); } return session; }
java
public TF_Session loadSavedModel(SavedModelConfig savedModelConfig, TF_SessionOptions options, TF_Buffer runOptions, TF_Graph graph, Map<String, String> inputsMap, Map<String, String> outputsMap, TF_Status status) { TF_Buffer metaGraph = TF_Buffer.newBuffer(); TF_Session session = TF_LoadSessionFromSavedModel(options, runOptions, new BytePointer(savedModelConfig.getSavedModelPath()), new BytePointer(savedModelConfig.getModelTag()), 1, graph, metaGraph, status); if (TF_GetCode(status) != TF_OK) { throw new IllegalStateException("ERROR: Unable to import model " + TF_Message(status).getString()); } MetaGraphDef metaGraphDef; try { metaGraphDef = MetaGraphDef.parseFrom(metaGraph.data().capacity(metaGraph.length()).asByteBuffer()); } catch (InvalidProtocolBufferException ex) { throw new IllegalStateException("ERROR: Unable to import model " + ex); } Map<String, SignatureDef> signatureDefMap = metaGraphDef.getSignatureDefMap(); SignatureDef signatureDef = signatureDefMap.get(savedModelConfig.getSignatureKey()); Map<String, TensorInfo> inputs = signatureDef.getInputsMap(); for (Map.Entry<String, TensorInfo> e : inputs.entrySet()) { inputsMap.put(e.getKey(), e.getValue().getName()); } Map<String, TensorInfo> outputs = signatureDef.getOutputsMap(); for (Map.Entry<String, TensorInfo> e : outputs.entrySet()) { outputsMap.put(e.getKey(), e.getValue().getName()); } return session; }
[ "public", "TF_Session", "loadSavedModel", "(", "SavedModelConfig", "savedModelConfig", ",", "TF_SessionOptions", "options", ",", "TF_Buffer", "runOptions", ",", "TF_Graph", "graph", ",", "Map", "<", "String", ",", "String", ">", "inputsMap", ",", "Map", "<", "Stri...
Load a session based on the saved model @param savedModelConfig the configuration for the saved model @param options the session options to use @param runOptions the run configuration to use @param graph the tf graph to use @param inputsMap the input map @param outputsMap the output names @param status the status object to use for verifying the results @return
[ "Load", "a", "session", "based", "on", "the", "saved", "model" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-tensorflow/src/main/java/org/nd4j/tensorflow/conversion/TensorflowConversion.java#L357-L385
Impetus/Kundera
src/kundera-couchdb/src/main/java/com/impetus/client/couchdb/CouchDBClient.java
CouchDBClient.getResponse
private HttpResponse getResponse(StringBuilder q, String _id) throws URISyntaxException, IOException, ClientProtocolException { URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(), _id, q.toString(), null); HttpGet get = new HttpGet(uri); get.addHeader("Accept", "application/json"); return httpClient.execute(httpHost, get, CouchDBUtils.getContext(httpHost)); }
java
private HttpResponse getResponse(StringBuilder q, String _id) throws URISyntaxException, IOException, ClientProtocolException { URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(), _id, q.toString(), null); HttpGet get = new HttpGet(uri); get.addHeader("Accept", "application/json"); return httpClient.execute(httpHost, get, CouchDBUtils.getContext(httpHost)); }
[ "private", "HttpResponse", "getResponse", "(", "StringBuilder", "q", ",", "String", "_id", ")", "throws", "URISyntaxException", ",", "IOException", ",", "ClientProtocolException", "{", "URI", "uri", "=", "new", "URI", "(", "CouchDBConstants", ".", "PROTOCOL", ",",...
Gets the response. @param q the q @param _id the _id @return the response @throws URISyntaxException the URI syntax exception @throws IOException Signals that an I/O exception has occurred. @throws ClientProtocolException the client protocol exception
[ "Gets", "the", "response", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-couchdb/src/main/java/com/impetus/client/couchdb/CouchDBClient.java#L1096-L1104
apache/incubator-druid
core/src/main/java/org/apache/druid/java/util/common/StreamUtils.java
StreamUtils.copyAndClose
public static long copyAndClose(InputStream is, OutputStream os) throws IOException { try { final long retval = ByteStreams.copy(is, os); // Workarround for http://hg.openjdk.java.net/jdk8/jdk8/jdk/rev/759aa847dcaf os.flush(); return retval; } finally { is.close(); os.close(); } }
java
public static long copyAndClose(InputStream is, OutputStream os) throws IOException { try { final long retval = ByteStreams.copy(is, os); // Workarround for http://hg.openjdk.java.net/jdk8/jdk8/jdk/rev/759aa847dcaf os.flush(); return retval; } finally { is.close(); os.close(); } }
[ "public", "static", "long", "copyAndClose", "(", "InputStream", "is", ",", "OutputStream", "os", ")", "throws", "IOException", "{", "try", "{", "final", "long", "retval", "=", "ByteStreams", ".", "copy", "(", "is", ",", "os", ")", ";", "// Workarround for ht...
Copy from `is` to `os` and close the streams regardless of the result. @param is The `InputStream` to copy results from. It is closed @param os The `OutputStream` to copy results to. It is closed @return The count of bytes written to `os` @throws IOException
[ "Copy", "from", "is", "to", "os", "and", "close", "the", "streams", "regardless", "of", "the", "result", "." ]
train
https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/core/src/main/java/org/apache/druid/java/util/common/StreamUtils.java#L74-L86
airlift/slice
src/main/java/io/airlift/slice/UnsafeSliceFactory.java
UnsafeSliceFactory.newSlice
public Slice newSlice(long address, int size, Object reference) { if (address <= 0) { throw new IllegalArgumentException("Invalid address: " + address); } if (reference == null) { throw new NullPointerException("Object reference is null"); } if (size == 0) { return Slices.EMPTY_SLICE; } return new Slice(null, address, size, size, reference); }
java
public Slice newSlice(long address, int size, Object reference) { if (address <= 0) { throw new IllegalArgumentException("Invalid address: " + address); } if (reference == null) { throw new NullPointerException("Object reference is null"); } if (size == 0) { return Slices.EMPTY_SLICE; } return new Slice(null, address, size, size, reference); }
[ "public", "Slice", "newSlice", "(", "long", "address", ",", "int", "size", ",", "Object", "reference", ")", "{", "if", "(", "address", "<=", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Invalid address: \"", "+", "address", ")", ";", ...
Creates a slice for directly a raw memory address. This is inherently unsafe as it may be used to access arbitrary memory. The slice will hold the specified object reference to prevent the garbage collector from freeing it while it is in use by the slice. @param address the raw memory address base @param size the size of the slice @param reference the object reference @return the unsafe slice
[ "Creates", "a", "slice", "for", "directly", "a", "raw", "memory", "address", ".", "This", "is", "inherently", "unsafe", "as", "it", "may", "be", "used", "to", "access", "arbitrary", "memory", ".", "The", "slice", "will", "hold", "the", "specified", "object...
train
https://github.com/airlift/slice/blob/7166cb0319e3655f8ba15f5a7ccf3d2f721c1242/src/main/java/io/airlift/slice/UnsafeSliceFactory.java#L86-L98
UrielCh/ovh-java-sdk
ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java
ApiOvhOrder.license_plesk_new_GET
public ArrayList<String> license_plesk_new_GET(OvhOrderableAntivirusEnum antivirus, OvhPleskApplicationSetEnum applicationSet, OvhOrderablePleskDomainNumberEnum domainNumber, String ip, OvhOrderablePleskLanguagePackEnum languagePackNumber, Boolean powerpack, Boolean resellerManagement, OvhLicenseTypeEnum serviceType, OvhPleskVersionEnum version, Boolean wordpressToolkit) throws IOException { String qPath = "/order/license/plesk/new"; StringBuilder sb = path(qPath); query(sb, "antivirus", antivirus); query(sb, "applicationSet", applicationSet); query(sb, "domainNumber", domainNumber); query(sb, "ip", ip); query(sb, "languagePackNumber", languagePackNumber); query(sb, "powerpack", powerpack); query(sb, "resellerManagement", resellerManagement); query(sb, "serviceType", serviceType); query(sb, "version", version); query(sb, "wordpressToolkit", wordpressToolkit); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, t1); }
java
public ArrayList<String> license_plesk_new_GET(OvhOrderableAntivirusEnum antivirus, OvhPleskApplicationSetEnum applicationSet, OvhOrderablePleskDomainNumberEnum domainNumber, String ip, OvhOrderablePleskLanguagePackEnum languagePackNumber, Boolean powerpack, Boolean resellerManagement, OvhLicenseTypeEnum serviceType, OvhPleskVersionEnum version, Boolean wordpressToolkit) throws IOException { String qPath = "/order/license/plesk/new"; StringBuilder sb = path(qPath); query(sb, "antivirus", antivirus); query(sb, "applicationSet", applicationSet); query(sb, "domainNumber", domainNumber); query(sb, "ip", ip); query(sb, "languagePackNumber", languagePackNumber); query(sb, "powerpack", powerpack); query(sb, "resellerManagement", resellerManagement); query(sb, "serviceType", serviceType); query(sb, "version", version); query(sb, "wordpressToolkit", wordpressToolkit); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, t1); }
[ "public", "ArrayList", "<", "String", ">", "license_plesk_new_GET", "(", "OvhOrderableAntivirusEnum", "antivirus", ",", "OvhPleskApplicationSetEnum", "applicationSet", ",", "OvhOrderablePleskDomainNumberEnum", "domainNumber", ",", "String", "ip", ",", "OvhOrderablePleskLanguage...
Get allowed durations for 'new' option REST: GET /order/license/plesk/new @param serviceType [required] # DEPRECATED # The kind of service on which this license will be used # Will not be used, keeped only for compatibility # @param languagePackNumber [required] The amount of language pack numbers to include in this licences @param resellerManagement [required] Reseller management option activation @param antivirus [required] The antivirus to enable on this Plesk license @param wordpressToolkit [required] WordpressToolkit option activation @param ip [required] Ip on which this license would be installed @param domainNumber [required] This license domain number @param applicationSet [required] Wanted application set @param version [required] This license version @param powerpack [required] powerpack current activation state on your license
[ "Get", "allowed", "durations", "for", "new", "option" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java#L1764-L1779
code4everything/util
src/main/java/com/zhazhapan/util/DateUtils.java
DateUtils.add
public static Date add(Date date, int field, int amount) { CALENDAR.setTime(date); CALENDAR.add(field, amount); return CALENDAR.getTime(); }
java
public static Date add(Date date, int field, int amount) { CALENDAR.setTime(date); CALENDAR.add(field, amount); return CALENDAR.getTime(); }
[ "public", "static", "Date", "add", "(", "Date", "date", ",", "int", "field", ",", "int", "amount", ")", "{", "CALENDAR", ".", "setTime", "(", "date", ")", ";", "CALENDAR", ".", "add", "(", "field", ",", "amount", ")", ";", "return", "CALENDAR", ".", ...
日期添加 @param date 日期 @param field 添加区域 {@link Calendar#DATE} {@link Calendar#MONTH} {@link Calendar#YEAR} @param amount 数量 @return 添加后的日期
[ "日期添加" ]
train
https://github.com/code4everything/util/blob/1fc9f0ead1108f4d7208ba7c000df4244f708418/src/main/java/com/zhazhapan/util/DateUtils.java#L525-L529
languagetool-org/languagetool
languagetool-language-modules/de/src/main/java/org/languagetool/rules/de/SubjectVerbAgreementRule.java
SubjectVerbAgreementRule.containsOnlyInfinitivesToTheLeft
private boolean containsOnlyInfinitivesToTheLeft(AnalyzedTokenReadings[] tokens, int startPos) throws IOException { int infinitives = 0; for (int i = startPos; i > 0; i--) { String token = tokens[i].getToken(); if (tokens[i].hasPartialPosTag("SUB:")) { AnalyzedTokenReadings lookup = tagger.lookup(token.toLowerCase()); if (lookup != null && lookup.hasPosTagStartingWith("VER:INF")) { infinitives++; } else { return false; } } } return infinitives >= 2; }
java
private boolean containsOnlyInfinitivesToTheLeft(AnalyzedTokenReadings[] tokens, int startPos) throws IOException { int infinitives = 0; for (int i = startPos; i > 0; i--) { String token = tokens[i].getToken(); if (tokens[i].hasPartialPosTag("SUB:")) { AnalyzedTokenReadings lookup = tagger.lookup(token.toLowerCase()); if (lookup != null && lookup.hasPosTagStartingWith("VER:INF")) { infinitives++; } else { return false; } } } return infinitives >= 2; }
[ "private", "boolean", "containsOnlyInfinitivesToTheLeft", "(", "AnalyzedTokenReadings", "[", "]", "tokens", ",", "int", "startPos", ")", "throws", "IOException", "{", "int", "infinitives", "=", "0", ";", "for", "(", "int", "i", "=", "startPos", ";", "i", ">", ...
No false alarm on ""Das Kopieren und Einfügen ist sehr nützlich." etc.
[ "No", "false", "alarm", "on", "Das", "Kopieren", "und", "Einfügen", "ist", "sehr", "nützlich", ".", "etc", "." ]
train
https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-language-modules/de/src/main/java/org/languagetool/rules/de/SubjectVerbAgreementRule.java#L300-L314
mediathekview/MLib
src/main/java/de/mediathekview/mlib/tool/TimedTextMarkupLanguageParser.java
TimedTextMarkupLanguageParser.toSrt
public void toSrt(Path srtFile) { try (FileOutputStream fos = new FileOutputStream(srtFile.toFile()); OutputStreamWriter osw = new OutputStreamWriter(fos, Charset.forName("UTF-8")); PrintWriter writer = new PrintWriter(osw)) { long counter = 1; for (Subtitle title : subtitleList) { writer.println(counter); writer.println(srtFormat.format(title.begin) + " --> " + srtFormat.format(title.end)); for (StyledString entry : title.listOfStrings) { if (!entry.color.isEmpty()) { writer.print("<font color=\"" + entry.color + "\">"); } writer.print(entry.text); if (!entry.color.isEmpty()) { writer.print("</font>"); } writer.println(); } writer.println(""); counter++; } } catch (Exception ex) { Log.errorLog(201036470, ex, "File: " + srtFile); } }
java
public void toSrt(Path srtFile) { try (FileOutputStream fos = new FileOutputStream(srtFile.toFile()); OutputStreamWriter osw = new OutputStreamWriter(fos, Charset.forName("UTF-8")); PrintWriter writer = new PrintWriter(osw)) { long counter = 1; for (Subtitle title : subtitleList) { writer.println(counter); writer.println(srtFormat.format(title.begin) + " --> " + srtFormat.format(title.end)); for (StyledString entry : title.listOfStrings) { if (!entry.color.isEmpty()) { writer.print("<font color=\"" + entry.color + "\">"); } writer.print(entry.text); if (!entry.color.isEmpty()) { writer.print("</font>"); } writer.println(); } writer.println(""); counter++; } } catch (Exception ex) { Log.errorLog(201036470, ex, "File: " + srtFile); } }
[ "public", "void", "toSrt", "(", "Path", "srtFile", ")", "{", "try", "(", "FileOutputStream", "fos", "=", "new", "FileOutputStream", "(", "srtFile", ".", "toFile", "(", ")", ")", ";", "OutputStreamWriter", "osw", "=", "new", "OutputStreamWriter", "(", "fos", ...
Convert internal representation into SubRip Text Format and save to file.
[ "Convert", "internal", "representation", "into", "SubRip", "Text", "Format", "and", "save", "to", "file", "." ]
train
https://github.com/mediathekview/MLib/blob/01fd5791d87390fea7536275b8a2d4407fc00908/src/main/java/de/mediathekview/mlib/tool/TimedTextMarkupLanguageParser.java#L296-L320
auth0/Lock.Android
lib/src/main/java/com/auth0/android/lock/views/ViewUtils.java
ViewUtils.dipToPixels
static float dipToPixels(Resources resources, int dip) { return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, resources.getDisplayMetrics()); }
java
static float dipToPixels(Resources resources, int dip) { return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, resources.getDisplayMetrics()); }
[ "static", "float", "dipToPixels", "(", "Resources", "resources", ",", "int", "dip", ")", "{", "return", "TypedValue", ".", "applyDimension", "(", "TypedValue", ".", "COMPLEX_UNIT_DIP", ",", "dip", ",", "resources", ".", "getDisplayMetrics", "(", ")", ")", ";",...
Converts dp into px. @param resources the context's current resources. @param dip the dp value to convert to px. @return the result px value.
[ "Converts", "dp", "into", "px", "." ]
train
https://github.com/auth0/Lock.Android/blob/8eb2a979048d2eb6cf0ec631e82e6c3fe6e7d220/lib/src/main/java/com/auth0/android/lock/views/ViewUtils.java#L75-L77
benmccann/xero-java-client
xjc-plugin/src/main/java/com/connectifier/xeroclient/jaxb/PluginImpl.java
PluginImpl.updateArrayOfSetters
private void updateArrayOfSetters(ClassOutline co, JCodeModel model) { JDefinedClass implClass = co.implClass; List<JMethod> removedMethods = new ArrayList<>(); Iterator<JMethod> iter = implClass.methods().iterator(); while (iter.hasNext()) { JMethod method = iter.next(); if (method.params().size() == 1 && method.params().get(0).type().name().startsWith("ArrayOf")) { removedMethods.add(method); iter.remove(); } } for (JMethod removed : removedMethods) { // Parse the old code to get the variable name StringWriter oldWriter = new StringWriter(); removed.body().state(new JFormatter(oldWriter)); String oldBody = oldWriter.toString(); String varName = oldBody.substring(oldBody.indexOf("this.") + "this.".length(), oldBody.indexOf(" = ")); // Build the new method JType arrType = removed.params().get(0).type(); String type = arrType.name().substring("ArrayOf".length()); JFieldVar field = implClass.fields().get(varName); String fieldName = model._getClass(field.type().fullName()).fields().keySet().iterator().next(); JMethod newMethod = implClass.method(removed.mods().getValue(), Void.TYPE, removed.name()); newMethod.param(model.ref("java.util.List").narrow(model.ref(type)), "value"); newMethod.body().decl(arrType, "arr", JExpr._new(arrType)); newMethod.body().directStatement("arr.get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1) + "().addAll(value);"); newMethod.body().directStatement("this." + varName + " = arr;"); } }
java
private void updateArrayOfSetters(ClassOutline co, JCodeModel model) { JDefinedClass implClass = co.implClass; List<JMethod> removedMethods = new ArrayList<>(); Iterator<JMethod> iter = implClass.methods().iterator(); while (iter.hasNext()) { JMethod method = iter.next(); if (method.params().size() == 1 && method.params().get(0).type().name().startsWith("ArrayOf")) { removedMethods.add(method); iter.remove(); } } for (JMethod removed : removedMethods) { // Parse the old code to get the variable name StringWriter oldWriter = new StringWriter(); removed.body().state(new JFormatter(oldWriter)); String oldBody = oldWriter.toString(); String varName = oldBody.substring(oldBody.indexOf("this.") + "this.".length(), oldBody.indexOf(" = ")); // Build the new method JType arrType = removed.params().get(0).type(); String type = arrType.name().substring("ArrayOf".length()); JFieldVar field = implClass.fields().get(varName); String fieldName = model._getClass(field.type().fullName()).fields().keySet().iterator().next(); JMethod newMethod = implClass.method(removed.mods().getValue(), Void.TYPE, removed.name()); newMethod.param(model.ref("java.util.List").narrow(model.ref(type)), "value"); newMethod.body().decl(arrType, "arr", JExpr._new(arrType)); newMethod.body().directStatement("arr.get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1) + "().addAll(value);"); newMethod.body().directStatement("this." + varName + " = arr;"); } }
[ "private", "void", "updateArrayOfSetters", "(", "ClassOutline", "co", ",", "JCodeModel", "model", ")", "{", "JDefinedClass", "implClass", "=", "co", ".", "implClass", ";", "List", "<", "JMethod", ">", "removedMethods", "=", "new", "ArrayList", "<>", "(", ")", ...
Update setters to use Java List. For example: setLineItems(ArrayOfLineItem value) -> setLineItems(List<LineItem> value)
[ "Update", "setters", "to", "use", "Java", "List", ".", "For", "example", ":", "setLineItems", "(", "ArrayOfLineItem", "value", ")", "-", ">", "setLineItems", "(", "List<LineItem", ">", "value", ")" ]
train
https://github.com/benmccann/xero-java-client/blob/1c84acf36929ea2a4a3ac5f2527a4e9252229f18/xjc-plugin/src/main/java/com/connectifier/xeroclient/jaxb/PluginImpl.java#L92-L124
google/error-prone-javac
src/jdk.javadoc/share/classes/com/sun/tools/doclets/formats/html/markup/HtmlTree.java
HtmlTree.UL
public static HtmlTree UL(HtmlStyle styleClass, Content body) { HtmlTree htmltree = new HtmlTree(HtmlTag.UL, nullCheck(body)); htmltree.addStyle(nullCheck(styleClass)); return htmltree; }
java
public static HtmlTree UL(HtmlStyle styleClass, Content body) { HtmlTree htmltree = new HtmlTree(HtmlTag.UL, nullCheck(body)); htmltree.addStyle(nullCheck(styleClass)); return htmltree; }
[ "public", "static", "HtmlTree", "UL", "(", "HtmlStyle", "styleClass", ",", "Content", "body", ")", "{", "HtmlTree", "htmltree", "=", "new", "HtmlTree", "(", "HtmlTag", ".", "UL", ",", "nullCheck", "(", "body", ")", ")", ";", "htmltree", ".", "addStyle", ...
Generates a UL tag with the style class attribute and some content. @param styleClass style for the tag @param body content for the tag @return an HtmlTree object for the UL tag
[ "Generates", "a", "UL", "tag", "with", "the", "style", "class", "attribute", "and", "some", "content", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/doclets/formats/html/markup/HtmlTree.java#L833-L837
Azure/azure-sdk-for-java
recoveryservices.backup/resource-manager/v2017_07_01/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2017_07_01/implementation/ProtectionIntentsInner.java
ProtectionIntentsInner.createOrUpdateAsync
public Observable<ProtectionIntentResourceInner> createOrUpdateAsync(String vaultName, String resourceGroupName, String fabricName, String intentObjectName, ProtectionIntentResourceInner parameters) { return createOrUpdateWithServiceResponseAsync(vaultName, resourceGroupName, fabricName, intentObjectName, parameters).map(new Func1<ServiceResponse<ProtectionIntentResourceInner>, ProtectionIntentResourceInner>() { @Override public ProtectionIntentResourceInner call(ServiceResponse<ProtectionIntentResourceInner> response) { return response.body(); } }); }
java
public Observable<ProtectionIntentResourceInner> createOrUpdateAsync(String vaultName, String resourceGroupName, String fabricName, String intentObjectName, ProtectionIntentResourceInner parameters) { return createOrUpdateWithServiceResponseAsync(vaultName, resourceGroupName, fabricName, intentObjectName, parameters).map(new Func1<ServiceResponse<ProtectionIntentResourceInner>, ProtectionIntentResourceInner>() { @Override public ProtectionIntentResourceInner call(ServiceResponse<ProtectionIntentResourceInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "ProtectionIntentResourceInner", ">", "createOrUpdateAsync", "(", "String", "vaultName", ",", "String", "resourceGroupName", ",", "String", "fabricName", ",", "String", "intentObjectName", ",", "ProtectionIntentResourceInner", "parameters", ")",...
Create Intent for Enabling backup of an item. This is a synchronous operation. @param vaultName The name of the recovery services vault. @param resourceGroupName The name of the resource group where the recovery services vault is present. @param fabricName Fabric name associated with the backup item. @param intentObjectName Intent object name. @param parameters resource backed up item @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the ProtectionIntentResourceInner object
[ "Create", "Intent", "for", "Enabling", "backup", "of", "an", "item", ".", "This", "is", "a", "synchronous", "operation", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/recoveryservices.backup/resource-manager/v2017_07_01/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2017_07_01/implementation/ProtectionIntentsInner.java#L209-L216
TheCoder4eu/BootsFaces-OSP
src/main/java/net/bootsfaces/component/panel/PanelRenderer.java
PanelRenderer.decode
@Override public void decode(FacesContext context, UIComponent component) { Panel panel = (Panel) component; String clientId = panel.getClientId(context); String jQueryClientID = clientId.replace(":", "_"); // the panel uses two ids to send requests to the server! new AJAXRenderer().decode(context, component, panel.getClientId(context)); new AJAXRenderer().decode(context, component, jQueryClientID+"content"); String collapseStateId = clientId.replace(":", "_") + "_collapsed"; String submittedValue = (String) context.getExternalContext().getRequestParameterMap().get(collapseStateId); if (submittedValue != null) { if (Boolean.valueOf(submittedValue) != panel.isCollapsed()) panel.setCollapsed(Boolean.valueOf(submittedValue)); } }
java
@Override public void decode(FacesContext context, UIComponent component) { Panel panel = (Panel) component; String clientId = panel.getClientId(context); String jQueryClientID = clientId.replace(":", "_"); // the panel uses two ids to send requests to the server! new AJAXRenderer().decode(context, component, panel.getClientId(context)); new AJAXRenderer().decode(context, component, jQueryClientID+"content"); String collapseStateId = clientId.replace(":", "_") + "_collapsed"; String submittedValue = (String) context.getExternalContext().getRequestParameterMap().get(collapseStateId); if (submittedValue != null) { if (Boolean.valueOf(submittedValue) != panel.isCollapsed()) panel.setCollapsed(Boolean.valueOf(submittedValue)); } }
[ "@", "Override", "public", "void", "decode", "(", "FacesContext", "context", ",", "UIComponent", "component", ")", "{", "Panel", "panel", "=", "(", "Panel", ")", "component", ";", "String", "clientId", "=", "panel", ".", "getClientId", "(", "context", ")", ...
This methods receives and processes input made by the user. More specifically, it ckecks whether the user has interacted with the current b:panel. 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:panel.
[ "This", "methods", "receives", "and", "processes", "input", "made", "by", "the", "user", ".", "More", "specifically", "it", "ckecks", "whether", "the", "user", "has", "interacted", "with", "the", "current", "b", ":", "panel", ".", "The", "default", "implemen...
train
https://github.com/TheCoder4eu/BootsFaces-OSP/blob/d1a70952bc240979b5272fa4fe1c7f100873add0/src/main/java/net/bootsfaces/component/panel/PanelRenderer.java#L51-L69
comapi/comapi-sdk-android
COMAPI/foundation/src/main/java/com/comapi/internal/helpers/APIHelper.java
APIHelper.createMessage
public static MessageToSend createMessage(@NonNull String conversationId, @NonNull String body, @Nullable String title) { Map<String, Object> fcm = new HashMap<>(); String fcmMsg = !TextUtils.isEmpty(body) ? body : "attachments"; fcm.put("notification", new Notification(title != null ? title : conversationId, fcmMsg, conversationId)); Map<String, Object> apns = new HashMap<>(); apns.put("alert", fcmMsg); MessageToSend.Builder builder = MessageToSend.builder(); if (!TextUtils.isEmpty(body)) { Part bodyPart = Part.builder().setData(body).setName("body").setSize(body.length()).setType("text/plain").build(); builder.addPart(bodyPart); } return builder.setAlert(fcm, apns).build(); }
java
public static MessageToSend createMessage(@NonNull String conversationId, @NonNull String body, @Nullable String title) { Map<String, Object> fcm = new HashMap<>(); String fcmMsg = !TextUtils.isEmpty(body) ? body : "attachments"; fcm.put("notification", new Notification(title != null ? title : conversationId, fcmMsg, conversationId)); Map<String, Object> apns = new HashMap<>(); apns.put("alert", fcmMsg); MessageToSend.Builder builder = MessageToSend.builder(); if (!TextUtils.isEmpty(body)) { Part bodyPart = Part.builder().setData(body).setName("body").setSize(body.length()).setType("text/plain").build(); builder.addPart(bodyPart); } return builder.setAlert(fcm, apns).build(); }
[ "public", "static", "MessageToSend", "createMessage", "(", "@", "NonNull", "String", "conversationId", ",", "@", "NonNull", "String", "body", ",", "@", "Nullable", "String", "title", ")", "{", "Map", "<", "String", ",", "Object", ">", "fcm", "=", "new", "H...
Convenience method to create a Message object with a single text body part. @param conversationId Unique conversation id. @param body Message text body. @param title Remote notification title. @return Message object that can by sent to other participants of the conversation.
[ "Convenience", "method", "to", "create", "a", "Message", "object", "with", "a", "single", "text", "body", "part", "." ]
train
https://github.com/comapi/comapi-sdk-android/blob/53140a58d5a62afe196047ccc5120bfe090ef211/COMAPI/foundation/src/main/java/com/comapi/internal/helpers/APIHelper.java#L50-L64
UrielCh/ovh-java-sdk
ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java
ApiOvhTelephony.billingAccount_line_serviceName_click2Call_POST
public void billingAccount_line_serviceName_click2Call_POST(String billingAccount, String serviceName, String calledNumber, String callingNumber, Boolean intercom) throws IOException { String qPath = "/telephony/{billingAccount}/line/{serviceName}/click2Call"; StringBuilder sb = path(qPath, billingAccount, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "calledNumber", calledNumber); addBody(o, "callingNumber", callingNumber); addBody(o, "intercom", intercom); exec(qPath, "POST", sb.toString(), o); }
java
public void billingAccount_line_serviceName_click2Call_POST(String billingAccount, String serviceName, String calledNumber, String callingNumber, Boolean intercom) throws IOException { String qPath = "/telephony/{billingAccount}/line/{serviceName}/click2Call"; StringBuilder sb = path(qPath, billingAccount, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "calledNumber", calledNumber); addBody(o, "callingNumber", callingNumber); addBody(o, "intercom", intercom); exec(qPath, "POST", sb.toString(), o); }
[ "public", "void", "billingAccount_line_serviceName_click2Call_POST", "(", "String", "billingAccount", ",", "String", "serviceName", ",", "String", "calledNumber", ",", "String", "callingNumber", ",", "Boolean", "intercom", ")", "throws", "IOException", "{", "String", "q...
Make a phone call from the current line REST: POST /telephony/{billingAccount}/line/{serviceName}/click2Call @param calledNumber [required] @param callingNumber [required] @param intercom [required] Activate the calling number in intercom mode automatically (pick up and speaker automatic activation). @param billingAccount [required] The name of your billingAccount @param serviceName [required]
[ "Make", "a", "phone", "call", "from", "the", "current", "line" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java#L819-L827
ironjacamar/ironjacamar
codegenerator/src/main/java/org/ironjacamar/codegenerator/code/AbstractCodeGen.java
AbstractCodeGen.writeClassComment
void writeClassComment(Definition def, Writer out) throws IOException { out.write("/**\n"); out.write(" * " + getClassName(def)); writeEol(out); out.write(" *\n"); out.write(" * @version $Revision: $\n"); out.write(" */\n"); }
java
void writeClassComment(Definition def, Writer out) throws IOException { out.write("/**\n"); out.write(" * " + getClassName(def)); writeEol(out); out.write(" *\n"); out.write(" * @version $Revision: $\n"); out.write(" */\n"); }
[ "void", "writeClassComment", "(", "Definition", "def", ",", "Writer", "out", ")", "throws", "IOException", "{", "out", ".", "write", "(", "\"/**\\n\"", ")", ";", "out", ".", "write", "(", "\" * \"", "+", "getClassName", "(", "def", ")", ")", ";", "writeE...
Output class comment @param def definition @param out Writer @throws IOException ioException
[ "Output", "class", "comment" ]
train
https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/codegenerator/src/main/java/org/ironjacamar/codegenerator/code/AbstractCodeGen.java#L67-L75
comapi/comapi-chat-sdk-android
COMAPI/chat/src/main/java/com/comapi/chat/ChatController.java
ChatController.synchroniseConversation
Observable<ChatResult> synchroniseConversation(String conversationId) { return checkState().flatMap(client -> client.service().messaging() .queryMessages(conversationId, null, 1) .map(result -> { if (result.isSuccessful() && result.getResult() != null) { return (long) result.getResult().getLatestEventId(); } return -1L; }) .flatMap(result -> persistenceController.getConversation(conversationId).map(loaded -> compare(result, loaded))) .flatMap(this::updateLocalConversationList) .flatMap(result -> lookForMissingEvents(client, result)) .map(result -> new ChatResult(result.isSuccessful, null))); }
java
Observable<ChatResult> synchroniseConversation(String conversationId) { return checkState().flatMap(client -> client.service().messaging() .queryMessages(conversationId, null, 1) .map(result -> { if (result.isSuccessful() && result.getResult() != null) { return (long) result.getResult().getLatestEventId(); } return -1L; }) .flatMap(result -> persistenceController.getConversation(conversationId).map(loaded -> compare(result, loaded))) .flatMap(this::updateLocalConversationList) .flatMap(result -> lookForMissingEvents(client, result)) .map(result -> new ChatResult(result.isSuccessful, null))); }
[ "Observable", "<", "ChatResult", ">", "synchroniseConversation", "(", "String", "conversationId", ")", "{", "return", "checkState", "(", ")", ".", "flatMap", "(", "client", "->", "client", ".", "service", "(", ")", ".", "messaging", "(", ")", ".", "queryMess...
Updates single conversation state. @return Result of synchronisation with services.
[ "Updates", "single", "conversation", "state", "." ]
train
https://github.com/comapi/comapi-chat-sdk-android/blob/388f37bfacb7793ce30c92ab70e5f32848bbe460/COMAPI/chat/src/main/java/com/comapi/chat/ChatController.java#L504-L518
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/AbstractReturnValueIgnored.java
AbstractReturnValueIgnored.mockitoInvocation
private static boolean mockitoInvocation(Tree tree, VisitorState state) { if (!(tree instanceof JCMethodInvocation)) { return false; } JCMethodInvocation invocation = (JCMethodInvocation) tree; if (!(invocation.getMethodSelect() instanceof JCFieldAccess)) { return false; } ExpressionTree receiver = ASTHelpers.getReceiver(invocation); return MOCKITO_MATCHER.matches(receiver, state); }
java
private static boolean mockitoInvocation(Tree tree, VisitorState state) { if (!(tree instanceof JCMethodInvocation)) { return false; } JCMethodInvocation invocation = (JCMethodInvocation) tree; if (!(invocation.getMethodSelect() instanceof JCFieldAccess)) { return false; } ExpressionTree receiver = ASTHelpers.getReceiver(invocation); return MOCKITO_MATCHER.matches(receiver, state); }
[ "private", "static", "boolean", "mockitoInvocation", "(", "Tree", "tree", ",", "VisitorState", "state", ")", "{", "if", "(", "!", "(", "tree", "instanceof", "JCMethodInvocation", ")", ")", "{", "return", "false", ";", "}", "JCMethodInvocation", "invocation", "...
Don't match the method that is invoked through {@code Mockito.verify(t)} or {@code doReturn(val).when(t)}.
[ "Don", "t", "match", "the", "method", "that", "is", "invoked", "through", "{" ]
train
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/AbstractReturnValueIgnored.java#L285-L295
Hygieia/Hygieia
api/src/main/java/com/capitalone/dashboard/service/DynamicPipelineServiceImpl.java
DynamicPipelineServiceImpl.processCommits
protected void processCommits(Pipeline pipeline, List<Commit> commits) { // TODO when processing commits should we only add the commits that are within the time boundaries? Set<String> seenRevisionNumbers = new HashSet<>(); if (logger.isDebugEnabled()) { StringBuilder sb = new StringBuilder(); sb.append("\n===== Commit List =====\n"); for (Commit commit : commits) { sb.append(" - " + commit.getId() + " (" + commit.getScmRevisionNumber() + ") - " + commit.getScmCommitLog() + "\n"); } logger.debug(sb.toString()); } for (Commit commit : commits) { boolean commitNotSeen = seenRevisionNumbers.add(commit.getScmRevisionNumber()); if (commitNotSeen) { pipeline.addCommit(PipelineStage.COMMIT.getName(), new PipelineCommit(commit, commit.getScmCommitTimestamp())); } } }
java
protected void processCommits(Pipeline pipeline, List<Commit> commits) { // TODO when processing commits should we only add the commits that are within the time boundaries? Set<String> seenRevisionNumbers = new HashSet<>(); if (logger.isDebugEnabled()) { StringBuilder sb = new StringBuilder(); sb.append("\n===== Commit List =====\n"); for (Commit commit : commits) { sb.append(" - " + commit.getId() + " (" + commit.getScmRevisionNumber() + ") - " + commit.getScmCommitLog() + "\n"); } logger.debug(sb.toString()); } for (Commit commit : commits) { boolean commitNotSeen = seenRevisionNumbers.add(commit.getScmRevisionNumber()); if (commitNotSeen) { pipeline.addCommit(PipelineStage.COMMIT.getName(), new PipelineCommit(commit, commit.getScmCommitTimestamp())); } } }
[ "protected", "void", "processCommits", "(", "Pipeline", "pipeline", ",", "List", "<", "Commit", ">", "commits", ")", "{", "// TODO when processing commits should we only add the commits that are within the time boundaries?\r", "Set", "<", "String", ">", "seenRevisionNumbers", ...
Computes the commit stage of the pipeline. @param pipeline @param commits
[ "Computes", "the", "commit", "stage", "of", "the", "pipeline", "." ]
train
https://github.com/Hygieia/Hygieia/blob/d8b67a590da2744acf59bcd99d9b34ef1bb84890/api/src/main/java/com/capitalone/dashboard/service/DynamicPipelineServiceImpl.java#L245-L266
banq/jdonframework
src/main/java/com/jdon/util/UtilDateTime.java
UtilDateTime.toTimestamp
public static java.sql.Timestamp toTimestamp(int month, int day, int year, int hour, int minute, int second) { java.util.Date newDate = toDate(month, day, year, hour, minute, second); if (newDate != null) return new java.sql.Timestamp(newDate.getTime()); else return null; }
java
public static java.sql.Timestamp toTimestamp(int month, int day, int year, int hour, int minute, int second) { java.util.Date newDate = toDate(month, day, year, hour, minute, second); if (newDate != null) return new java.sql.Timestamp(newDate.getTime()); else return null; }
[ "public", "static", "java", ".", "sql", ".", "Timestamp", "toTimestamp", "(", "int", "month", ",", "int", "day", ",", "int", "year", ",", "int", "hour", ",", "int", "minute", ",", "int", "second", ")", "{", "java", ".", "util", ".", "Date", "newDate"...
Makes a Timestamp from separate ints for month, day, year, hour, minute, and second. @param month The month int @param day The day int @param year The year int @param hour The hour int @param minute The minute int @param second The second int @return A Timestamp made from separate ints for month, day, year, hour, minute, and second.
[ "Makes", "a", "Timestamp", "from", "separate", "ints", "for", "month", "day", "year", "hour", "minute", "and", "second", "." ]
train
https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/src/main/java/com/jdon/util/UtilDateTime.java#L286-L293
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/REST.java
REST.setProxy
public void setProxy(String proxyHost, int proxyPort) { System.setProperty("http.proxySet", "true"); System.setProperty("http.proxyHost", proxyHost); System.setProperty("http.proxyPort", "" + proxyPort); System.setProperty("https.proxyHost", proxyHost); System.setProperty("https.proxyPort", "" + proxyPort); }
java
public void setProxy(String proxyHost, int proxyPort) { System.setProperty("http.proxySet", "true"); System.setProperty("http.proxyHost", proxyHost); System.setProperty("http.proxyPort", "" + proxyPort); System.setProperty("https.proxyHost", proxyHost); System.setProperty("https.proxyPort", "" + proxyPort); }
[ "public", "void", "setProxy", "(", "String", "proxyHost", ",", "int", "proxyPort", ")", "{", "System", ".", "setProperty", "(", "\"http.proxySet\"", ",", "\"true\"", ")", ";", "System", ".", "setProperty", "(", "\"http.proxyHost\"", ",", "proxyHost", ")", ";",...
Set a proxy for REST-requests. @param proxyHost @param proxyPort
[ "Set", "a", "proxy", "for", "REST", "-", "requests", "." ]
train
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/REST.java#L103-L109
joniles/mpxj
src/main/java/net/sf/mpxj/mpp/Var2Data.java
Var2Data.getDouble
public double getDouble(Integer id, Integer type) { double result = Double.longBitsToDouble(getLong(id, type)); if (Double.isNaN(result)) { result = 0; } return result; }
java
public double getDouble(Integer id, Integer type) { double result = Double.longBitsToDouble(getLong(id, type)); if (Double.isNaN(result)) { result = 0; } return result; }
[ "public", "double", "getDouble", "(", "Integer", "id", ",", "Integer", "type", ")", "{", "double", "result", "=", "Double", ".", "longBitsToDouble", "(", "getLong", "(", "id", ",", "type", ")", ")", ";", "if", "(", "Double", ".", "isNaN", "(", "result"...
This method retrieves a double of the specified type, belonging to the item with the specified unique ID. @param id unique ID of entity to which this data belongs @param type data type identifier @return required double data
[ "This", "method", "retrieves", "a", "double", "of", "the", "specified", "type", "belonging", "to", "the", "item", "with", "the", "specified", "unique", "ID", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpp/Var2Data.java#L390-L398
Azure/azure-sdk-for-java
batch/data-plane/src/main/java/com/microsoft/azure/batch/ComputeNodeOperations.java
ComputeNodeOperations.disableComputeNodeScheduling
public void disableComputeNodeScheduling(String poolId, String nodeId) throws BatchErrorException, IOException { disableComputeNodeScheduling(poolId, nodeId, null, null); }
java
public void disableComputeNodeScheduling(String poolId, String nodeId) throws BatchErrorException, IOException { disableComputeNodeScheduling(poolId, nodeId, null, null); }
[ "public", "void", "disableComputeNodeScheduling", "(", "String", "poolId", ",", "String", "nodeId", ")", "throws", "BatchErrorException", ",", "IOException", "{", "disableComputeNodeScheduling", "(", "poolId", ",", "nodeId", ",", "null", ",", "null", ")", ";", "}"...
Disables task scheduling on the specified compute node. @param poolId The ID of the pool. @param nodeId the ID of the compute node. @throws BatchErrorException Exception thrown when an error response is received from the Batch service. @throws IOException Exception thrown when there is an error in serialization/deserialization of data sent to/received from the Batch service.
[ "Disables", "task", "scheduling", "on", "the", "specified", "compute", "node", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/ComputeNodeOperations.java#L368-L370
looly/hutool
hutool-core/src/main/java/cn/hutool/core/date/format/FastDateFormat.java
FastDateFormat.getDateInstance
public static FastDateFormat getDateInstance(final int style, final TimeZone timeZone) { return cache.getDateInstance(style, timeZone, null); }
java
public static FastDateFormat getDateInstance(final int style, final TimeZone timeZone) { return cache.getDateInstance(style, timeZone, null); }
[ "public", "static", "FastDateFormat", "getDateInstance", "(", "final", "int", "style", ",", "final", "TimeZone", "timeZone", ")", "{", "return", "cache", ".", "getDateInstance", "(", "style", ",", "timeZone", ",", "null", ")", ";", "}" ]
获得 {@link FastDateFormat} 实例<br> 支持缓存 @param style date style: FULL, LONG, MEDIUM, or SHORT @param timeZone 时区{@link TimeZone} @return 本地化 {@link FastDateFormat}
[ "获得", "{", "@link", "FastDateFormat", "}", "实例<br", ">", "支持缓存" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/date/format/FastDateFormat.java#L145-L147
UrielCh/ovh-java-sdk
ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java
ApiOvhTelephony.billingAccount_screen_serviceName_screenLists_POST
public void billingAccount_screen_serviceName_screenLists_POST(String billingAccount, String serviceName, String callNumber, OvhScreenListNatureEnum nature, OvhScreenListTypeEnum type) throws IOException { String qPath = "/telephony/{billingAccount}/screen/{serviceName}/screenLists"; StringBuilder sb = path(qPath, billingAccount, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "callNumber", callNumber); addBody(o, "nature", nature); addBody(o, "type", type); exec(qPath, "POST", sb.toString(), o); }
java
public void billingAccount_screen_serviceName_screenLists_POST(String billingAccount, String serviceName, String callNumber, OvhScreenListNatureEnum nature, OvhScreenListTypeEnum type) throws IOException { String qPath = "/telephony/{billingAccount}/screen/{serviceName}/screenLists"; StringBuilder sb = path(qPath, billingAccount, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "callNumber", callNumber); addBody(o, "nature", nature); addBody(o, "type", type); exec(qPath, "POST", sb.toString(), o); }
[ "public", "void", "billingAccount_screen_serviceName_screenLists_POST", "(", "String", "billingAccount", ",", "String", "serviceName", ",", "String", "callNumber", ",", "OvhScreenListNatureEnum", "nature", ",", "OvhScreenListTypeEnum", "type", ")", "throws", "IOException", ...
Create a new screen list rule REST: POST /telephony/{billingAccount}/screen/{serviceName}/screenLists @param type [required] The type of the generic screen list @param nature [required] The nature of the generic screen list @param callNumber [required] The callNumber of the generic screen list @param billingAccount [required] The name of your billingAccount @param serviceName [required]
[ "Create", "a", "new", "screen", "list", "rule" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java#L5431-L5439
seedstack/shed
src/main/java/org/seedstack/shed/misc/PriorityUtils.java
PriorityUtils.sortByPriority
public static <T> void sortByPriority(List<T> someClasses, ToIntFunction<T> priorityExtractor) { someClasses.sort(Collections.reverseOrder(Comparator.comparingInt(priorityExtractor))); }
java
public static <T> void sortByPriority(List<T> someClasses, ToIntFunction<T> priorityExtractor) { someClasses.sort(Collections.reverseOrder(Comparator.comparingInt(priorityExtractor))); }
[ "public", "static", "<", "T", ">", "void", "sortByPriority", "(", "List", "<", "T", ">", "someClasses", ",", "ToIntFunction", "<", "T", ">", "priorityExtractor", ")", "{", "someClasses", ".", "sort", "(", "Collections", ".", "reverseOrder", "(", "Comparator"...
Sort classes by <strong>descending</strong> order of their priority, meaning the class with the higher priority will be the first element of the sorted list. The priority is determined according to the provided priority extractor. @param someClasses the list of classes to sort. @param priorityExtractor a function that extract a priority from an item.
[ "Sort", "classes", "by", "<strong", ">", "descending<", "/", "strong", ">", "order", "of", "their", "priority", "meaning", "the", "class", "with", "the", "higher", "priority", "will", "be", "the", "first", "element", "of", "the", "sorted", "list", ".", "Th...
train
https://github.com/seedstack/shed/blob/49ecb25aa3777539ab0f29f89abaae5ee93b572e/src/main/java/org/seedstack/shed/misc/PriorityUtils.java#L39-L41
xwiki/xwiki-rendering
xwiki-rendering-wikimodel/src/main/java/org/xwiki/rendering/wikimodel/xwiki/xwiki20/XWikiSerializer2.java
XWikiSerializer2.clearName
public final static String clearName(String name) { boolean stripDots = false; boolean ascii = true; return clearName(name, stripDots, ascii); }
java
public final static String clearName(String name) { boolean stripDots = false; boolean ascii = true; return clearName(name, stripDots, ascii); }
[ "public", "final", "static", "String", "clearName", "(", "String", "name", ")", "{", "boolean", "stripDots", "=", "false", ";", "boolean", "ascii", "=", "true", ";", "return", "clearName", "(", "name", ",", "stripDots", ",", "ascii", ")", ";", "}" ]
Clears the name of files; used while uploading attachments within XWiki RECOMMENDED FOR NAMES OF UPLOADED FILES. (boolean stripDots = false; boolean ascii = true;)
[ "Clears", "the", "name", "of", "files", ";", "used", "while", "uploading", "attachments", "within", "XWiki" ]
train
https://github.com/xwiki/xwiki-rendering/blob/a21cdfcb64ef5b76872e3eedf78c530f26d7beb0/xwiki-rendering-wikimodel/src/main/java/org/xwiki/rendering/wikimodel/xwiki/xwiki20/XWikiSerializer2.java#L570-L575
jayantk/jklol
src/com/jayantkrish/jklol/util/IoUtils.java
IoUtils.getNumberOfColumnsInFile
public static int getNumberOfColumnsInFile(String filename, String delimiter) { try { BufferedReader in = new BufferedReader(new FileReader(filename)); String line; while ((line = in.readLine()) != null) { String[] parts = line.split(delimiter); in.close(); return parts.length; } in.close(); // File is empty. return 0; } catch (IOException e) { throw new RuntimeException(e); } }
java
public static int getNumberOfColumnsInFile(String filename, String delimiter) { try { BufferedReader in = new BufferedReader(new FileReader(filename)); String line; while ((line = in.readLine()) != null) { String[] parts = line.split(delimiter); in.close(); return parts.length; } in.close(); // File is empty. return 0; } catch (IOException e) { throw new RuntimeException(e); } }
[ "public", "static", "int", "getNumberOfColumnsInFile", "(", "String", "filename", ",", "String", "delimiter", ")", "{", "try", "{", "BufferedReader", "in", "=", "new", "BufferedReader", "(", "new", "FileReader", "(", "filename", ")", ")", ";", "String", "line"...
Counts the number of columns in a file delimited by {@code delimiter}. Assumes that the first line of the file is representative of the file as a whole. @param filename @param delimiter @return
[ "Counts", "the", "number", "of", "columns", "in", "a", "file", "delimited", "by", "{", "@code", "delimiter", "}", ".", "Assumes", "that", "the", "first", "line", "of", "the", "file", "is", "representative", "of", "the", "file", "as", "a", "whole", "." ]
train
https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/util/IoUtils.java#L68-L83
youngmonkeys/ezyfox-sfs2x
src/main/java/com/tvd12/ezyfox/sfs2x/serverhandler/UserZoneEventHandler.java
UserZoneEventHandler.checkHandler
protected boolean checkHandler(ZoneHandlerClass handler, ApiZone apiZone) { return apiZone.getName().startsWith(handler.getZoneName()); }
java
protected boolean checkHandler(ZoneHandlerClass handler, ApiZone apiZone) { return apiZone.getName().startsWith(handler.getZoneName()); }
[ "protected", "boolean", "checkHandler", "(", "ZoneHandlerClass", "handler", ",", "ApiZone", "apiZone", ")", "{", "return", "apiZone", ".", "getName", "(", ")", ".", "startsWith", "(", "handler", ".", "getZoneName", "(", ")", ")", ";", "}" ]
Check zone name @param handler structure of handle class @param apiZone api zone reference @return true of false
[ "Check", "zone", "name" ]
train
https://github.com/youngmonkeys/ezyfox-sfs2x/blob/7e004033a3b551c3ae970a0c8f45db7b1ec144de/src/main/java/com/tvd12/ezyfox/sfs2x/serverhandler/UserZoneEventHandler.java#L120-L122
cdk/cdk
base/data/src/main/java/org/openscience/cdk/AtomContainerSet.java
AtomContainerSet.replaceAtomContainer
@Override public void replaceAtomContainer(int position, IAtomContainer container) { IAtomContainer old = atomContainers[position]; old.removeListener(this); atomContainers[position] = container; container.addListener(this); notifyChanged(); }
java
@Override public void replaceAtomContainer(int position, IAtomContainer container) { IAtomContainer old = atomContainers[position]; old.removeListener(this); atomContainers[position] = container; container.addListener(this); notifyChanged(); }
[ "@", "Override", "public", "void", "replaceAtomContainer", "(", "int", "position", ",", "IAtomContainer", "container", ")", "{", "IAtomContainer", "old", "=", "atomContainers", "[", "position", "]", ";", "old", ".", "removeListener", "(", "this", ")", ";", "at...
Replace the AtomContainer at a specific position (array has to be large enough). @param position position in array for AtomContainer @param container the replacement AtomContainer
[ "Replace", "the", "AtomContainer", "at", "a", "specific", "position", "(", "array", "has", "to", "be", "large", "enough", ")", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/base/data/src/main/java/org/openscience/cdk/AtomContainerSet.java#L140-L147
matthewhorridge/owlapi-gwt
owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLHasKeyAxiomImpl_CustomFieldSerializer.java
OWLHasKeyAxiomImpl_CustomFieldSerializer.deserializeInstance
@Override public void deserializeInstance(SerializationStreamReader streamReader, OWLHasKeyAxiomImpl instance) throws SerializationException { deserialize(streamReader, instance); }
java
@Override public void deserializeInstance(SerializationStreamReader streamReader, OWLHasKeyAxiomImpl instance) throws SerializationException { deserialize(streamReader, instance); }
[ "@", "Override", "public", "void", "deserializeInstance", "(", "SerializationStreamReader", "streamReader", ",", "OWLHasKeyAxiomImpl", "instance", ")", "throws", "SerializationException", "{", "deserialize", "(", "streamReader", ",", "instance", ")", ";", "}" ]
Deserializes the content of the object from the {@link com.google.gwt.user.client.rpc.SerializationStreamReader}. @param streamReader the {@link com.google.gwt.user.client.rpc.SerializationStreamReader} to read the object's content from @param instance the object instance to deserialize @throws com.google.gwt.user.client.rpc.SerializationException if the deserialization operation is not successful
[ "Deserializes", "the", "content", "of", "the", "object", "from", "the", "{", "@link", "com", ".", "google", ".", "gwt", ".", "user", ".", "client", ".", "rpc", ".", "SerializationStreamReader", "}", "." ]
train
https://github.com/matthewhorridge/owlapi-gwt/blob/7ab975fb6cef3c8947099983551672a3b5d4e2fd/owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLHasKeyAxiomImpl_CustomFieldSerializer.java#L98-L101
nguillaumin/slick2d-maven
slick2d-core/src/main/java/org/newdawn/slick/util/xml/ObjectTreeParser.java
ObjectTreeParser.parseOnto
public Object parseOnto(String ref, Object target) throws SlickXMLException { return parseOnto(ref, ResourceLoader.getResourceAsStream(ref), target); }
java
public Object parseOnto(String ref, Object target) throws SlickXMLException { return parseOnto(ref, ResourceLoader.getResourceAsStream(ref), target); }
[ "public", "Object", "parseOnto", "(", "String", "ref", ",", "Object", "target", ")", "throws", "SlickXMLException", "{", "return", "parseOnto", "(", "ref", ",", "ResourceLoader", ".", "getResourceAsStream", "(", "ref", ")", ",", "target", ")", ";", "}" ]
Parse the XML document located by the slick resource loader using the reference given. @param ref The reference to the XML document @param target The top level object that represents the root node @return The root element of the newly parse document @throws SlickXMLException Indicates a failure to parse the XML, most likely the XML is malformed in some way.
[ "Parse", "the", "XML", "document", "located", "by", "the", "slick", "resource", "loader", "using", "the", "reference", "given", "." ]
train
https://github.com/nguillaumin/slick2d-maven/blob/8251f88a0ed6a70e726d2468842455cd1f80893f/slick2d-core/src/main/java/org/newdawn/slick/util/xml/ObjectTreeParser.java#L153-L155
BotMill/fb-botmill
src/main/java/co/aurasphere/botmill/fb/model/outcoming/factory/ButtonFactory.java
ButtonFactory.createUrlButton
public static Button createUrlButton(String title, String url, WebViewHeightRatioType ratioType) { return new WebUrlButton(title, url, ratioType); }
java
public static Button createUrlButton(String title, String url, WebViewHeightRatioType ratioType) { return new WebUrlButton(title, url, ratioType); }
[ "public", "static", "Button", "createUrlButton", "(", "String", "title", ",", "String", "url", ",", "WebViewHeightRatioType", "ratioType", ")", "{", "return", "new", "WebUrlButton", "(", "title", ",", "url", ",", "ratioType", ")", ";", "}" ]
Creates a web view button. @param title the button label. @param url the URL to whom redirect when clicked. @param ratioType the web view ratio type. @return the button
[ "Creates", "a", "web", "view", "button", "." ]
train
https://github.com/BotMill/fb-botmill/blob/d94da3615a7339822c137ef75c92a03d791ee969/src/main/java/co/aurasphere/botmill/fb/model/outcoming/factory/ButtonFactory.java#L88-L91
alibaba/jstorm
jstorm-hdfs/src/main/java/com/alibaba/jstorm/hdfs/spout/FileLock.java
FileLock.getLastEntry
public static LogEntry getLastEntry(FileSystem fs, Path lockFile) throws IOException { FSDataInputStream in = fs.open(lockFile); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String lastLine = null; for(String line = reader.readLine(); line!=null; line = reader.readLine() ) { lastLine=line; } return LogEntry.deserialize(lastLine); }
java
public static LogEntry getLastEntry(FileSystem fs, Path lockFile) throws IOException { FSDataInputStream in = fs.open(lockFile); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String lastLine = null; for(String line = reader.readLine(); line!=null; line = reader.readLine() ) { lastLine=line; } return LogEntry.deserialize(lastLine); }
[ "public", "static", "LogEntry", "getLastEntry", "(", "FileSystem", "fs", ",", "Path", "lockFile", ")", "throws", "IOException", "{", "FSDataInputStream", "in", "=", "fs", ".", "open", "(", "lockFile", ")", ";", "BufferedReader", "reader", "=", "new", "Buffered...
returns the last log entry @param fs @param lockFile @return @throws IOException
[ "returns", "the", "last", "log", "entry" ]
train
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-hdfs/src/main/java/com/alibaba/jstorm/hdfs/spout/FileLock.java#L171-L180
alkacon/opencms-core
src/org/opencms/ade/containerpage/CmsContainerpageService.java
CmsContainerpageService.getLockInfo
private String getLockInfo(CmsResource resource) throws CmsException { CmsObject cms = getCmsObject(); CmsResourceUtil resourceUtil = new CmsResourceUtil(cms, resource); CmsLock lock = resourceUtil.getLock(); String lockInfo = null; if (!lock.isLockableBy(cms.getRequestContext().getCurrentUser())) { if (lock.getType() == CmsLockType.PUBLISH) { lockInfo = Messages.get().getBundle(OpenCms.getWorkplaceManager().getWorkplaceLocale(cms)).key( Messages.GUI_LOCKED_FOR_PUBLISH_0); } else { CmsUser lockOwner = cms.readUser(lock.getUserId()); lockInfo = Messages.get().getBundle(OpenCms.getWorkplaceManager().getWorkplaceLocale(cms)).key( Messages.GUI_LOCKED_BY_1, lockOwner.getFullName()); } } return lockInfo; }
java
private String getLockInfo(CmsResource resource) throws CmsException { CmsObject cms = getCmsObject(); CmsResourceUtil resourceUtil = new CmsResourceUtil(cms, resource); CmsLock lock = resourceUtil.getLock(); String lockInfo = null; if (!lock.isLockableBy(cms.getRequestContext().getCurrentUser())) { if (lock.getType() == CmsLockType.PUBLISH) { lockInfo = Messages.get().getBundle(OpenCms.getWorkplaceManager().getWorkplaceLocale(cms)).key( Messages.GUI_LOCKED_FOR_PUBLISH_0); } else { CmsUser lockOwner = cms.readUser(lock.getUserId()); lockInfo = Messages.get().getBundle(OpenCms.getWorkplaceManager().getWorkplaceLocale(cms)).key( Messages.GUI_LOCKED_BY_1, lockOwner.getFullName()); } } return lockInfo; }
[ "private", "String", "getLockInfo", "(", "CmsResource", "resource", ")", "throws", "CmsException", "{", "CmsObject", "cms", "=", "getCmsObject", "(", ")", ";", "CmsResourceUtil", "resourceUtil", "=", "new", "CmsResourceUtil", "(", "cms", ",", "resource", ")", ";...
Returns the lock information to the given resource.<p> @param resource the resource @return lock information, if the page is locked by another user @throws CmsException if something goes wrong reading the lock owner user
[ "Returns", "the", "lock", "information", "to", "the", "given", "resource", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/containerpage/CmsContainerpageService.java#L2514-L2532
dadoonet/spring-elasticsearch
src/main/java/fr/pilato/spring/elasticsearch/type/TypeElasticsearchUpdater.java
TypeElasticsearchUpdater.createTypeWithMappingInElasticsearch
private static void createTypeWithMappingInElasticsearch(RestHighLevelClient client, String index, String mapping) throws Exception { logger.trace("createTypeWithMappingInElasticsearch([{}])", index); assert client != null; assert index != null; if (mapping != null) { // Create mapping client.indices().putMapping(new PutMappingRequest(index).source(mapping, XContentType.JSON), RequestOptions.DEFAULT); } else { logger.trace("no content given for mapping. Ignoring mapping creation in index [{}].", index); } logger.trace("/createTypeWithMappingInElasticsearch([{}])", index); }
java
private static void createTypeWithMappingInElasticsearch(RestHighLevelClient client, String index, String mapping) throws Exception { logger.trace("createTypeWithMappingInElasticsearch([{}])", index); assert client != null; assert index != null; if (mapping != null) { // Create mapping client.indices().putMapping(new PutMappingRequest(index).source(mapping, XContentType.JSON), RequestOptions.DEFAULT); } else { logger.trace("no content given for mapping. Ignoring mapping creation in index [{}].", index); } logger.trace("/createTypeWithMappingInElasticsearch([{}])", index); }
[ "private", "static", "void", "createTypeWithMappingInElasticsearch", "(", "RestHighLevelClient", "client", ",", "String", "index", ",", "String", "mapping", ")", "throws", "Exception", "{", "logger", ".", "trace", "(", "\"createTypeWithMappingInElasticsearch([{}])\"", ","...
Create a new type in Elasticsearch @param client Elasticsearch client @param index Index name @param mapping Mapping if any, null if no specific mapping @throws Exception if the elasticsearch call is failing
[ "Create", "a", "new", "type", "in", "Elasticsearch" ]
train
https://github.com/dadoonet/spring-elasticsearch/blob/b338223818a5bdf5d9c06c88cb98589c843fd293/src/main/java/fr/pilato/spring/elasticsearch/type/TypeElasticsearchUpdater.java#L109-L124
apache/flink
flink-connectors/flink-connector-kafka-0.11/src/main/java/org/apache/flink/streaming/connectors/kafka/internal/FlinkKafkaProducer.java
FlinkKafkaProducer.resumeTransaction
public void resumeTransaction(long producerId, short epoch) { Preconditions.checkState(producerId >= 0 && epoch >= 0, "Incorrect values for producerId {} and epoch {}", producerId, epoch); LOG.info("Attempting to resume transaction {} with producerId {} and epoch {}", transactionalId, producerId, epoch); Object transactionManager = getValue(kafkaProducer, "transactionManager"); synchronized (transactionManager) { Object sequenceNumbers = getValue(transactionManager, "sequenceNumbers"); invoke(transactionManager, "transitionTo", getEnum("org.apache.kafka.clients.producer.internals.TransactionManager$State.INITIALIZING")); invoke(sequenceNumbers, "clear"); Object producerIdAndEpoch = getValue(transactionManager, "producerIdAndEpoch"); setValue(producerIdAndEpoch, "producerId", producerId); setValue(producerIdAndEpoch, "epoch", epoch); invoke(transactionManager, "transitionTo", getEnum("org.apache.kafka.clients.producer.internals.TransactionManager$State.READY")); invoke(transactionManager, "transitionTo", getEnum("org.apache.kafka.clients.producer.internals.TransactionManager$State.IN_TRANSACTION")); setValue(transactionManager, "transactionStarted", true); } }
java
public void resumeTransaction(long producerId, short epoch) { Preconditions.checkState(producerId >= 0 && epoch >= 0, "Incorrect values for producerId {} and epoch {}", producerId, epoch); LOG.info("Attempting to resume transaction {} with producerId {} and epoch {}", transactionalId, producerId, epoch); Object transactionManager = getValue(kafkaProducer, "transactionManager"); synchronized (transactionManager) { Object sequenceNumbers = getValue(transactionManager, "sequenceNumbers"); invoke(transactionManager, "transitionTo", getEnum("org.apache.kafka.clients.producer.internals.TransactionManager$State.INITIALIZING")); invoke(sequenceNumbers, "clear"); Object producerIdAndEpoch = getValue(transactionManager, "producerIdAndEpoch"); setValue(producerIdAndEpoch, "producerId", producerId); setValue(producerIdAndEpoch, "epoch", epoch); invoke(transactionManager, "transitionTo", getEnum("org.apache.kafka.clients.producer.internals.TransactionManager$State.READY")); invoke(transactionManager, "transitionTo", getEnum("org.apache.kafka.clients.producer.internals.TransactionManager$State.IN_TRANSACTION")); setValue(transactionManager, "transactionStarted", true); } }
[ "public", "void", "resumeTransaction", "(", "long", "producerId", ",", "short", "epoch", ")", "{", "Preconditions", ".", "checkState", "(", "producerId", ">=", "0", "&&", "epoch", ">=", "0", ",", "\"Incorrect values for producerId {} and epoch {}\"", ",", "producerI...
Instead of obtaining producerId and epoch from the transaction coordinator, re-use previously obtained ones, so that we can resume transaction after a restart. Implementation of this method is based on {@link org.apache.kafka.clients.producer.KafkaProducer#initTransactions}.
[ "Instead", "of", "obtaining", "producerId", "and", "epoch", "from", "the", "transaction", "coordinator", "re", "-", "use", "previously", "obtained", "ones", "so", "that", "we", "can", "resume", "transaction", "after", "a", "restart", ".", "Implementation", "of",...
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-connectors/flink-connector-kafka-0.11/src/main/java/org/apache/flink/streaming/connectors/kafka/internal/FlinkKafkaProducer.java#L191-L211
OpenLiberty/open-liberty
dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ejs/container/EJSContainer.java
EJSContainer.addBean
public BeanO addBean(BeanO beanO, ContainerTx containerTx) throws DuplicateKeyException, RemoteException { return activator.addBean(containerTx, beanO); }
java
public BeanO addBean(BeanO beanO, ContainerTx containerTx) throws DuplicateKeyException, RemoteException { return activator.addBean(containerTx, beanO); }
[ "public", "BeanO", "addBean", "(", "BeanO", "beanO", ",", "ContainerTx", "containerTx", ")", "throws", "DuplicateKeyException", ",", "RemoteException", "{", "return", "activator", ".", "addBean", "(", "containerTx", ",", "beanO", ")", ";", "}" ]
Add the bean associated with the given <code>BeanO</code> to this container in the context of the given transaction. <p> If a bean with the same identity already exists in this container within the same transaction context then the bean is not added and the <code>BeanO</code> associated with the existing bean is returned. In this case, the caller may retry the add. <p> @param beanO the <code>BeanO</code> to add to this container <p> @param containerTx the <code>ContainerTx</code> to add BeanO in <p> @return the <code>BeanO</code>, if any, that prevented bean from being added to this container; null if bean successfully added <p>
[ "Add", "the", "bean", "associated", "with", "the", "given", "<code", ">", "BeanO<", "/", "code", ">", "to", "this", "container", "in", "the", "context", "of", "the", "given", "transaction", ".", "<p", ">" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ejs/container/EJSContainer.java#L1777-L1779
googlegenomics/utils-java
src/main/java/com/google/cloud/genomics/utils/grpc/GenomicsChannel.java
GenomicsChannel.fromCreds
public static ManagedChannel fromCreds(GoogleCredentials creds, String fields) throws SSLException { List<ClientInterceptor> interceptors = new ArrayList(); interceptors.add(new ClientAuthInterceptor(creds.createScoped(Arrays.asList(GENOMICS_SCOPE)), Executors.newSingleThreadExecutor())); if (!Strings.isNullOrEmpty(fields)) { Metadata headers = new Metadata(); Metadata.Key<String> partialResponseHeader = Metadata.Key.of(PARTIAL_RESPONSE_HEADER, Metadata.ASCII_STRING_MARSHALLER); headers.put(partialResponseHeader, fields); interceptors.add(MetadataUtils.newAttachHeadersInterceptor(headers)); } return getGenomicsManagedChannel(interceptors); }
java
public static ManagedChannel fromCreds(GoogleCredentials creds, String fields) throws SSLException { List<ClientInterceptor> interceptors = new ArrayList(); interceptors.add(new ClientAuthInterceptor(creds.createScoped(Arrays.asList(GENOMICS_SCOPE)), Executors.newSingleThreadExecutor())); if (!Strings.isNullOrEmpty(fields)) { Metadata headers = new Metadata(); Metadata.Key<String> partialResponseHeader = Metadata.Key.of(PARTIAL_RESPONSE_HEADER, Metadata.ASCII_STRING_MARSHALLER); headers.put(partialResponseHeader, fields); interceptors.add(MetadataUtils.newAttachHeadersInterceptor(headers)); } return getGenomicsManagedChannel(interceptors); }
[ "public", "static", "ManagedChannel", "fromCreds", "(", "GoogleCredentials", "creds", ",", "String", "fields", ")", "throws", "SSLException", "{", "List", "<", "ClientInterceptor", ">", "interceptors", "=", "new", "ArrayList", "(", ")", ";", "interceptors", ".", ...
Create a new gRPC channel to the Google Genomics API, using the provided credentials for auth. @param creds The credential. @param fields Which fields to return in the partial response, or null for none. @return The ManagedChannel. @throws SSLException
[ "Create", "a", "new", "gRPC", "channel", "to", "the", "Google", "Genomics", "API", "using", "the", "provided", "credentials", "for", "auth", "." ]
train
https://github.com/googlegenomics/utils-java/blob/7205d5b4e4f61fc6b93acb4bdd76b93df5b5f612/src/main/java/com/google/cloud/genomics/utils/grpc/GenomicsChannel.java#L74-L86
apache/groovy
src/main/java/org/codehaus/groovy/syntax/CSTNode.java
CSTNode.matches
boolean matches(int type, int child1, int child2) { return matches(type, child1) && get(2, true).isA(child2); }
java
boolean matches(int type, int child1, int child2) { return matches(type, child1) && get(2, true).isA(child2); }
[ "boolean", "matches", "(", "int", "type", ",", "int", "child1", ",", "int", "child2", ")", "{", "return", "matches", "(", "type", ",", "child1", ")", "&&", "get", "(", "2", ",", "true", ")", ".", "isA", "(", "child2", ")", ";", "}" ]
Returns true if the node and it's first and second child match the specified types. Missing nodes are Token.NULL.
[ "Returns", "true", "if", "the", "node", "and", "it", "s", "first", "and", "second", "child", "match", "the", "specified", "types", ".", "Missing", "nodes", "are", "Token", ".", "NULL", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/syntax/CSTNode.java#L149-L151
joniles/mpxj
src/main/java/net/sf/mpxj/ProjectCalendar.java
ProjectCalendar.populateExpandedExceptions
private void populateExpandedExceptions() { if (!m_exceptions.isEmpty() && m_expandedExceptions.isEmpty()) { for (ProjectCalendarException exception : m_exceptions) { RecurringData recurring = exception.getRecurring(); if (recurring == null) { m_expandedExceptions.add(exception); } else { for (Date date : recurring.getDates()) { Date startDate = DateHelper.getDayStartDate(date); Date endDate = DateHelper.getDayEndDate(date); ProjectCalendarException newException = new ProjectCalendarException(startDate, endDate); int rangeCount = exception.getRangeCount(); for (int rangeIndex = 0; rangeIndex < rangeCount; rangeIndex++) { newException.addRange(exception.getRange(rangeIndex)); } m_expandedExceptions.add(newException); } } } Collections.sort(m_expandedExceptions); } }
java
private void populateExpandedExceptions() { if (!m_exceptions.isEmpty() && m_expandedExceptions.isEmpty()) { for (ProjectCalendarException exception : m_exceptions) { RecurringData recurring = exception.getRecurring(); if (recurring == null) { m_expandedExceptions.add(exception); } else { for (Date date : recurring.getDates()) { Date startDate = DateHelper.getDayStartDate(date); Date endDate = DateHelper.getDayEndDate(date); ProjectCalendarException newException = new ProjectCalendarException(startDate, endDate); int rangeCount = exception.getRangeCount(); for (int rangeIndex = 0; rangeIndex < rangeCount; rangeIndex++) { newException.addRange(exception.getRange(rangeIndex)); } m_expandedExceptions.add(newException); } } } Collections.sort(m_expandedExceptions); } }
[ "private", "void", "populateExpandedExceptions", "(", ")", "{", "if", "(", "!", "m_exceptions", ".", "isEmpty", "(", ")", "&&", "m_expandedExceptions", ".", "isEmpty", "(", ")", ")", "{", "for", "(", "ProjectCalendarException", "exception", ":", "m_exceptions", ...
Populate the expanded exceptions list based on the main exceptions list. Where we find recurring exception definitions, we generate individual exceptions for each recurrence to ensure that we account for them correctly.
[ "Populate", "the", "expanded", "exceptions", "list", "based", "on", "the", "main", "exceptions", "list", ".", "Where", "we", "find", "recurring", "exception", "definitions", "we", "generate", "individual", "exceptions", "for", "each", "recurrence", "to", "ensure",...
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/ProjectCalendar.java#L1929-L1958
looly/hutool
hutool-extra/src/main/java/cn/hutool/extra/ssh/Sftp.java
Sftp.init
public void init(String sshHost, int sshPort, String sshUser, String sshPass, Charset charset) { this.host = sshHost; this.port = sshPort; this.user = sshUser; this.password = sshPass; init(JschUtil.getSession(sshHost, sshPort, sshUser, sshPass), charset); }
java
public void init(String sshHost, int sshPort, String sshUser, String sshPass, Charset charset) { this.host = sshHost; this.port = sshPort; this.user = sshUser; this.password = sshPass; init(JschUtil.getSession(sshHost, sshPort, sshUser, sshPass), charset); }
[ "public", "void", "init", "(", "String", "sshHost", ",", "int", "sshPort", ",", "String", "sshUser", ",", "String", "sshPass", ",", "Charset", "charset", ")", "{", "this", ".", "host", "=", "sshHost", ";", "this", ".", "port", "=", "sshPort", ";", "thi...
构造 @param sshHost 远程主机 @param sshPort 远程主机端口 @param sshUser 远程主机用户名 @param sshPass 远程主机密码 @param charset 编码
[ "构造" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-extra/src/main/java/cn/hutool/extra/ssh/Sftp.java#L106-L112
apache/flink
flink-yarn/src/main/java/org/apache/flink/yarn/highavailability/YarnHighAvailabilityServices.java
YarnHighAvailabilityServices.forSingleJobAppMaster
public static YarnHighAvailabilityServices forSingleJobAppMaster( Configuration flinkConfig, org.apache.hadoop.conf.Configuration hadoopConfig) throws IOException { checkNotNull(flinkConfig, "flinkConfig"); checkNotNull(hadoopConfig, "hadoopConfig"); final HighAvailabilityMode mode = HighAvailabilityMode.fromConfig(flinkConfig); switch (mode) { case NONE: return new YarnIntraNonHaMasterServices(flinkConfig, hadoopConfig); case ZOOKEEPER: throw new UnsupportedOperationException("to be implemented"); default: throw new IllegalConfigurationException("Unrecognized high availability mode: " + mode); } }
java
public static YarnHighAvailabilityServices forSingleJobAppMaster( Configuration flinkConfig, org.apache.hadoop.conf.Configuration hadoopConfig) throws IOException { checkNotNull(flinkConfig, "flinkConfig"); checkNotNull(hadoopConfig, "hadoopConfig"); final HighAvailabilityMode mode = HighAvailabilityMode.fromConfig(flinkConfig); switch (mode) { case NONE: return new YarnIntraNonHaMasterServices(flinkConfig, hadoopConfig); case ZOOKEEPER: throw new UnsupportedOperationException("to be implemented"); default: throw new IllegalConfigurationException("Unrecognized high availability mode: " + mode); } }
[ "public", "static", "YarnHighAvailabilityServices", "forSingleJobAppMaster", "(", "Configuration", "flinkConfig", ",", "org", ".", "apache", ".", "hadoop", ".", "conf", ".", "Configuration", "hadoopConfig", ")", "throws", "IOException", "{", "checkNotNull", "(", "flin...
Creates the high-availability services for a single-job Flink YARN application, to be used in the Application Master that runs both ResourceManager and JobManager. @param flinkConfig The Flink configuration. @param hadoopConfig The Hadoop configuration for the YARN cluster. @return The created high-availability services. @throws IOException Thrown, if the high-availability services could not be initialized.
[ "Creates", "the", "high", "-", "availability", "services", "for", "a", "single", "-", "job", "Flink", "YARN", "application", "to", "be", "used", "in", "the", "Application", "Master", "that", "runs", "both", "ResourceManager", "and", "JobManager", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-yarn/src/main/java/org/apache/flink/yarn/highavailability/YarnHighAvailabilityServices.java#L318-L336
liferay/com-liferay-commerce
commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceOrderNotePersistenceImpl.java
CommerceOrderNotePersistenceImpl.removeByC_R
@Override public void removeByC_R(long commerceOrderId, boolean restricted) { for (CommerceOrderNote commerceOrderNote : findByC_R(commerceOrderId, restricted, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) { remove(commerceOrderNote); } }
java
@Override public void removeByC_R(long commerceOrderId, boolean restricted) { for (CommerceOrderNote commerceOrderNote : findByC_R(commerceOrderId, restricted, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) { remove(commerceOrderNote); } }
[ "@", "Override", "public", "void", "removeByC_R", "(", "long", "commerceOrderId", ",", "boolean", "restricted", ")", "{", "for", "(", "CommerceOrderNote", "commerceOrderNote", ":", "findByC_R", "(", "commerceOrderId", ",", "restricted", ",", "QueryUtil", ".", "ALL...
Removes all the commerce order notes where commerceOrderId = &#63; and restricted = &#63; from the database. @param commerceOrderId the commerce order ID @param restricted the restricted
[ "Removes", "all", "the", "commerce", "order", "notes", "where", "commerceOrderId", "=", "&#63", ";", "and", "restricted", "=", "&#63", ";", "from", "the", "database", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceOrderNotePersistenceImpl.java#L1102-L1108
Azure/azure-sdk-for-java
keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java
KeyVaultClientBaseImpl.updateStorageAccount
public StorageBundle updateStorageAccount(String vaultBaseUrl, String storageAccountName) { return updateStorageAccountWithServiceResponseAsync(vaultBaseUrl, storageAccountName).toBlocking().single().body(); }
java
public StorageBundle updateStorageAccount(String vaultBaseUrl, String storageAccountName) { return updateStorageAccountWithServiceResponseAsync(vaultBaseUrl, storageAccountName).toBlocking().single().body(); }
[ "public", "StorageBundle", "updateStorageAccount", "(", "String", "vaultBaseUrl", ",", "String", "storageAccountName", ")", "{", "return", "updateStorageAccountWithServiceResponseAsync", "(", "vaultBaseUrl", ",", "storageAccountName", ")", ".", "toBlocking", "(", ")", "."...
Updates the specified attributes associated with the given storage account. This operation requires the storage/set/update permission. @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. @param storageAccountName The name of the storage account. @throws IllegalArgumentException thrown if parameters fail the validation @throws KeyVaultErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the StorageBundle object if successful.
[ "Updates", "the", "specified", "attributes", "associated", "with", "the", "given", "storage", "account", ".", "This", "operation", "requires", "the", "storage", "/", "set", "/", "update", "permission", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java#L10093-L10095
matthewhorridge/owlapi-gwt
owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLObjectComplementOfImpl_CustomFieldSerializer.java
OWLObjectComplementOfImpl_CustomFieldSerializer.serializeInstance
@Override public void serializeInstance(SerializationStreamWriter streamWriter, OWLObjectComplementOfImpl instance) throws SerializationException { serialize(streamWriter, instance); }
java
@Override public void serializeInstance(SerializationStreamWriter streamWriter, OWLObjectComplementOfImpl instance) throws SerializationException { serialize(streamWriter, instance); }
[ "@", "Override", "public", "void", "serializeInstance", "(", "SerializationStreamWriter", "streamWriter", ",", "OWLObjectComplementOfImpl", "instance", ")", "throws", "SerializationException", "{", "serialize", "(", "streamWriter", ",", "instance", ")", ";", "}" ]
Serializes the content of the object into the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter}. @param streamWriter the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter} to write the object's content to @param instance the object instance to serialize @throws com.google.gwt.user.client.rpc.SerializationException if the serialization operation is not successful
[ "Serializes", "the", "content", "of", "the", "object", "into", "the", "{", "@link", "com", ".", "google", ".", "gwt", ".", "user", ".", "client", ".", "rpc", ".", "SerializationStreamWriter", "}", "." ]
train
https://github.com/matthewhorridge/owlapi-gwt/blob/7ab975fb6cef3c8947099983551672a3b5d4e2fd/owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLObjectComplementOfImpl_CustomFieldSerializer.java#L69-L72
zxing/zxing
core/src/main/java/com/google/zxing/qrcode/encoder/MatrixUtil.java
MatrixUtil.maybeEmbedVersionInfo
static void maybeEmbedVersionInfo(Version version, ByteMatrix matrix) throws WriterException { if (version.getVersionNumber() < 7) { // Version info is necessary if version >= 7. return; // Don't need version info. } BitArray versionInfoBits = new BitArray(); makeVersionInfoBits(version, versionInfoBits); int bitIndex = 6 * 3 - 1; // It will decrease from 17 to 0. for (int i = 0; i < 6; ++i) { for (int j = 0; j < 3; ++j) { // Place bits in LSB (least significant bit) to MSB order. boolean bit = versionInfoBits.get(bitIndex); bitIndex--; // Left bottom corner. matrix.set(i, matrix.getHeight() - 11 + j, bit); // Right bottom corner. matrix.set(matrix.getHeight() - 11 + j, i, bit); } } }
java
static void maybeEmbedVersionInfo(Version version, ByteMatrix matrix) throws WriterException { if (version.getVersionNumber() < 7) { // Version info is necessary if version >= 7. return; // Don't need version info. } BitArray versionInfoBits = new BitArray(); makeVersionInfoBits(version, versionInfoBits); int bitIndex = 6 * 3 - 1; // It will decrease from 17 to 0. for (int i = 0; i < 6; ++i) { for (int j = 0; j < 3; ++j) { // Place bits in LSB (least significant bit) to MSB order. boolean bit = versionInfoBits.get(bitIndex); bitIndex--; // Left bottom corner. matrix.set(i, matrix.getHeight() - 11 + j, bit); // Right bottom corner. matrix.set(matrix.getHeight() - 11 + j, i, bit); } } }
[ "static", "void", "maybeEmbedVersionInfo", "(", "Version", "version", ",", "ByteMatrix", "matrix", ")", "throws", "WriterException", "{", "if", "(", "version", ".", "getVersionNumber", "(", ")", "<", "7", ")", "{", "// Version info is necessary if version >= 7.", "r...
See 8.10 of JISX0510:2004 (p.47) for how to embed version information.
[ "See", "8", ".", "10", "of", "JISX0510", ":", "2004", "(", "p", ".", "47", ")", "for", "how", "to", "embed", "version", "information", "." ]
train
https://github.com/zxing/zxing/blob/653ac2a3beb11481eff82e7d5f2bab8a745f7fac/core/src/main/java/com/google/zxing/qrcode/encoder/MatrixUtil.java#L198-L217
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/base64/Base64.java
Base64.decodeToFile
public static void decodeToFile (@Nonnull final String sDataToDecode, @Nonnull final File aFile) throws IOException { try (final Base64OutputStream bos = new Base64OutputStream (FileHelper.getBufferedOutputStream (aFile), DECODE)) { bos.write (sDataToDecode.getBytes (PREFERRED_ENCODING)); } }
java
public static void decodeToFile (@Nonnull final String sDataToDecode, @Nonnull final File aFile) throws IOException { try (final Base64OutputStream bos = new Base64OutputStream (FileHelper.getBufferedOutputStream (aFile), DECODE)) { bos.write (sDataToDecode.getBytes (PREFERRED_ENCODING)); } }
[ "public", "static", "void", "decodeToFile", "(", "@", "Nonnull", "final", "String", "sDataToDecode", ",", "@", "Nonnull", "final", "File", "aFile", ")", "throws", "IOException", "{", "try", "(", "final", "Base64OutputStream", "bos", "=", "new", "Base64OutputStre...
Convenience method for decoding data to a file. <p> As of v 2.3, if there is a error, the method will throw an IOException. <b>This is new to v2.3!</b> In earlier versions, it just returned false, but in retrospect that's a pretty poor way to handle it. </p> @param sDataToDecode Base64-encoded data as a string @param aFile File for saving decoded data @throws IOException if there is an error @since 2.1
[ "Convenience", "method", "for", "decoding", "data", "to", "a", "file", ".", "<p", ">", "As", "of", "v", "2", ".", "3", "if", "there", "is", "a", "error", "the", "method", "will", "throw", "an", "IOException", ".", "<b", ">", "This", "is", "new", "t...
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/base64/Base64.java#L2390-L2396
dhemery/hartley
src/main/java/com/dhemery/expressing/ImmediateExpressions.java
ImmediateExpressions.assertThat
public static <V> void assertThat(Sampler<V> variable, Matcher<? super V> criteria) { assertThat(sampleOf(variable, criteria)); }
java
public static <V> void assertThat(Sampler<V> variable, Matcher<? super V> criteria) { assertThat(sampleOf(variable, criteria)); }
[ "public", "static", "<", "V", ">", "void", "assertThat", "(", "Sampler", "<", "V", ">", "variable", ",", "Matcher", "<", "?", "super", "V", ">", "criteria", ")", "{", "assertThat", "(", "sampleOf", "(", "variable", ",", "criteria", ")", ")", ";", "}"...
Assert that a sample of the variable satisfies the criteria. <p>Example:</p> <pre> {@code Sampler<Integer> threadCount = ...; ... assertThat(threadCount, is(9)); }
[ "Assert", "that", "a", "sample", "of", "the", "variable", "satisfies", "the", "criteria", ".", "<p", ">", "Example", ":", "<", "/", "p", ">", "<pre", ">", "{", "@code" ]
train
https://github.com/dhemery/hartley/blob/7754bd6bc12695f2249601b8890da530a61fcf33/src/main/java/com/dhemery/expressing/ImmediateExpressions.java#L48-L50
avianey/facebook-api-android-maven
facebook/src/main/java/com/facebook/widget/LoginButton.java
LoginButton.onActivityResult
public boolean onActivityResult(int requestCode, int resultCode, Intent data) { Session session = sessionTracker.getSession(); if (session != null) { return session.onActivityResult((Activity)getContext(), requestCode, resultCode, data); } else { return false; } }
java
public boolean onActivityResult(int requestCode, int resultCode, Intent data) { Session session = sessionTracker.getSession(); if (session != null) { return session.onActivityResult((Activity)getContext(), requestCode, resultCode, data); } else { return false; } }
[ "public", "boolean", "onActivityResult", "(", "int", "requestCode", ",", "int", "resultCode", ",", "Intent", "data", ")", "{", "Session", "session", "=", "sessionTracker", ".", "getSession", "(", ")", ";", "if", "(", "session", "!=", "null", ")", "{", "ret...
Provides an implementation for {@link Activity#onActivityResult onActivityResult} that updates the Session based on information returned during the authorization flow. The Activity containing this view should forward the resulting onActivityResult call here to update the Session state based on the contents of the resultCode and data. @param requestCode The requestCode parameter from the forwarded call. When this onActivityResult occurs as part of Facebook authorization flow, this value is the activityCode passed to open or authorize. @param resultCode An int containing the resultCode parameter from the forwarded call. @param data The Intent passed as the data parameter from the forwarded call. @return A boolean indicating whether the requestCode matched a pending authorization request for this Session. @see Session#onActivityResult(Activity, int, int, Intent)
[ "Provides", "an", "implementation", "for", "{", "@link", "Activity#onActivityResult", "onActivityResult", "}", "that", "updates", "the", "Session", "based", "on", "information", "returned", "during", "the", "authorization", "flow", ".", "The", "Activity", "containing"...
train
https://github.com/avianey/facebook-api-android-maven/blob/ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede/facebook/src/main/java/com/facebook/widget/LoginButton.java#L579-L587
exoplatform/jcr
exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/SessionDataManager.java
SessionDataManager.getItem
public ItemImpl getItem(QPath path, boolean pool) throws RepositoryException { long start = 0; if (LOG.isDebugEnabled()) { start = System.currentTimeMillis(); LOG.debug("getItem(" + path.getAsString() + " ) >>>>>"); } ItemImpl item = null; try { return item = readItem(getItemData(path), pool); } finally { if (LOG.isDebugEnabled()) { LOG.debug("getItem(" + path.getAsString() + ") --> " + (item != null ? item.getPath() : "null") + " <<<<< " + ((System.currentTimeMillis() - start) / 1000d) + "sec"); } } }
java
public ItemImpl getItem(QPath path, boolean pool) throws RepositoryException { long start = 0; if (LOG.isDebugEnabled()) { start = System.currentTimeMillis(); LOG.debug("getItem(" + path.getAsString() + " ) >>>>>"); } ItemImpl item = null; try { return item = readItem(getItemData(path), pool); } finally { if (LOG.isDebugEnabled()) { LOG.debug("getItem(" + path.getAsString() + ") --> " + (item != null ? item.getPath() : "null") + " <<<<< " + ((System.currentTimeMillis() - start) / 1000d) + "sec"); } } }
[ "public", "ItemImpl", "getItem", "(", "QPath", "path", ",", "boolean", "pool", ")", "throws", "RepositoryException", "{", "long", "start", "=", "0", ";", "if", "(", "LOG", ".", "isDebugEnabled", "(", ")", ")", "{", "start", "=", "System", ".", "currentTi...
Return item by absolute path in this transient storage then in workspace container. @param path - absolute path to the searched item @param pool - indicates does the item fall in pool @return existed item or null if not found @throws RepositoryException
[ "Return", "item", "by", "absolute", "path", "in", "this", "transient", "storage", "then", "in", "workspace", "container", "." ]
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/SessionDataManager.java#L546-L568
j256/ormlite-core
src/main/java/com/j256/ormlite/field/FieldType.java
FieldType.findForeignFieldType
private FieldType findForeignFieldType(Class<?> clazz, Class<?> foreignClass, Dao<?, ?> foreignDao) throws SQLException { String foreignColumnName = fieldConfig.getForeignCollectionForeignFieldName(); for (FieldType fieldType : foreignDao.getTableInfo().getFieldTypes()) { if (fieldType.getType() == foreignClass && (foreignColumnName == null || fieldType.getField().getName().equals(foreignColumnName))) { if (!fieldType.fieldConfig.isForeign() && !fieldType.fieldConfig.isForeignAutoRefresh()) { // this may never be reached throw new SQLException("Foreign collection object " + clazz + " for field '" + field.getName() + "' contains a field of class " + foreignClass + " but it's not foreign"); } return fieldType; } } // build our complex error message StringBuilder sb = new StringBuilder(); sb.append("Foreign collection class ").append(clazz.getName()); sb.append(" for field '").append(field.getName()).append("' column-name does not contain a foreign field"); if (foreignColumnName != null) { sb.append(" named '").append(foreignColumnName).append('\''); } sb.append(" of class ").append(foreignClass.getName()); throw new SQLException(sb.toString()); }
java
private FieldType findForeignFieldType(Class<?> clazz, Class<?> foreignClass, Dao<?, ?> foreignDao) throws SQLException { String foreignColumnName = fieldConfig.getForeignCollectionForeignFieldName(); for (FieldType fieldType : foreignDao.getTableInfo().getFieldTypes()) { if (fieldType.getType() == foreignClass && (foreignColumnName == null || fieldType.getField().getName().equals(foreignColumnName))) { if (!fieldType.fieldConfig.isForeign() && !fieldType.fieldConfig.isForeignAutoRefresh()) { // this may never be reached throw new SQLException("Foreign collection object " + clazz + " for field '" + field.getName() + "' contains a field of class " + foreignClass + " but it's not foreign"); } return fieldType; } } // build our complex error message StringBuilder sb = new StringBuilder(); sb.append("Foreign collection class ").append(clazz.getName()); sb.append(" for field '").append(field.getName()).append("' column-name does not contain a foreign field"); if (foreignColumnName != null) { sb.append(" named '").append(foreignColumnName).append('\''); } sb.append(" of class ").append(foreignClass.getName()); throw new SQLException(sb.toString()); }
[ "private", "FieldType", "findForeignFieldType", "(", "Class", "<", "?", ">", "clazz", ",", "Class", "<", "?", ">", "foreignClass", ",", "Dao", "<", "?", ",", "?", ">", "foreignDao", ")", "throws", "SQLException", "{", "String", "foreignColumnName", "=", "f...
If we have a class Foo with a collection of Bar's then we go through Bar's DAO looking for a Foo field. We need this field to build the query that is able to find all Bar's that have foo_id that matches our id.
[ "If", "we", "have", "a", "class", "Foo", "with", "a", "collection", "of", "Bar", "s", "then", "we", "go", "through", "Bar", "s", "DAO", "looking", "for", "a", "Foo", "field", ".", "We", "need", "this", "field", "to", "build", "the", "query", "that", ...
train
https://github.com/j256/ormlite-core/blob/154d85bbb9614a0ea65a012251257831fb4fba21/src/main/java/com/j256/ormlite/field/FieldType.java#L1109-L1132
m-m-m/util
value/src/main/java/net/sf/mmm/util/value/impl/AbstractValueConverterToContainer.java
AbstractValueConverterToContainer.convertFromArray
protected <T extends CONTAINER> T convertFromArray(Object arrayValue, Object valueSource, GenericType<T> targetType) { int len = Array.getLength(arrayValue); T container = createContainer(targetType, len); for (int i = 0; i < len; i++) { Object element = Array.get(arrayValue, i); convertContainerEntry(element, i, container, valueSource, targetType, arrayValue); } return container; }
java
protected <T extends CONTAINER> T convertFromArray(Object arrayValue, Object valueSource, GenericType<T> targetType) { int len = Array.getLength(arrayValue); T container = createContainer(targetType, len); for (int i = 0; i < len; i++) { Object element = Array.get(arrayValue, i); convertContainerEntry(element, i, container, valueSource, targetType, arrayValue); } return container; }
[ "protected", "<", "T", "extends", "CONTAINER", ">", "T", "convertFromArray", "(", "Object", "arrayValue", ",", "Object", "valueSource", ",", "GenericType", "<", "T", ">", "targetType", ")", "{", "int", "len", "=", "Array", ".", "getLength", "(", "arrayValue"...
This method performs the {@link #convert(Object, Object, GenericType) conversion} for array values. @param <T> is the generic type of {@code targetType}. @param arrayValue is the array value to convert. @param valueSource describes the source of the value or {@code null} if NOT available. @param targetType is the {@link #getTargetType() target-type} to convert to. @return the converted container.
[ "This", "method", "performs", "the", "{", "@link", "#convert", "(", "Object", "Object", "GenericType", ")", "conversion", "}", "for", "array", "values", "." ]
train
https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/value/src/main/java/net/sf/mmm/util/value/impl/AbstractValueConverterToContainer.java#L222-L231
albfernandez/itext2
src/main/java/com/lowagie/text/pdf/CFFFontSubset.java
CFFFontSubset.CalcBias
protected int CalcBias(int Offset,int Font) { seek(Offset); int nSubrs = getCard16(); // If type==1 -> bias=0 if (fonts[Font].CharstringType == 1) return 0; // else calc according to the count else if (nSubrs < 1240) return 107; else if (nSubrs < 33900) return 1131; else return 32768; }
java
protected int CalcBias(int Offset,int Font) { seek(Offset); int nSubrs = getCard16(); // If type==1 -> bias=0 if (fonts[Font].CharstringType == 1) return 0; // else calc according to the count else if (nSubrs < 1240) return 107; else if (nSubrs < 33900) return 1131; else return 32768; }
[ "protected", "int", "CalcBias", "(", "int", "Offset", ",", "int", "Font", ")", "{", "seek", "(", "Offset", ")", ";", "int", "nSubrs", "=", "getCard16", "(", ")", ";", "// If type==1 -> bias=0 ", "if", "(", "fonts", "[", "Font", "]", ".", "CharstringType"...
Function calcs bias according to the CharString type and the count of the subrs @param Offset The offset to the relevant subrs index @param Font the font @return The calculated Bias
[ "Function", "calcs", "bias", "according", "to", "the", "CharString", "type", "and", "the", "count", "of", "the", "subrs" ]
train
https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/CFFFontSubset.java#L403-L417
MorphiaOrg/morphia
morphia/src/main/java/dev/morphia/Morphia.java
Morphia.fromDBObject
public <T> T fromDBObject(final Datastore datastore, final Class<T> entityClass, final DBObject dbObject) { return fromDBObject(datastore, entityClass, dbObject, mapper.createEntityCache()); }
java
public <T> T fromDBObject(final Datastore datastore, final Class<T> entityClass, final DBObject dbObject) { return fromDBObject(datastore, entityClass, dbObject, mapper.createEntityCache()); }
[ "public", "<", "T", ">", "T", "fromDBObject", "(", "final", "Datastore", "datastore", ",", "final", "Class", "<", "T", ">", "entityClass", ",", "final", "DBObject", "dbObject", ")", "{", "return", "fromDBObject", "(", "datastore", ",", "entityClass", ",", ...
Creates an entity and populates its state based on the dbObject given. This method is primarily an internal method. Reliance on this method may break your application in future releases. @param <T> type of the entity @param datastore the Datastore to use when fetching this reference @param entityClass type to create @param dbObject the object state to use @return the newly created and populated entity
[ "Creates", "an", "entity", "and", "populates", "its", "state", "based", "on", "the", "dbObject", "given", ".", "This", "method", "is", "primarily", "an", "internal", "method", ".", "Reliance", "on", "this", "method", "may", "break", "your", "application", "i...
train
https://github.com/MorphiaOrg/morphia/blob/667c30bdc7c6f1d9f2e2eb8774835d6137b52d12/morphia/src/main/java/dev/morphia/Morphia.java#L116-L118
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/models/sequencevectors/listeners/SerializingListener.java
SerializingListener.validateEvent
@Override public boolean validateEvent(ListenerEvent event, long argument) { try { /** * please note, since sequence vectors are multithreaded we need to stop processed while model is being saved */ locker.acquire(); if (event == targetEvent && argument % targetFrequency == 0) { return true; } else return false; } catch (Exception e) { throw new RuntimeException(e); } finally { locker.release(); } }
java
@Override public boolean validateEvent(ListenerEvent event, long argument) { try { /** * please note, since sequence vectors are multithreaded we need to stop processed while model is being saved */ locker.acquire(); if (event == targetEvent && argument % targetFrequency == 0) { return true; } else return false; } catch (Exception e) { throw new RuntimeException(e); } finally { locker.release(); } }
[ "@", "Override", "public", "boolean", "validateEvent", "(", "ListenerEvent", "event", ",", "long", "argument", ")", "{", "try", "{", "/**\n * please note, since sequence vectors are multithreaded we need to stop processed while model is being saved\n */", "loc...
This method is called prior each processEvent call, to check if this specific VectorsListener implementation is viable for specific event @param event @param argument @return TRUE, if this event can and should be processed with this listener, FALSE otherwise
[ "This", "method", "is", "called", "prior", "each", "processEvent", "call", "to", "check", "if", "this", "specific", "VectorsListener", "implementation", "is", "viable", "for", "specific", "event" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/models/sequencevectors/listeners/SerializingListener.java#L55-L72
BotMill/fb-botmill
src/main/java/co/aurasphere/botmill/fb/model/outcoming/factory/AirlineItineraryTemplateBuilder.java
AirlineItineraryTemplateBuilder.addPassengerInfo
public AirlineItineraryTemplateBuilder addPassengerInfo(String passengerId, String name) { PassengerInfo passengerInfo = new PassengerInfo(passengerId, name); this.payload.addPassengerInfo(passengerInfo); return this; }
java
public AirlineItineraryTemplateBuilder addPassengerInfo(String passengerId, String name) { PassengerInfo passengerInfo = new PassengerInfo(passengerId, name); this.payload.addPassengerInfo(passengerInfo); return this; }
[ "public", "AirlineItineraryTemplateBuilder", "addPassengerInfo", "(", "String", "passengerId", ",", "String", "name", ")", "{", "PassengerInfo", "passengerInfo", "=", "new", "PassengerInfo", "(", "passengerId", ",", "name", ")", ";", "this", ".", "payload", ".", "...
Adds a {@link PassengerInfo} object to this template. This field is mandatory for this template. There must be at least one element. @param passengerId the passenger ID. It can't be empty. @param name the passenger name. It can't be empty. @return this builder.
[ "Adds", "a", "{", "@link", "PassengerInfo", "}", "object", "to", "this", "template", ".", "This", "field", "is", "mandatory", "for", "this", "template", ".", "There", "must", "be", "at", "least", "one", "element", "." ]
train
https://github.com/BotMill/fb-botmill/blob/d94da3615a7339822c137ef75c92a03d791ee969/src/main/java/co/aurasphere/botmill/fb/model/outcoming/factory/AirlineItineraryTemplateBuilder.java#L148-L153
alkacon/opencms-core
src-gwt/org/opencms/ade/sitemap/client/alias/simple/CmsAliasErrorColumn.java
CmsAliasErrorColumn.getComparator
public static Comparator<CmsAliasTableRow> getComparator() { return new Comparator<CmsAliasTableRow>() { public int compare(CmsAliasTableRow o1, CmsAliasTableRow o2) { String err1 = getValueInternal(o1); String err2 = getValueInternal(o2); if ((err1 == null) && (err2 == null)) { return 0; } if (err1 == null) { return -1; } if (err2 == null) { return 1; } return 0; } }; }
java
public static Comparator<CmsAliasTableRow> getComparator() { return new Comparator<CmsAliasTableRow>() { public int compare(CmsAliasTableRow o1, CmsAliasTableRow o2) { String err1 = getValueInternal(o1); String err2 = getValueInternal(o2); if ((err1 == null) && (err2 == null)) { return 0; } if (err1 == null) { return -1; } if (err2 == null) { return 1; } return 0; } }; }
[ "public", "static", "Comparator", "<", "CmsAliasTableRow", ">", "getComparator", "(", ")", "{", "return", "new", "Comparator", "<", "CmsAliasTableRow", ">", "(", ")", "{", "public", "int", "compare", "(", "CmsAliasTableRow", "o1", ",", "CmsAliasTableRow", "o2", ...
Gets the comparator which should be used for this column.<p> @return the comparator used for this column
[ "Gets", "the", "comparator", "which", "should", "be", "used", "for", "this", "column", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/sitemap/client/alias/simple/CmsAliasErrorColumn.java#L62-L82
apereo/cas
core/cas-server-core-services-api/src/main/java/org/apereo/cas/authentication/principal/ShibbolethCompatiblePersistentIdGenerator.java
ShibbolethCompatiblePersistentIdGenerator.prepareMessageDigest
protected static MessageDigest prepareMessageDigest(final String principal, final String service) throws NoSuchAlgorithmException { val md = MessageDigest.getInstance("SHA"); if (StringUtils.isNotBlank(service)) { md.update(service.getBytes(StandardCharsets.UTF_8)); md.update(CONST_SEPARATOR); } md.update(principal.getBytes(StandardCharsets.UTF_8)); md.update(CONST_SEPARATOR); return md; }
java
protected static MessageDigest prepareMessageDigest(final String principal, final String service) throws NoSuchAlgorithmException { val md = MessageDigest.getInstance("SHA"); if (StringUtils.isNotBlank(service)) { md.update(service.getBytes(StandardCharsets.UTF_8)); md.update(CONST_SEPARATOR); } md.update(principal.getBytes(StandardCharsets.UTF_8)); md.update(CONST_SEPARATOR); return md; }
[ "protected", "static", "MessageDigest", "prepareMessageDigest", "(", "final", "String", "principal", ",", "final", "String", "service", ")", "throws", "NoSuchAlgorithmException", "{", "val", "md", "=", "MessageDigest", ".", "getInstance", "(", "\"SHA\"", ")", ";", ...
Prepare message digest message digest. @param principal the principal @param service the service @return the message digest @throws NoSuchAlgorithmException the no such algorithm exception
[ "Prepare", "message", "digest", "message", "digest", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/core/cas-server-core-services-api/src/main/java/org/apereo/cas/authentication/principal/ShibbolethCompatiblePersistentIdGenerator.java#L126-L135
landawn/AbacusUtil
src/com/landawn/abacus/util/Matth.java
Matth.addExact
public static int addExact(int a, int b) { long result = (long) a + b; checkNoOverflow(result == (int) result); return (int) result; }
java
public static int addExact(int a, int b) { long result = (long) a + b; checkNoOverflow(result == (int) result); return (int) result; }
[ "public", "static", "int", "addExact", "(", "int", "a", ",", "int", "b", ")", "{", "long", "result", "=", "(", "long", ")", "a", "+", "b", ";", "checkNoOverflow", "(", "result", "==", "(", "int", ")", "result", ")", ";", "return", "(", "int", ")"...
Returns the sum of {@code a} and {@code b}, provided it does not overflow. @throws ArithmeticException if {@code a + b} overflows in signed {@code int} arithmetic
[ "Returns", "the", "sum", "of", "{", "@code", "a", "}", "and", "{", "@code", "b", "}", "provided", "it", "does", "not", "overflow", "." ]
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/Matth.java#L1371-L1375
apiman/apiman
manager/api/beans/src/main/java/io/apiman/manager/api/beans/audit/data/EntityUpdatedData.java
EntityUpdatedData.addChange
public void addChange(String name, Enum<?> before, Enum<?> after) { String beforeStr = before != null ? before.name() : null; String afterStr = after != null ? after.name() : null; addChange(name, beforeStr, afterStr); }
java
public void addChange(String name, Enum<?> before, Enum<?> after) { String beforeStr = before != null ? before.name() : null; String afterStr = after != null ? after.name() : null; addChange(name, beforeStr, afterStr); }
[ "public", "void", "addChange", "(", "String", "name", ",", "Enum", "<", "?", ">", "before", ",", "Enum", "<", "?", ">", "after", ")", "{", "String", "beforeStr", "=", "before", "!=", "null", "?", "before", ".", "name", "(", ")", ":", "null", ";", ...
Adds a single change. @param name the name @param before the before state @param after the after state
[ "Adds", "a", "single", "change", "." ]
train
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/beans/src/main/java/io/apiman/manager/api/beans/audit/data/EntityUpdatedData.java#L56-L60
alkacon/opencms-core
src/org/opencms/db/generic/CmsUserDriver.java
CmsUserDriver.internalValidateUserInGroup
protected boolean internalValidateUserInGroup(CmsDbContext dbc, CmsUUID userId, CmsUUID groupId) throws CmsDataAccessException { boolean userInGroup = false; PreparedStatement stmt = null; ResultSet res = null; Connection conn = null; try { conn = getSqlManager().getConnection(dbc); stmt = m_sqlManager.getPreparedStatement(conn, "C_GROUPS_USER_IN_GROUP_2"); stmt.setString(1, groupId.toString()); stmt.setString(2, userId.toString()); res = stmt.executeQuery(); if (res.next()) { userInGroup = true; while (res.next()) { // do nothing only move through all rows because of mssql odbc driver } } } catch (SQLException e) { throw new CmsDbSqlException( Messages.get().container(Messages.ERR_GENERIC_SQL_1, CmsDbSqlException.getErrorQuery(stmt)), e); } finally { m_sqlManager.closeAll(dbc, conn, stmt, res); } return userInGroup; }
java
protected boolean internalValidateUserInGroup(CmsDbContext dbc, CmsUUID userId, CmsUUID groupId) throws CmsDataAccessException { boolean userInGroup = false; PreparedStatement stmt = null; ResultSet res = null; Connection conn = null; try { conn = getSqlManager().getConnection(dbc); stmt = m_sqlManager.getPreparedStatement(conn, "C_GROUPS_USER_IN_GROUP_2"); stmt.setString(1, groupId.toString()); stmt.setString(2, userId.toString()); res = stmt.executeQuery(); if (res.next()) { userInGroup = true; while (res.next()) { // do nothing only move through all rows because of mssql odbc driver } } } catch (SQLException e) { throw new CmsDbSqlException( Messages.get().container(Messages.ERR_GENERIC_SQL_1, CmsDbSqlException.getErrorQuery(stmt)), e); } finally { m_sqlManager.closeAll(dbc, conn, stmt, res); } return userInGroup; }
[ "protected", "boolean", "internalValidateUserInGroup", "(", "CmsDbContext", "dbc", ",", "CmsUUID", "userId", ",", "CmsUUID", "groupId", ")", "throws", "CmsDataAccessException", "{", "boolean", "userInGroup", "=", "false", ";", "PreparedStatement", "stmt", "=", "null",...
Checks if a user is member of a group.<p> @param dbc the database context @param userId the id of the user to check @param groupId the id of the group to check @return true if user is member of group @throws CmsDataAccessException if operation was not succesful
[ "Checks", "if", "a", "user", "is", "member", "of", "a", "group", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/generic/CmsUserDriver.java#L2883-L2913
Azure/azure-sdk-for-java
automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/SchedulesInner.java
SchedulesInner.updateAsync
public Observable<ScheduleInner> updateAsync(String resourceGroupName, String automationAccountName, String scheduleName, ScheduleUpdateParameters parameters) { return updateWithServiceResponseAsync(resourceGroupName, automationAccountName, scheduleName, parameters).map(new Func1<ServiceResponse<ScheduleInner>, ScheduleInner>() { @Override public ScheduleInner call(ServiceResponse<ScheduleInner> response) { return response.body(); } }); }
java
public Observable<ScheduleInner> updateAsync(String resourceGroupName, String automationAccountName, String scheduleName, ScheduleUpdateParameters parameters) { return updateWithServiceResponseAsync(resourceGroupName, automationAccountName, scheduleName, parameters).map(new Func1<ServiceResponse<ScheduleInner>, ScheduleInner>() { @Override public ScheduleInner call(ServiceResponse<ScheduleInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "ScheduleInner", ">", "updateAsync", "(", "String", "resourceGroupName", ",", "String", "automationAccountName", ",", "String", "scheduleName", ",", "ScheduleUpdateParameters", "parameters", ")", "{", "return", "updateWithServiceResponseAsync", ...
Update the schedule identified by schedule name. @param resourceGroupName Name of an Azure Resource group. @param automationAccountName The name of the automation account. @param scheduleName The schedule name. @param parameters The parameters supplied to the update schedule operation. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the ScheduleInner object
[ "Update", "the", "schedule", "identified", "by", "schedule", "name", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/SchedulesInner.java#L234-L241
DiUS/pact-jvm
pact-jvm-consumer-java8/src/main/java/io/pactfoundation/consumer/dsl/LambdaDslObject.java
LambdaDslObject.eachKeyLike
public LambdaDslObject eachKeyLike(String exampleKey, Consumer<LambdaDslObject> nestedObject) { final PactDslJsonBody objectLike = object.eachKeyLike(exampleKey); final LambdaDslObject dslObject = new LambdaDslObject(objectLike); nestedObject.accept(dslObject); objectLike.closeObject(); return this; }
java
public LambdaDslObject eachKeyLike(String exampleKey, Consumer<LambdaDslObject> nestedObject) { final PactDslJsonBody objectLike = object.eachKeyLike(exampleKey); final LambdaDslObject dslObject = new LambdaDslObject(objectLike); nestedObject.accept(dslObject); objectLike.closeObject(); return this; }
[ "public", "LambdaDslObject", "eachKeyLike", "(", "String", "exampleKey", ",", "Consumer", "<", "LambdaDslObject", ">", "nestedObject", ")", "{", "final", "PactDslJsonBody", "objectLike", "=", "object", ".", "eachKeyLike", "(", "exampleKey", ")", ";", "final", "Lam...
Accepts any key, and each key is mapped to a map that must match the following object definition. Note: this needs the Java system property "pact.matching.wildcard" set to value "true" when the pact file is verified. @param exampleKey Example key to use for generating bodies
[ "Accepts", "any", "key", "and", "each", "key", "is", "mapped", "to", "a", "map", "that", "must", "match", "the", "following", "object", "definition", ".", "Note", ":", "this", "needs", "the", "Java", "system", "property", "pact", ".", "matching", ".", "w...
train
https://github.com/DiUS/pact-jvm/blob/2f447e9dd4ac152a6a36b7fcf8962d07de9ef3ef/pact-jvm-consumer-java8/src/main/java/io/pactfoundation/consumer/dsl/LambdaDslObject.java#L665-L671
jbundle/jbundle
base/base/src/main/java/org/jbundle/base/field/event/MainReadOnlyHandler.java
MainReadOnlyHandler.init
public void init(BaseField field, String keyName) { super.init(field, keyName); m_bReadOnly = true; }
java
public void init(BaseField field, String keyName) { super.init(field, keyName); m_bReadOnly = true; }
[ "public", "void", "init", "(", "BaseField", "field", ",", "String", "keyName", ")", "{", "super", ".", "init", "(", "field", ",", "keyName", ")", ";", "m_bReadOnly", "=", "true", ";", "}" ]
Constructor. @param field The basefield owner of this listener (usually null and set on setOwner()). @param iKeySeq The key area to read.
[ "Constructor", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/field/event/MainReadOnlyHandler.java#L47-L52
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/file/meta/InodeTreePersistentState.java
InodeTreePersistentState.applyAndJournal
public void applyAndJournal(Supplier<JournalContext> context, UpdateInodeDirectoryEntry entry) { try { applyUpdateInodeDirectory(entry); context.get().append(JournalEntry.newBuilder().setUpdateInodeDirectory(entry).build()); } catch (Throwable t) { ProcessUtils.fatalError(LOG, t, "Failed to apply %s", entry); throw t; // fatalError will usually system.exit } }
java
public void applyAndJournal(Supplier<JournalContext> context, UpdateInodeDirectoryEntry entry) { try { applyUpdateInodeDirectory(entry); context.get().append(JournalEntry.newBuilder().setUpdateInodeDirectory(entry).build()); } catch (Throwable t) { ProcessUtils.fatalError(LOG, t, "Failed to apply %s", entry); throw t; // fatalError will usually system.exit } }
[ "public", "void", "applyAndJournal", "(", "Supplier", "<", "JournalContext", ">", "context", ",", "UpdateInodeDirectoryEntry", "entry", ")", "{", "try", "{", "applyUpdateInodeDirectory", "(", "entry", ")", ";", "context", ".", "get", "(", ")", ".", "append", "...
Updates an inode directory's state. @param context journal context supplier @param entry update inode directory entry
[ "Updates", "an", "inode", "directory", "s", "state", "." ]
train
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/file/meta/InodeTreePersistentState.java#L250-L258
spring-projects/spring-boot
spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelector.java
AutoConfigurationImportSelector.getAutoConfigurationEntry
protected AutoConfigurationEntry getAutoConfigurationEntry( AutoConfigurationMetadata autoConfigurationMetadata, AnnotationMetadata annotationMetadata) { if (!isEnabled(annotationMetadata)) { return EMPTY_ENTRY; } AnnotationAttributes attributes = getAttributes(annotationMetadata); List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes); configurations = removeDuplicates(configurations); Set<String> exclusions = getExclusions(annotationMetadata, attributes); checkExcludedClasses(configurations, exclusions); configurations.removeAll(exclusions); configurations = filter(configurations, autoConfigurationMetadata); fireAutoConfigurationImportEvents(configurations, exclusions); return new AutoConfigurationEntry(configurations, exclusions); }
java
protected AutoConfigurationEntry getAutoConfigurationEntry( AutoConfigurationMetadata autoConfigurationMetadata, AnnotationMetadata annotationMetadata) { if (!isEnabled(annotationMetadata)) { return EMPTY_ENTRY; } AnnotationAttributes attributes = getAttributes(annotationMetadata); List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes); configurations = removeDuplicates(configurations); Set<String> exclusions = getExclusions(annotationMetadata, attributes); checkExcludedClasses(configurations, exclusions); configurations.removeAll(exclusions); configurations = filter(configurations, autoConfigurationMetadata); fireAutoConfigurationImportEvents(configurations, exclusions); return new AutoConfigurationEntry(configurations, exclusions); }
[ "protected", "AutoConfigurationEntry", "getAutoConfigurationEntry", "(", "AutoConfigurationMetadata", "autoConfigurationMetadata", ",", "AnnotationMetadata", "annotationMetadata", ")", "{", "if", "(", "!", "isEnabled", "(", "annotationMetadata", ")", ")", "{", "return", "EM...
Return the {@link AutoConfigurationEntry} based on the {@link AnnotationMetadata} of the importing {@link Configuration @Configuration} class. @param autoConfigurationMetadata the auto-configuration metadata @param annotationMetadata the annotation metadata of the configuration class @return the auto-configurations that should be imported
[ "Return", "the", "{" ]
train
https://github.com/spring-projects/spring-boot/blob/0b27f7c70e164b2b1a96477f1d9c1acba56790c1/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelector.java#L112-L128
eclipse/xtext-lib
org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/CharacterExtensions.java
CharacterExtensions.operator_plus
@Pure @Inline(value="($1 + $2)", constantExpression=true) public static int operator_plus(char a, char b) { return a + b; }
java
@Pure @Inline(value="($1 + $2)", constantExpression=true) public static int operator_plus(char a, char b) { return a + b; }
[ "@", "Pure", "@", "Inline", "(", "value", "=", "\"($1 + $2)\"", ",", "constantExpression", "=", "true", ")", "public", "static", "int", "operator_plus", "(", "char", "a", ",", "char", "b", ")", "{", "return", "a", "+", "b", ";", "}" ]
The binary <code>plus</code> operator. This is the equivalent to the Java <code>+</code> operator. @param a a character. @param b a character. @return <code>a+b</code> @since 2.3
[ "The", "binary", "<code", ">", "plus<", "/", "code", ">", "operator", ".", "This", "is", "the", "equivalent", "to", "the", "Java", "<code", ">", "+", "<", "/", "code", ">", "operator", "." ]
train
https://github.com/eclipse/xtext-lib/blob/7063572e1f1bd713a3aa53bdf3a8dc60e25c169a/org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/CharacterExtensions.java#L881-L885
alkacon/opencms-core
src-setup/org/opencms/setup/CmsSetupBean.java
CmsSetupBean.sortModules
public List<String> sortModules(Collection<CmsModule> modules) { List<CmsModule> aux = new ArrayList<CmsModule>(modules); Collections.sort(aux, new Comparator<CmsModule>() { public int compare(CmsModule module1, CmsModule module2) { return getDisplayForModule(module1).compareTo(getDisplayForModule(module2)); } }); List<String> ret = new ArrayList<String>(aux.size()); for (Iterator<CmsModule> it = aux.iterator(); it.hasNext();) { CmsModule module = it.next(); ret.add(module.getName()); } return ret; }
java
public List<String> sortModules(Collection<CmsModule> modules) { List<CmsModule> aux = new ArrayList<CmsModule>(modules); Collections.sort(aux, new Comparator<CmsModule>() { public int compare(CmsModule module1, CmsModule module2) { return getDisplayForModule(module1).compareTo(getDisplayForModule(module2)); } }); List<String> ret = new ArrayList<String>(aux.size()); for (Iterator<CmsModule> it = aux.iterator(); it.hasNext();) { CmsModule module = it.next(); ret.add(module.getName()); } return ret; }
[ "public", "List", "<", "String", ">", "sortModules", "(", "Collection", "<", "CmsModule", ">", "modules", ")", "{", "List", "<", "CmsModule", ">", "aux", "=", "new", "ArrayList", "<", "CmsModule", ">", "(", "modules", ")", ";", "Collections", ".", "sort"...
Sorts the modules for display.<p> @param modules the list of {@link CmsModule} objects @return a sorted list of module names
[ "Sorts", "the", "modules", "for", "display", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-setup/org/opencms/setup/CmsSetupBean.java#L2307-L2324
looly/hutool
hutool-db/src/main/java/cn/hutool/db/handler/HandleHelper.java
HandleHelper.handleRow
public static Entity handleRow(int columnCount, ResultSetMetaData meta, ResultSet rs) throws SQLException { return handleRow(Entity.create(), columnCount, meta, rs, true); }
java
public static Entity handleRow(int columnCount, ResultSetMetaData meta, ResultSet rs) throws SQLException { return handleRow(Entity.create(), columnCount, meta, rs, true); }
[ "public", "static", "Entity", "handleRow", "(", "int", "columnCount", ",", "ResultSetMetaData", "meta", ",", "ResultSet", "rs", ")", "throws", "SQLException", "{", "return", "handleRow", "(", "Entity", ".", "create", "(", ")", ",", "columnCount", ",", "meta", ...
处理单条数据 @param columnCount 列数 @param meta ResultSetMetaData @param rs 数据集 @return 每一行的Entity @throws SQLException SQL执行异常
[ "处理单条数据" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-db/src/main/java/cn/hutool/db/handler/HandleHelper.java#L111-L113
orbisgis/h2gis
h2gis-functions/src/main/java/org/h2gis/functions/spatial/topology/ST_Graph.java
ST_Graph.createGraph
public static boolean createGraph(Connection connection, String tableName) throws SQLException { return createGraph(connection, tableName, null); }
java
public static boolean createGraph(Connection connection, String tableName) throws SQLException { return createGraph(connection, tableName, null); }
[ "public", "static", "boolean", "createGraph", "(", "Connection", "connection", ",", "String", "tableName", ")", "throws", "SQLException", "{", "return", "createGraph", "(", "connection", ",", "tableName", ",", "null", ")", ";", "}" ]
Create the nodes and edges tables from the input table containing LINESTRINGs. <p/> Since no column is specified in this signature, we take the first geometry column we find. <p/> If the input table has name 'input', then the output tables are named 'input_nodes' and 'input_edges'. @param connection Connection @param tableName Input table containing LINESTRINGs @return true if both output tables were created @throws SQLException
[ "Create", "the", "nodes", "and", "edges", "tables", "from", "the", "input", "table", "containing", "LINESTRINGs", ".", "<p", "/", ">", "Since", "no", "column", "is", "specified", "in", "this", "signature", "we", "take", "the", "first", "geometry", "column", ...
train
https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/spatial/topology/ST_Graph.java#L105-L108
twitter/hraven
hraven-etl/src/main/java/com/twitter/hraven/mapreduce/JobFileTableMapper.java
JobFileTableMapper.loadCostProperties
Properties loadCostProperties(Path cachePath, String machineType) { Properties prop = new Properties(); InputStream inp = null; try { inp = new FileInputStream(cachePath.toString()); prop.load(inp); return prop; } catch (FileNotFoundException fnf) { LOG.error("cost properties does not exist, using default values"); return null; } catch (IOException e) { LOG.error("error loading properties, using default values"); return null; } finally { if (inp != null) { try { inp.close(); } catch (IOException ignore) { // do nothing } } } }
java
Properties loadCostProperties(Path cachePath, String machineType) { Properties prop = new Properties(); InputStream inp = null; try { inp = new FileInputStream(cachePath.toString()); prop.load(inp); return prop; } catch (FileNotFoundException fnf) { LOG.error("cost properties does not exist, using default values"); return null; } catch (IOException e) { LOG.error("error loading properties, using default values"); return null; } finally { if (inp != null) { try { inp.close(); } catch (IOException ignore) { // do nothing } } } }
[ "Properties", "loadCostProperties", "(", "Path", "cachePath", ",", "String", "machineType", ")", "{", "Properties", "prop", "=", "new", "Properties", "(", ")", ";", "InputStream", "inp", "=", "null", ";", "try", "{", "inp", "=", "new", "FileInputStream", "("...
looks for cost file in distributed cache @param cachePath of the cost properties file @param machineType of the node the job ran on @throws IOException
[ "looks", "for", "cost", "file", "in", "distributed", "cache" ]
train
https://github.com/twitter/hraven/blob/e35996b6e2f016bcd18db0bad320be7c93d95208/hraven-etl/src/main/java/com/twitter/hraven/mapreduce/JobFileTableMapper.java#L444-L466
alkacon/opencms-core
src-gwt/org/opencms/acacia/client/CmsValidationHandler.java
CmsValidationHandler.addHandler
protected <H extends EventHandler> HandlerRegistration addHandler(final H handler, GwtEvent.Type<H> type) { return ensureHandlers().addHandlerToSource(type, this, handler); }
java
protected <H extends EventHandler> HandlerRegistration addHandler(final H handler, GwtEvent.Type<H> type) { return ensureHandlers().addHandlerToSource(type, this, handler); }
[ "protected", "<", "H", "extends", "EventHandler", ">", "HandlerRegistration", "addHandler", "(", "final", "H", "handler", ",", "GwtEvent", ".", "Type", "<", "H", ">", "type", ")", "{", "return", "ensureHandlers", "(", ")", ".", "addHandlerToSource", "(", "ty...
Adds this handler to the widget. @param <H> the type of handler to add @param type the event type @param handler the handler @return {@link HandlerRegistration} used to remove the handler
[ "Adds", "this", "handler", "to", "the", "widget", "." ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/acacia/client/CmsValidationHandler.java#L308-L311
jbundle/jbundle
thin/base/message/src/main/java/org/jbundle/thin/base/message/BaseMessageFilter.java
BaseMessageFilter.init
public void init(String strQueueName, String strQueueType, Object source, Map<String,Object> properties) { m_messageReceiver = null; m_vListenerList = null; m_bCreateRemoteFilter = true; m_bUpdateRemoteFilter = true; m_bThinTarget = false; super.init(strQueueName, strQueueType, source, properties); }
java
public void init(String strQueueName, String strQueueType, Object source, Map<String,Object> properties) { m_messageReceiver = null; m_vListenerList = null; m_bCreateRemoteFilter = true; m_bUpdateRemoteFilter = true; m_bThinTarget = false; super.init(strQueueName, strQueueType, source, properties); }
[ "public", "void", "init", "(", "String", "strQueueName", ",", "String", "strQueueType", ",", "Object", "source", ",", "Map", "<", "String", ",", "Object", ">", "properties", ")", "{", "m_messageReceiver", "=", "null", ";", "m_vListenerList", "=", "null", ";"...
Constructor. @param strQueueName Name of the queue. @param strQueueType Type of queue - remote or local. @param source usually the object sending or listening for the message, to reduce echos.
[ "Constructor", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/thin/base/message/src/main/java/org/jbundle/thin/base/message/BaseMessageFilter.java#L112-L120
nextreports/nextreports-engine
src/ro/nextreports/engine/util/ReportUtil.java
ReportUtil.readAsString
public static String readAsString(InputStream is) throws IOException { try { // Scanner iterates over tokens in the stream, and in this case // we separate tokens using "beginning of the input boundary" (\A) // thus giving us only one token for the entire contents of the // stream return new Scanner(is, "UTF-8").useDelimiter("\\A").next(); } catch (java.util.NoSuchElementException e) { return ""; } }
java
public static String readAsString(InputStream is) throws IOException { try { // Scanner iterates over tokens in the stream, and in this case // we separate tokens using "beginning of the input boundary" (\A) // thus giving us only one token for the entire contents of the // stream return new Scanner(is, "UTF-8").useDelimiter("\\A").next(); } catch (java.util.NoSuchElementException e) { return ""; } }
[ "public", "static", "String", "readAsString", "(", "InputStream", "is", ")", "throws", "IOException", "{", "try", "{", "// Scanner iterates over tokens in the stream, and in this case", "// we separate tokens using \"beginning of the input boundary\" (\\A)", "// thus giving us only one...
Read data from input stream @param is input stream @return string content read from input stream @throws IOException if cannot read from input stream
[ "Read", "data", "from", "input", "stream" ]
train
https://github.com/nextreports/nextreports-engine/blob/a847575a9298b5fce63b88961190c5b83ddccc44/src/ro/nextreports/engine/util/ReportUtil.java#L487-L497
cesarferreira/AndroidQuickUtils
library/src/main/java/quickutils/core/categories/string.java
string.wordWrapToTwoLines
public static String wordWrapToTwoLines(String text, int minLength) { String wordWrapText = text != null ? text.trim() : null; if ((wordWrapText != null) && (wordWrapText.length() > minLength)) { int middle = wordWrapText.length() / 2; int leftSpaceIndex = wordWrapText.substring(0, middle).lastIndexOf(SPACE); int rightSpaceIndex = wordWrapText.indexOf(SPACE, middle); int wordWrapIndex = rightSpaceIndex; if ((leftSpaceIndex >= 0) && ((rightSpaceIndex < 0) || ((middle - leftSpaceIndex) < (rightSpaceIndex - middle)))) { wordWrapIndex = leftSpaceIndex; } if (wordWrapIndex >= 0) { wordWrapText = wordWrapText.substring(0, wordWrapIndex) + "\n" + wordWrapText.substring(wordWrapIndex + 1); } } return wordWrapText; }
java
public static String wordWrapToTwoLines(String text, int minLength) { String wordWrapText = text != null ? text.trim() : null; if ((wordWrapText != null) && (wordWrapText.length() > minLength)) { int middle = wordWrapText.length() / 2; int leftSpaceIndex = wordWrapText.substring(0, middle).lastIndexOf(SPACE); int rightSpaceIndex = wordWrapText.indexOf(SPACE, middle); int wordWrapIndex = rightSpaceIndex; if ((leftSpaceIndex >= 0) && ((rightSpaceIndex < 0) || ((middle - leftSpaceIndex) < (rightSpaceIndex - middle)))) { wordWrapIndex = leftSpaceIndex; } if (wordWrapIndex >= 0) { wordWrapText = wordWrapText.substring(0, wordWrapIndex) + "\n" + wordWrapText.substring(wordWrapIndex + 1); } } return wordWrapText; }
[ "public", "static", "String", "wordWrapToTwoLines", "(", "String", "text", ",", "int", "minLength", ")", "{", "String", "wordWrapText", "=", "text", "!=", "null", "?", "text", ".", "trim", "(", ")", ":", "null", ";", "if", "(", "(", "wordWrapText", "!=",...
This method word wrap a text to two lines if the text has multiple words and its length is greater than the specified minLength. To do the word wrap, the white space closest to the middle of the string is replaced by a "\n" character @param text A Sting, the text to word wrap to two lines. @param minLength The min text length to appy word wrap. @return The input text word wrapped to two lines or the original text.
[ "This", "method", "word", "wrap", "a", "text", "to", "two", "lines", "if", "the", "text", "has", "multiple", "words", "and", "its", "length", "is", "greater", "than", "the", "specified", "minLength", ".", "To", "do", "the", "word", "wrap", "the", "white"...
train
https://github.com/cesarferreira/AndroidQuickUtils/blob/73a91daedbb9f7be7986ea786fbc441c9e5a881c/library/src/main/java/quickutils/core/categories/string.java#L392-L410
ravendb/ravendb-jvm-client
src/main/java/net/ravendb/client/documents/subscriptions/DocumentSubscriptions.java
DocumentSubscriptions.getSubscriptionState
public SubscriptionState getSubscriptionState(String subscriptionName, String database) { if (StringUtils.isEmpty(subscriptionName)) { throw new IllegalArgumentException("SubscriptionName cannot be null"); } RequestExecutor requestExecutor = _store.getRequestExecutor(ObjectUtils.firstNonNull(database, _store.getDatabase())); GetSubscriptionStateCommand command = new GetSubscriptionStateCommand(subscriptionName); requestExecutor.execute(command); return command.getResult(); }
java
public SubscriptionState getSubscriptionState(String subscriptionName, String database) { if (StringUtils.isEmpty(subscriptionName)) { throw new IllegalArgumentException("SubscriptionName cannot be null"); } RequestExecutor requestExecutor = _store.getRequestExecutor(ObjectUtils.firstNonNull(database, _store.getDatabase())); GetSubscriptionStateCommand command = new GetSubscriptionStateCommand(subscriptionName); requestExecutor.execute(command); return command.getResult(); }
[ "public", "SubscriptionState", "getSubscriptionState", "(", "String", "subscriptionName", ",", "String", "database", ")", "{", "if", "(", "StringUtils", ".", "isEmpty", "(", "subscriptionName", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Subsc...
Returns subscription definition and it's current state @param subscriptionName Subscription name as received from the server @param database Database to use @return Subscription states
[ "Returns", "subscription", "definition", "and", "it", "s", "current", "state" ]
train
https://github.com/ravendb/ravendb-jvm-client/blob/5a45727de507b541d1571e79ddd97c7d88bee787/src/main/java/net/ravendb/client/documents/subscriptions/DocumentSubscriptions.java#L400-L410
nguillaumin/slick2d-maven
slick2d-core/src/main/java/org/newdawn/slick/command/InputProvider.java
InputProvider.bindCommand
public void bindCommand(Control control, Command command) { commands.put(control, command); if (commandState.get(command) == null) { commandState.put(command, new CommandState()); } }
java
public void bindCommand(Control control, Command command) { commands.put(control, command); if (commandState.get(command) == null) { commandState.put(command, new CommandState()); } }
[ "public", "void", "bindCommand", "(", "Control", "control", ",", "Command", "command", ")", "{", "commands", ".", "put", "(", "control", ",", "command", ")", ";", "if", "(", "commandState", ".", "get", "(", "command", ")", "==", "null", ")", "{", "comm...
Bind an command to a control. @param command The command to bind to @param control The control that is pressed/released to represent the command
[ "Bind", "an", "command", "to", "a", "control", "." ]
train
https://github.com/nguillaumin/slick2d-maven/blob/8251f88a0ed6a70e726d2468842455cd1f80893f/slick2d-core/src/main/java/org/newdawn/slick/command/InputProvider.java#L143-L149
raydac/java-binary-block-parser
jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPDslBuilder.java
JBBPDslBuilder.CustomArray
public JBBPDslBuilder CustomArray(final String type, final String name, final String sizeExpression, final String param) { final ItemCustom item = new ItemCustom(type, name, this.byteOrder); item.array = true; item.bitLenExpression = param == null ? null : assertExpressionChars(param); item.sizeExpression = assertExpressionChars(sizeExpression); this.addItem(item); return this; }
java
public JBBPDslBuilder CustomArray(final String type, final String name, final String sizeExpression, final String param) { final ItemCustom item = new ItemCustom(type, name, this.byteOrder); item.array = true; item.bitLenExpression = param == null ? null : assertExpressionChars(param); item.sizeExpression = assertExpressionChars(sizeExpression); this.addItem(item); return this; }
[ "public", "JBBPDslBuilder", "CustomArray", "(", "final", "String", "type", ",", "final", "String", "name", ",", "final", "String", "sizeExpression", ",", "final", "String", "param", ")", "{", "final", "ItemCustom", "item", "=", "new", "ItemCustom", "(", "type"...
Create named custom type array which size calculated by expression. @param type custom type, must not be null @param name name of the array, can be null for anonymous one @param sizeExpression expression to calculate array length, must not be null. @param param optional parameter for the field, can be null @return the builder instance, must not be null
[ "Create", "named", "custom", "type", "array", "which", "size", "calculated", "by", "expression", "." ]
train
https://github.com/raydac/java-binary-block-parser/blob/6d98abcab01e0c72d525ebcc9e7b694f9ce49f5b/jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPDslBuilder.java#L546-L553
VoltDB/voltdb
src/hsqldb19b3/org/hsqldb_voltpatches/lib/StringConverter.java
StringConverter.writeHexBytes
public static void writeHexBytes(byte[] o, int from, byte[] b) { int len = b.length; for (int i = 0; i < len; i++) { int c = ((int) b[i]) & 0xff; o[from++] = HEXBYTES[c >> 4 & 0xf]; o[from++] = HEXBYTES[c & 0xf]; } }
java
public static void writeHexBytes(byte[] o, int from, byte[] b) { int len = b.length; for (int i = 0; i < len; i++) { int c = ((int) b[i]) & 0xff; o[from++] = HEXBYTES[c >> 4 & 0xf]; o[from++] = HEXBYTES[c & 0xf]; } }
[ "public", "static", "void", "writeHexBytes", "(", "byte", "[", "]", "o", ",", "int", "from", ",", "byte", "[", "]", "b", ")", "{", "int", "len", "=", "b", ".", "length", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "len", ";", "i", ...
Converts a byte array into hexadecimal characters which are written as ASCII to the given output stream. @param o output array @param from offset into output array @param b input array
[ "Converts", "a", "byte", "array", "into", "hexadecimal", "characters", "which", "are", "written", "as", "ASCII", "to", "the", "given", "output", "stream", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/lib/StringConverter.java#L321-L331
finmath/finmath-lib
src/main/java6/net/finmath/functions/AnalyticFormulas.java
AnalyticFormulas.sabrNormalVolatilitySkewApproximation
public static double sabrNormalVolatilitySkewApproximation(double alpha, double beta, double rho, double nu, double displacement, double underlying, double maturity) { double sigma = sabrBerestyckiNormalVolatilityApproximation(alpha, beta, rho, nu, displacement, underlying, underlying, maturity); // Apply displacement. Displaced model is just a shift on underlying and strike. underlying += displacement; double a = alpha/Math.pow(underlying, 1-beta); double c = 1.0/24*Math.pow(a, 3)*beta*(1.0-beta); double skew = + (rho*nu/a + beta) * (1.0/2.0*sigma/underlying) - maturity*c*(3.0*rho*nu/a + beta - 2.0); // Some alternative representations // double term1dterm21 = (beta*(2-beta)*alpha*alpha*alpha)/24*Math.pow(underlying,-3.0*(1.0-beta)) * (1.0-beta); // double term1dterm22 = beta*alpha*alpha*rho*nu / 4 * Math.pow(underlying,-2.0*(1.0-beta)) * -(1.0-beta) * 0.5; // skew = + 1.0/2.0*sigma/underlying*(rho*nu/alpha * Math.pow(underlying, 1-beta) + beta) + maturity * (term1dterm21+term1dterm22); // skew = + (rho*nu/a + beta) * (1.0/2.0*sigma/underlying - maturity*3.0*c) + maturity*2.0*c*(1+beta); // skew = + (rho*nu/a + beta) * (1.0/2.0*sigma/underlying - maturity*c) - maturity*c*(2.0*rho*nu/a - 2.0); // The follwoing may be used as approximations (for beta=0 the approximation is exact). // double approximation = (rho*nu/a + beta) * (1.0/2.0*sigma/underlying); // double residual = skew - approximation; return skew; }
java
public static double sabrNormalVolatilitySkewApproximation(double alpha, double beta, double rho, double nu, double displacement, double underlying, double maturity) { double sigma = sabrBerestyckiNormalVolatilityApproximation(alpha, beta, rho, nu, displacement, underlying, underlying, maturity); // Apply displacement. Displaced model is just a shift on underlying and strike. underlying += displacement; double a = alpha/Math.pow(underlying, 1-beta); double c = 1.0/24*Math.pow(a, 3)*beta*(1.0-beta); double skew = + (rho*nu/a + beta) * (1.0/2.0*sigma/underlying) - maturity*c*(3.0*rho*nu/a + beta - 2.0); // Some alternative representations // double term1dterm21 = (beta*(2-beta)*alpha*alpha*alpha)/24*Math.pow(underlying,-3.0*(1.0-beta)) * (1.0-beta); // double term1dterm22 = beta*alpha*alpha*rho*nu / 4 * Math.pow(underlying,-2.0*(1.0-beta)) * -(1.0-beta) * 0.5; // skew = + 1.0/2.0*sigma/underlying*(rho*nu/alpha * Math.pow(underlying, 1-beta) + beta) + maturity * (term1dterm21+term1dterm22); // skew = + (rho*nu/a + beta) * (1.0/2.0*sigma/underlying - maturity*3.0*c) + maturity*2.0*c*(1+beta); // skew = + (rho*nu/a + beta) * (1.0/2.0*sigma/underlying - maturity*c) - maturity*c*(2.0*rho*nu/a - 2.0); // The follwoing may be used as approximations (for beta=0 the approximation is exact). // double approximation = (rho*nu/a + beta) * (1.0/2.0*sigma/underlying); // double residual = skew - approximation; return skew; }
[ "public", "static", "double", "sabrNormalVolatilitySkewApproximation", "(", "double", "alpha", ",", "double", "beta", ",", "double", "rho", ",", "double", "nu", ",", "double", "displacement", ",", "double", "underlying", ",", "double", "maturity", ")", "{", "dou...
Return the skew of the implied normal volatility (Bachelier volatility) under a SABR model using the approximation of Berestycki. The skew is the first derivative of the implied vol w.r.t. the strike, evaluated at the money. @param alpha initial value of the stochastic volatility process of the SABR model. @param beta CEV parameter of the SABR model. @param rho Correlation (leverages) of the stochastic volatility. @param nu Volatility of the stochastic volatility (vol-of-vol). @param displacement The displacement parameter d. @param underlying Underlying (spot) value. @param maturity Maturity. @return The skew of the implied normal volatility (Bachelier volatility)
[ "Return", "the", "skew", "of", "the", "implied", "normal", "volatility", "(", "Bachelier", "volatility", ")", "under", "a", "SABR", "model", "using", "the", "approximation", "of", "Berestycki", ".", "The", "skew", "is", "the", "first", "derivative", "of", "t...
train
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/functions/AnalyticFormulas.java#L1216-L1240