repository_name stringlengths 7 58 | func_path_in_repository stringlengths 18 188 | func_name stringlengths 7 127 | whole_func_string stringlengths 77 3.91k | language stringclasses 1
value | func_code_string stringlengths 77 3.91k | func_code_tokens listlengths 20 745 | func_documentation_string stringlengths 61 1.98k | func_documentation_tokens listlengths 1 477 | split_name stringclasses 1
value | func_code_url stringlengths 111 288 |
|---|---|---|---|---|---|---|---|---|---|---|
cdk/cdk | misc/extra/src/main/java/org/openscience/cdk/tools/AtomTypeTools.java | AtomTypeTools.getSubgraphSmiles | private static String getSubgraphSmiles(IAtomContainer subgraph, IAtomContainer molecule) throws CDKException {
Set<IBond> bonds = new HashSet<>();
for (IBond bond : subgraph.bonds())
bonds.add(bond);
Integer[] hCount = new Integer[subgraph.getAtomCount()];
for (int i = 0; i < subgraph.getAtomCount(); i++) {
final IAtom atom = subgraph.getAtom(i);
int removed = 0;
for (IBond bond : molecule.getConnectedBondsList(atom)) {
if (!bonds.contains(bond))
removed += bond.getOrder().numeric();
}
hCount[i] = atom.getImplicitHydrogenCount();
atom.setImplicitHydrogenCount(hCount[i] == null ? removed : hCount[i] + removed);
}
String smi = cansmi(subgraph);
// reset for fused rings!
for (int i = 0; i < subgraph.getAtomCount(); i++) {
subgraph.getAtom(i).setImplicitHydrogenCount(hCount[i]);
}
return smi;
} | java | private static String getSubgraphSmiles(IAtomContainer subgraph, IAtomContainer molecule) throws CDKException {
Set<IBond> bonds = new HashSet<>();
for (IBond bond : subgraph.bonds())
bonds.add(bond);
Integer[] hCount = new Integer[subgraph.getAtomCount()];
for (int i = 0; i < subgraph.getAtomCount(); i++) {
final IAtom atom = subgraph.getAtom(i);
int removed = 0;
for (IBond bond : molecule.getConnectedBondsList(atom)) {
if (!bonds.contains(bond))
removed += bond.getOrder().numeric();
}
hCount[i] = atom.getImplicitHydrogenCount();
atom.setImplicitHydrogenCount(hCount[i] == null ? removed : hCount[i] + removed);
}
String smi = cansmi(subgraph);
// reset for fused rings!
for (int i = 0; i < subgraph.getAtomCount(); i++) {
subgraph.getAtom(i).setImplicitHydrogenCount(hCount[i]);
}
return smi;
} | [
"private",
"static",
"String",
"getSubgraphSmiles",
"(",
"IAtomContainer",
"subgraph",
",",
"IAtomContainer",
"molecule",
")",
"throws",
"CDKException",
"{",
"Set",
"<",
"IBond",
">",
"bonds",
"=",
"new",
"HashSet",
"<>",
"(",
")",
";",
"for",
"(",
"IBond",
... | New SMILES code respects atom valency hence a ring subgraph of 'o1cccc1CCCC' is correctly
written as 'o1ccc[c]1' note there is no hydrogen there since it was an external attachment.
To get unique subgraph SMILES we need to adjust valencies of atoms by adding Hydrogens. We
base this on the sum of bond orders removed.
@param subgraph subgraph (atom and bond refs in 'molecule')
@param molecule the molecule
@return the canonical smiles of the subgraph
@throws CDKException something went wrong with SMILES gen | [
"New",
"SMILES",
"code",
"respects",
"atom",
"valency",
"hence",
"a",
"ring",
"subgraph",
"of",
"o1cccc1CCCC",
"is",
"correctly",
"written",
"as",
"o1ccc",
"[",
"c",
"]",
"1",
"note",
"there",
"is",
"no",
"hydrogen",
"there",
"since",
"it",
"was",
"an",
... | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/misc/extra/src/main/java/org/openscience/cdk/tools/AtomTypeTools.java#L146-L171 |
EvidentSolutions/dalesbred | dalesbred/src/main/java/org/dalesbred/Database.java | Database.updateAndProcessGeneratedKeys | public <T> T updateAndProcessGeneratedKeys(@NotNull ResultSetProcessor<T> generatedKeysProcessor, @NotNull List<String> columnNames, @NotNull SqlQuery query) {
return withCurrentTransaction(query, tx -> {
logQuery(query);
try (PreparedStatement ps = prepareStatement(tx.getConnection(), query.getSql(), columnNames)) {
prepareStatementFromQuery(ps, query);
long startTime = currentTimeMillis();
ps.executeUpdate();
logQueryExecution(query, currentTimeMillis() - startTime);
try (ResultSet rs = ps.getGeneratedKeys()) {
return generatedKeysProcessor.process(rs);
}
}
});
} | java | public <T> T updateAndProcessGeneratedKeys(@NotNull ResultSetProcessor<T> generatedKeysProcessor, @NotNull List<String> columnNames, @NotNull SqlQuery query) {
return withCurrentTransaction(query, tx -> {
logQuery(query);
try (PreparedStatement ps = prepareStatement(tx.getConnection(), query.getSql(), columnNames)) {
prepareStatementFromQuery(ps, query);
long startTime = currentTimeMillis();
ps.executeUpdate();
logQueryExecution(query, currentTimeMillis() - startTime);
try (ResultSet rs = ps.getGeneratedKeys()) {
return generatedKeysProcessor.process(rs);
}
}
});
} | [
"public",
"<",
"T",
">",
"T",
"updateAndProcessGeneratedKeys",
"(",
"@",
"NotNull",
"ResultSetProcessor",
"<",
"T",
">",
"generatedKeysProcessor",
",",
"@",
"NotNull",
"List",
"<",
"String",
">",
"columnNames",
",",
"@",
"NotNull",
"SqlQuery",
"query",
")",
"{... | Executes an update against the database and return generated keys as extracted by generatedKeysProcessor.
@param generatedKeysProcessor processor for handling the generated keys
@param columnNames names of columns that contain the generated keys. Can be empty, in which case the
returned columns depend on the database
@param query to execute
@return Result of processing the results with {@code generatedKeysProcessor}. | [
"Executes",
"an",
"update",
"against",
"the",
"database",
"and",
"return",
"generated",
"keys",
"as",
"extracted",
"by",
"generatedKeysProcessor",
"."
] | train | https://github.com/EvidentSolutions/dalesbred/blob/713f5b6e152d97e1672ca68b9ff9c7c6c288ceb1/dalesbred/src/main/java/org/dalesbred/Database.java#L650-L666 |
TheCoder4eu/BootsFaces-OSP | src/main/java/net/bootsfaces/component/container/ContainerRenderer.java | ContainerRenderer.encodeBegin | @Override
public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
if (!component.isRendered()) {
return;
}
Container container = (Container) component;
ResponseWriter rw = context.getResponseWriter();
String clientId = container.getClientId();
boolean fluid = container.isFluid();
String style = container.getStyle();
String sc = container.getStyleClass();
String c = (fluid ? "container-fluid" : "container");
if (sc != null) {
c += " " + sc;
}
rw.startElement("div", container);
rw.writeAttribute("id", clientId, "id");
String dir = container.getDir();
if (null != dir)
rw.writeAttribute("dir", dir, "dir");
Tooltip.generateTooltip(context, container, rw);
if (style != null) {
rw.writeAttribute("style", style, "style");
}
rw.writeAttribute("class", c, "class");
beginDisabledFieldset(container, rw);
} | java | @Override
public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
if (!component.isRendered()) {
return;
}
Container container = (Container) component;
ResponseWriter rw = context.getResponseWriter();
String clientId = container.getClientId();
boolean fluid = container.isFluid();
String style = container.getStyle();
String sc = container.getStyleClass();
String c = (fluid ? "container-fluid" : "container");
if (sc != null) {
c += " " + sc;
}
rw.startElement("div", container);
rw.writeAttribute("id", clientId, "id");
String dir = container.getDir();
if (null != dir)
rw.writeAttribute("dir", dir, "dir");
Tooltip.generateTooltip(context, container, rw);
if (style != null) {
rw.writeAttribute("style", style, "style");
}
rw.writeAttribute("class", c, "class");
beginDisabledFieldset(container, rw);
} | [
"@",
"Override",
"public",
"void",
"encodeBegin",
"(",
"FacesContext",
"context",
",",
"UIComponent",
"component",
")",
"throws",
"IOException",
"{",
"if",
"(",
"!",
"component",
".",
"isRendered",
"(",
")",
")",
"{",
"return",
";",
"}",
"Container",
"contai... | This methods generates the HTML code of the current b:container.
<code>encodeBegin</code> generates the start of the component. After the,
the JSF framework calls <code>encodeChildren()</code> to generate the
HTML code between the beginning and the end of the component. For
instance, in the case of a panel component the content of the panel is
generated by <code>encodeChildren()</code>. After that,
<code>encodeEnd()</code> is called to generate the rest of the HTML code.
@param context
the FacesContext.
@param component
the current b:container.
@throws IOException
thrown if something goes wrong when writing the HTML code. | [
"This",
"methods",
"generates",
"the",
"HTML",
"code",
"of",
"the",
"current",
"b",
":",
"container",
".",
"<code",
">",
"encodeBegin<",
"/",
"code",
">",
"generates",
"the",
"start",
"of",
"the",
"component",
".",
"After",
"the",
"the",
"JSF",
"framework"... | train | https://github.com/TheCoder4eu/BootsFaces-OSP/blob/d1a70952bc240979b5272fa4fe1c7f100873add0/src/main/java/net/bootsfaces/component/container/ContainerRenderer.java#L51-L81 |
nutzam/nutzwx | src/main/java/org/nutz/weixin/util/Wxs.java | Wxs.checkPayReturn | public static NutMap checkPayReturn(String xml, String key) {
try {
NutMap map = Xmls.asMap(xmls().parse(new InputSource(new StringReader(xml))).getDocumentElement());
return checkPayReturnMap(map, key);
}
catch (Exception e) {
throw Lang.makeThrow("e.wx.pay.re.error : %s", xml);
}
} | java | public static NutMap checkPayReturn(String xml, String key) {
try {
NutMap map = Xmls.asMap(xmls().parse(new InputSource(new StringReader(xml))).getDocumentElement());
return checkPayReturnMap(map, key);
}
catch (Exception e) {
throw Lang.makeThrow("e.wx.pay.re.error : %s", xml);
}
} | [
"public",
"static",
"NutMap",
"checkPayReturn",
"(",
"String",
"xml",
",",
"String",
"key",
")",
"{",
"try",
"{",
"NutMap",
"map",
"=",
"Xmls",
".",
"asMap",
"(",
"xmls",
"(",
")",
".",
"parse",
"(",
"new",
"InputSource",
"(",
"new",
"StringReader",
"(... | 检查一下支付平台返回的 xml,是否签名合法,如果合法,转换成一个 map
@param xml
支付平台返回的 xml
@param key
商户秘钥
@return 合法的 Map
@throws "e.wx.sign.invalid"
@see #checkPayReturnMap(NutMap, String)
@see <a href=
"https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1">
支付平台文档</a> | [
"检查一下支付平台返回的",
"xml,是否签名合法,如果合法,转换成一个",
"map"
] | train | https://github.com/nutzam/nutzwx/blob/e6c8831b75f8a96bcc060b0c5562b882eefcf5ee/src/main/java/org/nutz/weixin/util/Wxs.java#L155-L163 |
EdwardRaff/JSAT | JSAT/src/jsat/io/CSV.java | CSV.readC | public static ClassificationDataSet readC(int classification_target, Path path, char delimiter, int lines_to_skip, char comment, Set<Integer> cat_cols) throws IOException
{
BufferedReader br = Files.newBufferedReader(path, Charset.defaultCharset());
ClassificationDataSet ret = readC(classification_target, br, delimiter, lines_to_skip, comment, cat_cols);
br.close();
return ret;
} | java | public static ClassificationDataSet readC(int classification_target, Path path, char delimiter, int lines_to_skip, char comment, Set<Integer> cat_cols) throws IOException
{
BufferedReader br = Files.newBufferedReader(path, Charset.defaultCharset());
ClassificationDataSet ret = readC(classification_target, br, delimiter, lines_to_skip, comment, cat_cols);
br.close();
return ret;
} | [
"public",
"static",
"ClassificationDataSet",
"readC",
"(",
"int",
"classification_target",
",",
"Path",
"path",
",",
"char",
"delimiter",
",",
"int",
"lines_to_skip",
",",
"char",
"comment",
",",
"Set",
"<",
"Integer",
">",
"cat_cols",
")",
"throws",
"IOExceptio... | Reads in a CSV dataset as a classification dataset.
@param classification_target the column index (starting from zero) of the
feature that will be the categorical target value
@param path the CSV file
@param delimiter the delimiter to separate columns, usually a comma
@param lines_to_skip the number of lines to skip when reading in the CSV
(used to skip header information)
@param comment the character used to indicate the start of a comment.
Once this character is reached, anything at and after the character will
be ignored.
@param cat_cols a set of the indices to treat as categorical features.
@return the classification dataset from the given CSV file
@throws IOException | [
"Reads",
"in",
"a",
"CSV",
"dataset",
"as",
"a",
"classification",
"dataset",
"."
] | train | https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/io/CSV.java#L214-L220 |
apache/incubator-gobblin | gobblin-utility/src/main/java/org/apache/gobblin/util/ExecutorsUtils.java | ExecutorsUtils.newDaemonThreadFactory | public static ThreadFactory newDaemonThreadFactory(Optional<Logger> logger, Optional<String> nameFormat) {
return newThreadFactory(new ThreadFactoryBuilder().setDaemon(true), logger, nameFormat);
} | java | public static ThreadFactory newDaemonThreadFactory(Optional<Logger> logger, Optional<String> nameFormat) {
return newThreadFactory(new ThreadFactoryBuilder().setDaemon(true), logger, nameFormat);
} | [
"public",
"static",
"ThreadFactory",
"newDaemonThreadFactory",
"(",
"Optional",
"<",
"Logger",
">",
"logger",
",",
"Optional",
"<",
"String",
">",
"nameFormat",
")",
"{",
"return",
"newThreadFactory",
"(",
"new",
"ThreadFactoryBuilder",
"(",
")",
".",
"setDaemon",... | Get a new {@link ThreadFactory} that uses a {@link LoggingUncaughtExceptionHandler}
to handle uncaught exceptions, uses the given thread name format, and produces daemon threads.
@param logger an {@link Optional} wrapping the {@link Logger} that the
{@link LoggingUncaughtExceptionHandler} uses to log uncaught exceptions thrown in threads
@param nameFormat an {@link Optional} wrapping a thread naming format
@return a new {@link ThreadFactory} | [
"Get",
"a",
"new",
"{",
"@link",
"ThreadFactory",
"}",
"that",
"uses",
"a",
"{",
"@link",
"LoggingUncaughtExceptionHandler",
"}",
"to",
"handle",
"uncaught",
"exceptions",
"uses",
"the",
"given",
"thread",
"name",
"format",
"and",
"produces",
"daemon",
"threads"... | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/ExecutorsUtils.java#L102-L104 |
bazaarvoice/ostrich | core/src/main/java/com/bazaarvoice/ostrich/pool/SingleThreadedClientServiceCache.java | SingleThreadedClientServiceCache.checkOut | public ServiceHandle<S> checkOut(ServiceEndPoint endPoint) throws Exception {
checkNotNull(endPoint);
_requestCount.incrementAndGet();
try {
long revision = _revisionNumber.incrementAndGet();
S service = _pool.borrowObject(endPoint);
ServiceHandle<S> handle = new ServiceHandle<>(service, endPoint);
// Remember the revision that we've checked this service out on in case we need to invalidate it later
_checkedOutRevisions.put(handle, revision);
return handle;
} catch (NoSuchElementException e) {
_missCount.incrementAndGet();
// This will happen if there are no available connections and there is no room for a new one,
// or if a newly created connection is not valid.
throw new NoCachedInstancesAvailableException(String.format("No cached instances available for endpoint: %s", endPoint));
}
} | java | public ServiceHandle<S> checkOut(ServiceEndPoint endPoint) throws Exception {
checkNotNull(endPoint);
_requestCount.incrementAndGet();
try {
long revision = _revisionNumber.incrementAndGet();
S service = _pool.borrowObject(endPoint);
ServiceHandle<S> handle = new ServiceHandle<>(service, endPoint);
// Remember the revision that we've checked this service out on in case we need to invalidate it later
_checkedOutRevisions.put(handle, revision);
return handle;
} catch (NoSuchElementException e) {
_missCount.incrementAndGet();
// This will happen if there are no available connections and there is no room for a new one,
// or if a newly created connection is not valid.
throw new NoCachedInstancesAvailableException(String.format("No cached instances available for endpoint: %s", endPoint));
}
} | [
"public",
"ServiceHandle",
"<",
"S",
">",
"checkOut",
"(",
"ServiceEndPoint",
"endPoint",
")",
"throws",
"Exception",
"{",
"checkNotNull",
"(",
"endPoint",
")",
";",
"_requestCount",
".",
"incrementAndGet",
"(",
")",
";",
"try",
"{",
"long",
"revision",
"=",
... | Retrieves a cached service instance for an end point that is not currently checked out. If no idle cached
instance is available and the cache is not full, a new one will be created, added to the cache, and then checked
out. Once the checked out instance is no longer in use, it should be returned by calling {@link #checkIn}.
@param endPoint The end point to retrieve a cached service instance for.
@return A service handle that contains a cached service instance for the requested end point.
@throws NoCachedInstancesAvailableException If the cache has reached total maximum capacity, or maximum capacity
for the requested end point, and no connections that aren't already checked out are available. | [
"Retrieves",
"a",
"cached",
"service",
"instance",
"for",
"an",
"end",
"point",
"that",
"is",
"not",
"currently",
"checked",
"out",
".",
"If",
"no",
"idle",
"cached",
"instance",
"is",
"available",
"and",
"the",
"cache",
"is",
"not",
"full",
"a",
"new",
... | train | https://github.com/bazaarvoice/ostrich/blob/13591867870ab23445253f11fc872662a8028191/core/src/main/java/com/bazaarvoice/ostrich/pool/SingleThreadedClientServiceCache.java#L169-L189 |
jbundle/jbundle | app/program/screen/src/main/java/org/jbundle/app/program/screen/ClassProjectScreen.java | ClassProjectScreen.doCommand | public boolean doCommand(String strCommand, ScreenField sourceSField, int iCommandOptions)
{
boolean bFlag = false;
if (strCommand.indexOf(org.jbundle.app.program.script.process.SetupProjectProcess.class.getName()) != -1)
{
try {
strCommand = Utility.addURLParam(strCommand, DBConstants.OBJECT_ID, this.getMainRecord().writeAndRefresh().toString());
} catch (DBException e) {
e.printStackTrace();
}
}
if (bFlag == false)
bFlag = super.doCommand(strCommand, sourceSField, iCommandOptions); // This will send the command to my parent
return bFlag;
} | java | public boolean doCommand(String strCommand, ScreenField sourceSField, int iCommandOptions)
{
boolean bFlag = false;
if (strCommand.indexOf(org.jbundle.app.program.script.process.SetupProjectProcess.class.getName()) != -1)
{
try {
strCommand = Utility.addURLParam(strCommand, DBConstants.OBJECT_ID, this.getMainRecord().writeAndRefresh().toString());
} catch (DBException e) {
e.printStackTrace();
}
}
if (bFlag == false)
bFlag = super.doCommand(strCommand, sourceSField, iCommandOptions); // This will send the command to my parent
return bFlag;
} | [
"public",
"boolean",
"doCommand",
"(",
"String",
"strCommand",
",",
"ScreenField",
"sourceSField",
",",
"int",
"iCommandOptions",
")",
"{",
"boolean",
"bFlag",
"=",
"false",
";",
"if",
"(",
"strCommand",
".",
"indexOf",
"(",
"org",
".",
"jbundle",
".",
"app"... | Process the command.
<br />Step 1 - Process the command if possible and return true if processed.
<br />Step 2 - If I can't process, pass to all children (with me as the source).
<br />Step 3 - If children didn't process, pass to parent (with me as the source).
<br />Note: Never pass to a parent or child that matches the source (to avoid an endless loop).
@param strCommand The command to process.
@param sourceSField The source screen field (to avoid echos).
@param iCommandOptions If this command creates a new screen, create in a new window?
@return true if success. | [
"Process",
"the",
"command",
".",
"<br",
"/",
">",
"Step",
"1",
"-",
"Process",
"the",
"command",
"if",
"possible",
"and",
"return",
"true",
"if",
"processed",
".",
"<br",
"/",
">",
"Step",
"2",
"-",
"If",
"I",
"can",
"t",
"process",
"pass",
"to",
... | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/app/program/screen/src/main/java/org/jbundle/app/program/screen/ClassProjectScreen.java#L123-L139 |
dita-ot/dita-ot | src/main/java/org/dita/dost/util/MergeUtils.java | MergeUtils.getFirstTopicId | public String getFirstTopicId(final URI file, final boolean useCatalog) {
assert file.isAbsolute();
if (!(new File(file).exists())) {
return null;
}
final StringBuilder firstTopicId = new StringBuilder();
final TopicIdParser parser = new TopicIdParser(firstTopicId);
try {
final XMLReader reader = XMLUtils.getXMLReader();
reader.setContentHandler(parser);
if (useCatalog) {
reader.setEntityResolver(CatalogUtils.getCatalogResolver());
}
reader.parse(file.toString());
} catch (final Exception e) {
logger.error(e.getMessage(), e) ;
}
return firstTopicId.toString();
} | java | public String getFirstTopicId(final URI file, final boolean useCatalog) {
assert file.isAbsolute();
if (!(new File(file).exists())) {
return null;
}
final StringBuilder firstTopicId = new StringBuilder();
final TopicIdParser parser = new TopicIdParser(firstTopicId);
try {
final XMLReader reader = XMLUtils.getXMLReader();
reader.setContentHandler(parser);
if (useCatalog) {
reader.setEntityResolver(CatalogUtils.getCatalogResolver());
}
reader.parse(file.toString());
} catch (final Exception e) {
logger.error(e.getMessage(), e) ;
}
return firstTopicId.toString();
} | [
"public",
"String",
"getFirstTopicId",
"(",
"final",
"URI",
"file",
",",
"final",
"boolean",
"useCatalog",
")",
"{",
"assert",
"file",
".",
"isAbsolute",
"(",
")",
";",
"if",
"(",
"!",
"(",
"new",
"File",
"(",
"file",
")",
".",
"exists",
"(",
")",
")... | Get the first topic id.
@param file file URI
@param useCatalog whether use catalog file for validation
@return topic id | [
"Get",
"the",
"first",
"topic",
"id",
"."
] | train | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/util/MergeUtils.java#L136-L154 |
looly/hutool | hutool-db/src/main/java/cn/hutool/db/AbstractDb.java | AbstractDb.query | public <T> List<T> query(String sql, Class<T> beanClass, Object... params) throws SQLException {
return query(sql, new BeanListHandler<T>(beanClass), params);
} | java | public <T> List<T> query(String sql, Class<T> beanClass, Object... params) throws SQLException {
return query(sql, new BeanListHandler<T>(beanClass), params);
} | [
"public",
"<",
"T",
">",
"List",
"<",
"T",
">",
"query",
"(",
"String",
"sql",
",",
"Class",
"<",
"T",
">",
"beanClass",
",",
"Object",
"...",
"params",
")",
"throws",
"SQLException",
"{",
"return",
"query",
"(",
"sql",
",",
"new",
"BeanListHandler",
... | 查询
@param <T> 结果集需要处理的对象类型
@param sql 查询语句
@param beanClass 元素Bean类型
@param params 参数
@return 结果对象
@throws SQLException SQL执行异常
@since 3.2.2 | [
"查询"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-db/src/main/java/cn/hutool/db/AbstractDb.java#L94-L96 |
samskivert/pythagoras | src/main/java/pythagoras/f/Matrix4.java | Matrix4.setToReflection | public Matrix4 setToReflection (float x, float y, float z, float w) {
float x2 = -2f*x, y2 = -2f*y, z2 = -2f*z;
float xy2 = x2*y, xz2 = x2*z, yz2 = y2*z;
float x2y2z2 = x*x + y*y + z*z;
return set(1f + x2*x, xy2, xz2, x2*w*x2y2z2,
xy2, 1f + y2*y, yz2, y2*w*x2y2z2,
xz2, yz2, 1f + z2*z, z2*w*x2y2z2,
0f, 0f, 0f, 1f);
} | java | public Matrix4 setToReflection (float x, float y, float z, float w) {
float x2 = -2f*x, y2 = -2f*y, z2 = -2f*z;
float xy2 = x2*y, xz2 = x2*z, yz2 = y2*z;
float x2y2z2 = x*x + y*y + z*z;
return set(1f + x2*x, xy2, xz2, x2*w*x2y2z2,
xy2, 1f + y2*y, yz2, y2*w*x2y2z2,
xz2, yz2, 1f + z2*z, z2*w*x2y2z2,
0f, 0f, 0f, 1f);
} | [
"public",
"Matrix4",
"setToReflection",
"(",
"float",
"x",
",",
"float",
"y",
",",
"float",
"z",
",",
"float",
"w",
")",
"{",
"float",
"x2",
"=",
"-",
"2f",
"*",
"x",
",",
"y2",
"=",
"-",
"2f",
"*",
"y",
",",
"z2",
"=",
"-",
"2f",
"*",
"z",
... | Sets this to a reflection across the specified plane.
@return a reference to this matrix, for chaining. | [
"Sets",
"this",
"to",
"a",
"reflection",
"across",
"the",
"specified",
"plane",
"."
] | train | https://github.com/samskivert/pythagoras/blob/b8fea743ee8a7d742ad9c06ee4f11f50571fbd32/src/main/java/pythagoras/f/Matrix4.java#L326-L334 |
opsmatters/opsmatters-core | src/main/java/com/opsmatters/core/util/StringUtilities.java | StringUtilities.getMatchResult | public static boolean getMatchResult(String str, String expr)
{
Pattern pattern = Pattern.compile(expr, Pattern.DOTALL);
return pattern.matcher(str).matches();
} | java | public static boolean getMatchResult(String str, String expr)
{
Pattern pattern = Pattern.compile(expr, Pattern.DOTALL);
return pattern.matcher(str).matches();
} | [
"public",
"static",
"boolean",
"getMatchResult",
"(",
"String",
"str",
",",
"String",
"expr",
")",
"{",
"Pattern",
"pattern",
"=",
"Pattern",
".",
"compile",
"(",
"expr",
",",
"Pattern",
".",
"DOTALL",
")",
";",
"return",
"pattern",
".",
"matcher",
"(",
... | Returns <CODE>true</CODE> if the given string matches the given regular expression.
@param str The string against which the expression is to be matched
@param expr The regular expression to match with the input string
@return <CODE>true</CODE> if the given string matches the given regular expression | [
"Returns",
"<CODE",
">",
"true<",
"/",
"CODE",
">",
"if",
"the",
"given",
"string",
"matches",
"the",
"given",
"regular",
"expression",
"."
] | train | https://github.com/opsmatters/opsmatters-core/blob/c48904f7e8d029fd45357811ec38a735e261e3fd/src/main/java/com/opsmatters/core/util/StringUtilities.java#L136-L140 |
mikepenz/FastAdapter | library-extensions/src/main/java/com/mikepenz/fastadapter_extensions/RangeSelectorHelper.java | RangeSelectorHelper.selectRange | public <T extends IItem & IExpandable> void selectRange(int from, int to, boolean select) {
selectRange(from, to, select, false);
} | java | public <T extends IItem & IExpandable> void selectRange(int from, int to, boolean select) {
selectRange(from, to, select, false);
} | [
"public",
"<",
"T",
"extends",
"IItem",
"&",
"IExpandable",
">",
"void",
"selectRange",
"(",
"int",
"from",
",",
"int",
"to",
",",
"boolean",
"select",
")",
"{",
"selectRange",
"(",
"from",
",",
"to",
",",
"select",
",",
"false",
")",
";",
"}"
] | selects all items in a range, from and to indizes are inclusive
@param from the from index
@param to the to index
@param select true, if the provided range should be selected, false otherwise | [
"selects",
"all",
"items",
"in",
"a",
"range",
"from",
"and",
"to",
"indizes",
"are",
"inclusive"
] | train | https://github.com/mikepenz/FastAdapter/blob/3b2412abe001ba58422e0125846b704d4dba4ae9/library-extensions/src/main/java/com/mikepenz/fastadapter_extensions/RangeSelectorHelper.java#L123-L125 |
flow/nbt | src/main/java/com/flowpowered/nbt/holder/FieldUtils.java | FieldUtils.checkTagCast | public static <T extends Tag<?>> T checkTagCast(Tag<?> tag, Class<T> type) throws IllegalArgumentException {
if (tag == null) {
throw new IllegalArgumentException("Expected tag of type " + type.getName() + ", was null");
} else if (!type.isInstance(tag)) {
throw new IllegalArgumentException("Expected tag to be a " + type.getName() + ", was a " + tag.getClass().getName());
}
return type.cast(tag);
} | java | public static <T extends Tag<?>> T checkTagCast(Tag<?> tag, Class<T> type) throws IllegalArgumentException {
if (tag == null) {
throw new IllegalArgumentException("Expected tag of type " + type.getName() + ", was null");
} else if (!type.isInstance(tag)) {
throw new IllegalArgumentException("Expected tag to be a " + type.getName() + ", was a " + tag.getClass().getName());
}
return type.cast(tag);
} | [
"public",
"static",
"<",
"T",
"extends",
"Tag",
"<",
"?",
">",
">",
"T",
"checkTagCast",
"(",
"Tag",
"<",
"?",
">",
"tag",
",",
"Class",
"<",
"T",
">",
"type",
")",
"throws",
"IllegalArgumentException",
"{",
"if",
"(",
"tag",
"==",
"null",
")",
"{"... | Checks that a tag is not null and of the required type
@param tag The tag to check
@param type The type of tag required
@param <T> The type parameter of {@code type}
@return The casted tag
@throws IllegalArgumentException if the tag is null or not of the required type | [
"Checks",
"that",
"a",
"tag",
"is",
"not",
"null",
"and",
"of",
"the",
"required",
"type"
] | train | https://github.com/flow/nbt/blob/7a1b6d986e6fbd01862356d47827b8b357349a22/src/main/java/com/flowpowered/nbt/holder/FieldUtils.java#L44-L51 |
google/error-prone | core/src/main/java/com/google/errorprone/bugpatterns/apidiff/ApiDiff.java | ApiDiff.isMemberUnsupported | boolean isMemberUnsupported(String className, ClassMemberKey memberKey) {
return unsupportedMembersByClass().containsEntry(className, memberKey)
|| unsupportedMembersByClass()
.containsEntry(className, ClassMemberKey.create(memberKey.identifier(), ""));
} | java | boolean isMemberUnsupported(String className, ClassMemberKey memberKey) {
return unsupportedMembersByClass().containsEntry(className, memberKey)
|| unsupportedMembersByClass()
.containsEntry(className, ClassMemberKey.create(memberKey.identifier(), ""));
} | [
"boolean",
"isMemberUnsupported",
"(",
"String",
"className",
",",
"ClassMemberKey",
"memberKey",
")",
"{",
"return",
"unsupportedMembersByClass",
"(",
")",
".",
"containsEntry",
"(",
"className",
",",
"memberKey",
")",
"||",
"unsupportedMembersByClass",
"(",
")",
"... | Returns true if the member with the given declaring class is unsupported. | [
"Returns",
"true",
"if",
"the",
"member",
"with",
"the",
"given",
"declaring",
"class",
"is",
"unsupported",
"."
] | train | https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/apidiff/ApiDiff.java#L62-L66 |
strator-dev/greenpepper | greenpepper/core/src/main/java/com/greenpepper/interpreter/ListOfInterpreter.java | ListOfInterpreter.processRow | private void processRow(Example valuesRow, Example headers, Fixture rowFixtureAdapter) throws Exception
{
Statistics rowStats = new Statistics();
for (int i = 0; i != valuesRow.remainings(); ++i)
{
Example cell = valuesRow.at( i );
if (i < headers.remainings())
{
ExpectedColumn column = columns != null ? (ExpectedColumn) columns[i] :
CollectionHeaderForm.parse(headers.at(i).getContent()).selectColumn();
chekOneCell(rowFixtureAdapter, rowStats, cell, column);
}
else
{
cell.annotate( ignored( cell.getContent() ) );
}
}
applyRowStatistic(rowStats);
} | java | private void processRow(Example valuesRow, Example headers, Fixture rowFixtureAdapter) throws Exception
{
Statistics rowStats = new Statistics();
for (int i = 0; i != valuesRow.remainings(); ++i)
{
Example cell = valuesRow.at( i );
if (i < headers.remainings())
{
ExpectedColumn column = columns != null ? (ExpectedColumn) columns[i] :
CollectionHeaderForm.parse(headers.at(i).getContent()).selectColumn();
chekOneCell(rowFixtureAdapter, rowStats, cell, column);
}
else
{
cell.annotate( ignored( cell.getContent() ) );
}
}
applyRowStatistic(rowStats);
} | [
"private",
"void",
"processRow",
"(",
"Example",
"valuesRow",
",",
"Example",
"headers",
",",
"Fixture",
"rowFixtureAdapter",
")",
"throws",
"Exception",
"{",
"Statistics",
"rowStats",
"=",
"new",
"Statistics",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0"... | <p>processRow.</p>
@param valuesRow a {@link com.greenpepper.Example} object.
@param headers a {@link com.greenpepper.Example} object.
@param rowFixtureAdapter a {@link com.greenpepper.reflect.Fixture} object.
@throws java.lang.Exception if any. | [
"<p",
">",
"processRow",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/strator-dev/greenpepper/blob/2a61e6c179b74085babcc559d677490b0cad2d30/greenpepper/core/src/main/java/com/greenpepper/interpreter/ListOfInterpreter.java#L126-L146 |
DV8FromTheWorld/JDA | src/main/java/net/dv8tion/jda/bot/sharding/DefaultShardManagerBuilder.java | DefaultShardManagerBuilder.setGatewayPool | public DefaultShardManagerBuilder setGatewayPool(ScheduledExecutorService pool, boolean automaticShutdown)
{
return setGatewayPoolProvider(pool == null ? null : new ThreadPoolProviderImpl<>(pool, automaticShutdown));
} | java | public DefaultShardManagerBuilder setGatewayPool(ScheduledExecutorService pool, boolean automaticShutdown)
{
return setGatewayPoolProvider(pool == null ? null : new ThreadPoolProviderImpl<>(pool, automaticShutdown));
} | [
"public",
"DefaultShardManagerBuilder",
"setGatewayPool",
"(",
"ScheduledExecutorService",
"pool",
",",
"boolean",
"automaticShutdown",
")",
"{",
"return",
"setGatewayPoolProvider",
"(",
"pool",
"==",
"null",
"?",
"null",
":",
"new",
"ThreadPoolProviderImpl",
"<>",
"(",... | Sets the {@link ScheduledExecutorService ScheduledExecutorService} that should be used for
the JDA main WebSocket workers.
<br><b>Only change this pool if you know what you're doing.</b>
<br>This will override the worker pool provider set from {@link #setGatewayPoolProvider(ThreadPoolProvider)}.
@param pool
The thread-pool to use for main WebSocket workers
@param automaticShutdown
Whether {@link net.dv8tion.jda.core.JDA#shutdown()} should automatically shutdown this pool
@return The DefaultShardManagerBuilder instance. Useful for chaining. | [
"Sets",
"the",
"{",
"@link",
"ScheduledExecutorService",
"ScheduledExecutorService",
"}",
"that",
"should",
"be",
"used",
"for",
"the",
"JDA",
"main",
"WebSocket",
"workers",
".",
"<br",
">",
"<b",
">",
"Only",
"change",
"this",
"pool",
"if",
"you",
"know",
... | train | https://github.com/DV8FromTheWorld/JDA/blob/8ecbbe354d03f6bf448411bba573d0d4c268b560/src/main/java/net/dv8tion/jda/bot/sharding/DefaultShardManagerBuilder.java#L785-L788 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/v3/AlertPolicyServiceClient.java | AlertPolicyServiceClient.createAlertPolicy | public final AlertPolicy createAlertPolicy(String name, AlertPolicy alertPolicy) {
CreateAlertPolicyRequest request =
CreateAlertPolicyRequest.newBuilder().setName(name).setAlertPolicy(alertPolicy).build();
return createAlertPolicy(request);
} | java | public final AlertPolicy createAlertPolicy(String name, AlertPolicy alertPolicy) {
CreateAlertPolicyRequest request =
CreateAlertPolicyRequest.newBuilder().setName(name).setAlertPolicy(alertPolicy).build();
return createAlertPolicy(request);
} | [
"public",
"final",
"AlertPolicy",
"createAlertPolicy",
"(",
"String",
"name",
",",
"AlertPolicy",
"alertPolicy",
")",
"{",
"CreateAlertPolicyRequest",
"request",
"=",
"CreateAlertPolicyRequest",
".",
"newBuilder",
"(",
")",
".",
"setName",
"(",
"name",
")",
".",
"... | Creates a new alerting policy.
<p>Sample code:
<pre><code>
try (AlertPolicyServiceClient alertPolicyServiceClient = AlertPolicyServiceClient.create()) {
ProjectName name = ProjectName.of("[PROJECT]");
AlertPolicy alertPolicy = AlertPolicy.newBuilder().build();
AlertPolicy response = alertPolicyServiceClient.createAlertPolicy(name.toString(), alertPolicy);
}
</code></pre>
@param name The project in which to create the alerting policy. The format is
`projects/[PROJECT_ID]`.
<p>Note that this field names the parent container in which the alerting policy will be
written, not the name of the created policy. The alerting policy that is returned will have
a name that contains a normalized representation of this name as a prefix but adds a suffix
of the form `/alertPolicies/[POLICY_ID]`, identifying the policy in the container.
@param alertPolicy The requested alerting policy. You should omit the `name` field in this
policy. The name will be returned in the new policy, including a new [ALERT_POLICY_ID]
value.
@throws com.google.api.gax.rpc.ApiException if the remote call fails | [
"Creates",
"a",
"new",
"alerting",
"policy",
"."
] | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/v3/AlertPolicyServiceClient.java#L465-L470 |
davidcarboni/cryptolite-java | src/main/java/com/github/davidcarboni/cryptolite/Keys.java | Keys.newSecretKey | public static SecretKey newSecretKey() {
// FYI: AES keys are just random bytes from a strong source of randomness.
// Get a key generator instance
KeyGenerator keyGenerator;
try {
keyGenerator = KeyGenerator.getInstance(SYMMETRIC_ALGORITHM);
} catch (NoSuchAlgorithmException e) {
try {
if (SecurityProvider.addProvider()) {
keyGenerator = KeyGenerator.getInstance(SYMMETRIC_ALGORITHM);
} else keyGenerator = null;
} catch (NoSuchAlgorithmException e1) {
keyGenerator = null;
}
if (keyGenerator == null) {
throw new IllegalStateException("Algorithm unavailable: " + SYMMETRIC_ALGORITHM, e);
}
}
// Generate a key:
keyGenerator.init(SYMMETRIC_KEY_SIZE);
return keyGenerator.generateKey();
} | java | public static SecretKey newSecretKey() {
// FYI: AES keys are just random bytes from a strong source of randomness.
// Get a key generator instance
KeyGenerator keyGenerator;
try {
keyGenerator = KeyGenerator.getInstance(SYMMETRIC_ALGORITHM);
} catch (NoSuchAlgorithmException e) {
try {
if (SecurityProvider.addProvider()) {
keyGenerator = KeyGenerator.getInstance(SYMMETRIC_ALGORITHM);
} else keyGenerator = null;
} catch (NoSuchAlgorithmException e1) {
keyGenerator = null;
}
if (keyGenerator == null) {
throw new IllegalStateException("Algorithm unavailable: " + SYMMETRIC_ALGORITHM, e);
}
}
// Generate a key:
keyGenerator.init(SYMMETRIC_KEY_SIZE);
return keyGenerator.generateKey();
} | [
"public",
"static",
"SecretKey",
"newSecretKey",
"(",
")",
"{",
"// FYI: AES keys are just random bytes from a strong source of randomness.\r",
"// Get a key generator instance\r",
"KeyGenerator",
"keyGenerator",
";",
"try",
"{",
"keyGenerator",
"=",
"KeyGenerator",
".",
"getInst... | Generates a new secret (also known as symmetric) key for use with {@value #SYMMETRIC_ALGORITHM}.
<p>
The key size is determined by {@link #SYMMETRIC_KEY_SIZE}.
@return A new, randomly generated secret key. | [
"Generates",
"a",
"new",
"secret",
"(",
"also",
"known",
"as",
"symmetric",
")",
"key",
"for",
"use",
"with",
"{",
"@value",
"#SYMMETRIC_ALGORITHM",
"}",
".",
"<p",
">",
"The",
"key",
"size",
"is",
"determined",
"by",
"{",
"@link",
"#SYMMETRIC_KEY_SIZE",
"... | train | https://github.com/davidcarboni/cryptolite-java/blob/e67954181a04ffc9beb1d9abca1421195fcf9764/src/main/java/com/github/davidcarboni/cryptolite/Keys.java#L133-L157 |
apache/incubator-gobblin | gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/InnerMetricContext.java | InnerMetricContext.getMeters | @Override
public SortedMap<String, Meter> getMeters(MetricFilter filter) {
return getSimplyNamedMetrics(Meter.class, Optional.of(filter));
} | java | @Override
public SortedMap<String, Meter> getMeters(MetricFilter filter) {
return getSimplyNamedMetrics(Meter.class, Optional.of(filter));
} | [
"@",
"Override",
"public",
"SortedMap",
"<",
"String",
",",
"Meter",
">",
"getMeters",
"(",
"MetricFilter",
"filter",
")",
"{",
"return",
"getSimplyNamedMetrics",
"(",
"Meter",
".",
"class",
",",
"Optional",
".",
"of",
"(",
"filter",
")",
")",
";",
"}"
] | See {@link com.codahale.metrics.MetricRegistry#getMeters(com.codahale.metrics.MetricFilter)}.
<p>
This method will return fully-qualified metric names if the {@link MetricContext} is configured
to report fully-qualified metric names.
</p> | [
"See",
"{",
"@link",
"com",
".",
"codahale",
".",
"metrics",
".",
"MetricRegistry#getMeters",
"(",
"com",
".",
"codahale",
".",
"metrics",
".",
"MetricFilter",
")",
"}",
"."
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/InnerMetricContext.java#L229-L232 |
ModeShape/modeshape | modeshape-jcr/src/main/java/org/modeshape/connector/filesystem/FileSystemConnector.java | FileSystemConnector.checkFileNotExcluded | protected void checkFileNotExcluded( String id,
File file ) {
if (isExcluded(file)) {
String msg = JcrI18n.fileConnectorCannotStoreFileThatIsExcluded.text(getSourceName(), id, file.getAbsolutePath());
throw new DocumentStoreException(id, msg);
}
} | java | protected void checkFileNotExcluded( String id,
File file ) {
if (isExcluded(file)) {
String msg = JcrI18n.fileConnectorCannotStoreFileThatIsExcluded.text(getSourceName(), id, file.getAbsolutePath());
throw new DocumentStoreException(id, msg);
}
} | [
"protected",
"void",
"checkFileNotExcluded",
"(",
"String",
"id",
",",
"File",
"file",
")",
"{",
"if",
"(",
"isExcluded",
"(",
"file",
")",
")",
"{",
"String",
"msg",
"=",
"JcrI18n",
".",
"fileConnectorCannotStoreFileThatIsExcluded",
".",
"text",
"(",
"getSour... | Utility method to ensure that the file is writable by this connector.
@param id the identifier of the node
@param file the file
@throws DocumentStoreException if the file is expected to be writable but is not or is excluded, or if the connector is
readonly | [
"Utility",
"method",
"to",
"ensure",
"that",
"the",
"file",
"is",
"writable",
"by",
"this",
"connector",
"."
] | train | https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-jcr/src/main/java/org/modeshape/connector/filesystem/FileSystemConnector.java#L471-L477 |
Carbonado/Carbonado | src/main/java/com/amazon/carbonado/gen/CodeBuilderUtil.java | CodeBuilderUtil.definePrepareBridge | private static void definePrepareBridge(ClassFile cf, Class leaf, Class returnClass) {
TypeDesc returnType = TypeDesc.forClass(returnClass);
if (isPublicMethodFinal(leaf, PREPARE_METHOD_NAME, returnType, null)) {
// Cannot override.
return;
}
MethodInfo mi = cf.addMethod(Modifiers.PUBLIC.toBridge(true),
PREPARE_METHOD_NAME, returnType, null);
CodeBuilder b = new CodeBuilder(mi);
b.loadThis();
b.invokeVirtual(PREPARE_METHOD_NAME, cf.getType(), null);
b.returnValue(returnType);
} | java | private static void definePrepareBridge(ClassFile cf, Class leaf, Class returnClass) {
TypeDesc returnType = TypeDesc.forClass(returnClass);
if (isPublicMethodFinal(leaf, PREPARE_METHOD_NAME, returnType, null)) {
// Cannot override.
return;
}
MethodInfo mi = cf.addMethod(Modifiers.PUBLIC.toBridge(true),
PREPARE_METHOD_NAME, returnType, null);
CodeBuilder b = new CodeBuilder(mi);
b.loadThis();
b.invokeVirtual(PREPARE_METHOD_NAME, cf.getType(), null);
b.returnValue(returnType);
} | [
"private",
"static",
"void",
"definePrepareBridge",
"(",
"ClassFile",
"cf",
",",
"Class",
"leaf",
",",
"Class",
"returnClass",
")",
"{",
"TypeDesc",
"returnType",
"=",
"TypeDesc",
".",
"forClass",
"(",
"returnClass",
")",
";",
"if",
"(",
"isPublicMethodFinal",
... | Add a prepare bridge method to the classfile for the given type.
@param cf file to which to add the prepare bridge
@param leaf leaf class
@param returnClass type returned from generated bridge method
@since 1.2 | [
"Add",
"a",
"prepare",
"bridge",
"method",
"to",
"the",
"classfile",
"for",
"the",
"given",
"type",
"."
] | train | https://github.com/Carbonado/Carbonado/blob/eee29b365a61c8f03e1a1dc6bed0692e6b04b1db/src/main/java/com/amazon/carbonado/gen/CodeBuilderUtil.java#L278-L292 |
b3log/latke | latke-core/src/main/java/org/b3log/latke/servlet/RequestContext.java | RequestContext.parseRequestJSONObject | private static JSONObject parseRequestJSONObject(final HttpServletRequest request, final HttpServletResponse response) {
response.setContentType("application/json");
try {
BufferedReader reader;
try {
reader = request.getReader();
} catch (final IllegalStateException illegalStateException) {
reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
}
String tmp = IOUtils.toString(reader);
if (StringUtils.isBlank(tmp)) {
tmp = "{}";
} else {
if (StringUtils.startsWithIgnoreCase(tmp, "%7B%22" /* {" */)) {
tmp = URLs.decode(tmp);
}
}
return new JSONObject(tmp);
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Parses request JSON object failed [" + e.getMessage() + "], returns an empty json object");
return new JSONObject();
}
} | java | private static JSONObject parseRequestJSONObject(final HttpServletRequest request, final HttpServletResponse response) {
response.setContentType("application/json");
try {
BufferedReader reader;
try {
reader = request.getReader();
} catch (final IllegalStateException illegalStateException) {
reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
}
String tmp = IOUtils.toString(reader);
if (StringUtils.isBlank(tmp)) {
tmp = "{}";
} else {
if (StringUtils.startsWithIgnoreCase(tmp, "%7B%22" /* {" */)) {
tmp = URLs.decode(tmp);
}
}
return new JSONObject(tmp);
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Parses request JSON object failed [" + e.getMessage() + "], returns an empty json object");
return new JSONObject();
}
} | [
"private",
"static",
"JSONObject",
"parseRequestJSONObject",
"(",
"final",
"HttpServletRequest",
"request",
",",
"final",
"HttpServletResponse",
"response",
")",
"{",
"response",
".",
"setContentType",
"(",
"\"application/json\"",
")",
";",
"try",
"{",
"BufferedReader",... | Gets the request json object with the specified request.
@param request the specified request
@param response the specified response, sets its content type with "application/json"
@return a json object | [
"Gets",
"the",
"request",
"json",
"object",
"with",
"the",
"specified",
"request",
"."
] | train | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/servlet/RequestContext.java#L578-L604 |
Azure/azure-sdk-for-java | keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/authentication/KeyVaultCredentials.java | KeyVaultCredentials.getAuthenticationCredentials | private AuthenticationResult getAuthenticationCredentials(Boolean supportsPop, Map<String, String> challengeMap) {
String authorization = challengeMap.get("authorization");
if (authorization == null) {
authorization = challengeMap.get("authorization_uri");
}
String resource = challengeMap.get("resource");
String scope = challengeMap.get("scope");
String schema = supportsPop ? "pop" : "bearer";
return doAuthenticate(authorization, resource, scope, schema);
} | java | private AuthenticationResult getAuthenticationCredentials(Boolean supportsPop, Map<String, String> challengeMap) {
String authorization = challengeMap.get("authorization");
if (authorization == null) {
authorization = challengeMap.get("authorization_uri");
}
String resource = challengeMap.get("resource");
String scope = challengeMap.get("scope");
String schema = supportsPop ? "pop" : "bearer";
return doAuthenticate(authorization, resource, scope, schema);
} | [
"private",
"AuthenticationResult",
"getAuthenticationCredentials",
"(",
"Boolean",
"supportsPop",
",",
"Map",
"<",
"String",
",",
"String",
">",
"challengeMap",
")",
"{",
"String",
"authorization",
"=",
"challengeMap",
".",
"get",
"(",
"\"authorization\"",
")",
";",... | Extracts the authentication challenges from the challenge map and calls the
authentication callback to get the bearer token and return it.
@param supportsPop
is resource supports pop authentication.
@param challengeMap
the challenge map.
@return AuthenticationResult with bearer token and PoP key. | [
"Extracts",
"the",
"authentication",
"challenges",
"from",
"the",
"challenge",
"map",
"and",
"calls",
"the",
"authentication",
"callback",
"to",
"get",
"the",
"bearer",
"token",
"and",
"return",
"it",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/authentication/KeyVaultCredentials.java#L211-L222 |
Alfresco/alfresco-sdk | plugins/alfresco-maven-plugin/src/main/java/org/alfresco/maven/plugin/AbstractRefreshWebappMojo.java | AbstractRefreshWebappMojo.refreshWebScripts | protected void refreshWebScripts(String url) {
// Create the Refresh URL for the Alfresco Tomcat server
URL alfrescoTomcatUrl = buildFinalUrl(url);
if (alfrescoTomcatUrl == null) {
getLog().error("Could not build refresh URL for " + refreshWebappName + ", " + getAbortedMsg());
}
// Set up the data we need to POST to the server for the refresh to work
List<NameValuePair> postData = new ArrayList<NameValuePair>();
postData.add(new BasicNameValuePair("reset", "on"));
postData.add(new BasicNameValuePair("submit", "Refresh Web Scripts"));
// Do the refresh
makePostCall(alfrescoTomcatUrl, postData, "Refresh Web Scripts");
} | java | protected void refreshWebScripts(String url) {
// Create the Refresh URL for the Alfresco Tomcat server
URL alfrescoTomcatUrl = buildFinalUrl(url);
if (alfrescoTomcatUrl == null) {
getLog().error("Could not build refresh URL for " + refreshWebappName + ", " + getAbortedMsg());
}
// Set up the data we need to POST to the server for the refresh to work
List<NameValuePair> postData = new ArrayList<NameValuePair>();
postData.add(new BasicNameValuePair("reset", "on"));
postData.add(new BasicNameValuePair("submit", "Refresh Web Scripts"));
// Do the refresh
makePostCall(alfrescoTomcatUrl, postData, "Refresh Web Scripts");
} | [
"protected",
"void",
"refreshWebScripts",
"(",
"String",
"url",
")",
"{",
"// Create the Refresh URL for the Alfresco Tomcat server",
"URL",
"alfrescoTomcatUrl",
"=",
"buildFinalUrl",
"(",
"url",
")",
";",
"if",
"(",
"alfrescoTomcatUrl",
"==",
"null",
")",
"{",
"getLo... | Perform a Refresh of Web Scripts container in webapp.
Called by specific refresh mojo implementation.
@param url the relative path to refresh webscripts | [
"Perform",
"a",
"Refresh",
"of",
"Web",
"Scripts",
"container",
"in",
"webapp",
".",
"Called",
"by",
"specific",
"refresh",
"mojo",
"implementation",
"."
] | train | https://github.com/Alfresco/alfresco-sdk/blob/7f861a96726edb776293e2363ee85ef05643368b/plugins/alfresco-maven-plugin/src/main/java/org/alfresco/maven/plugin/AbstractRefreshWebappMojo.java#L170-L184 |
jeremylong/DependencyCheck | utils/src/main/java/org/owasp/dependencycheck/utils/Settings.java | Settings.getConnectionString | public String getConnectionString(String connectionStringKey, String dbFileNameKey)
throws IOException, InvalidSettingException {
final String connStr = getString(connectionStringKey);
if (connStr == null) {
final String msg = String.format("Invalid properties file; %s is missing.", connectionStringKey);
throw new InvalidSettingException(msg);
}
if (connStr.contains("%s")) {
final File directory = getH2DataDirectory();
LOGGER.debug("Data directory: {}", directory);
String fileName = null;
if (dbFileNameKey != null) {
fileName = getString(dbFileNameKey);
}
if (fileName == null) {
final String msg = String.format("Invalid properties file to get a file based connection string; '%s' must be defined.",
dbFileNameKey);
throw new InvalidSettingException(msg);
}
if (connStr.startsWith("jdbc:h2:file:") && fileName.endsWith(".mv.db")) {
fileName = fileName.substring(0, fileName.length() - 6);
}
// yes, for H2 this path won't actually exists - but this is sufficient to get the value needed
final File dbFile = new File(directory, fileName);
final String cString = String.format(connStr, dbFile.getCanonicalPath());
LOGGER.debug("Connection String: '{}'", cString);
return cString;
}
return connStr;
} | java | public String getConnectionString(String connectionStringKey, String dbFileNameKey)
throws IOException, InvalidSettingException {
final String connStr = getString(connectionStringKey);
if (connStr == null) {
final String msg = String.format("Invalid properties file; %s is missing.", connectionStringKey);
throw new InvalidSettingException(msg);
}
if (connStr.contains("%s")) {
final File directory = getH2DataDirectory();
LOGGER.debug("Data directory: {}", directory);
String fileName = null;
if (dbFileNameKey != null) {
fileName = getString(dbFileNameKey);
}
if (fileName == null) {
final String msg = String.format("Invalid properties file to get a file based connection string; '%s' must be defined.",
dbFileNameKey);
throw new InvalidSettingException(msg);
}
if (connStr.startsWith("jdbc:h2:file:") && fileName.endsWith(".mv.db")) {
fileName = fileName.substring(0, fileName.length() - 6);
}
// yes, for H2 this path won't actually exists - but this is sufficient to get the value needed
final File dbFile = new File(directory, fileName);
final String cString = String.format(connStr, dbFile.getCanonicalPath());
LOGGER.debug("Connection String: '{}'", cString);
return cString;
}
return connStr;
} | [
"public",
"String",
"getConnectionString",
"(",
"String",
"connectionStringKey",
",",
"String",
"dbFileNameKey",
")",
"throws",
"IOException",
",",
"InvalidSettingException",
"{",
"final",
"String",
"connStr",
"=",
"getString",
"(",
"connectionStringKey",
")",
";",
"i... | Returns a connection string from the configured properties. If the
connection string contains a %s, this method will determine the 'data'
directory and replace the %s with the path to the data directory. If the
data directory does not exist it will be created.
@param connectionStringKey the property file key for the connection
string
@param dbFileNameKey the settings key for the db filename
@return the connection string
@throws IOException thrown the data directory cannot be created
@throws InvalidSettingException thrown if there is an invalid setting | [
"Returns",
"a",
"connection",
"string",
"from",
"the",
"configured",
"properties",
".",
"If",
"the",
"connection",
"string",
"contains",
"a",
"%s",
"this",
"method",
"will",
"determine",
"the",
"data",
"directory",
"and",
"replace",
"the",
"%s",
"with",
"the",... | train | https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/utils/src/main/java/org/owasp/dependencycheck/utils/Settings.java#L1095-L1124 |
beders/Resty | src/main/java/us/monoid/web/Resty.java | Resty.setProxy | public void setProxy(String proxyhost, int proxyport) {
proxy = new java.net.Proxy(java.net.Proxy.Type.HTTP, new InetSocketAddress(proxyhost, proxyport));
} | java | public void setProxy(String proxyhost, int proxyport) {
proxy = new java.net.Proxy(java.net.Proxy.Type.HTTP, new InetSocketAddress(proxyhost, proxyport));
} | [
"public",
"void",
"setProxy",
"(",
"String",
"proxyhost",
",",
"int",
"proxyport",
")",
"{",
"proxy",
"=",
"new",
"java",
".",
"net",
".",
"Proxy",
"(",
"java",
".",
"net",
".",
"Proxy",
".",
"Type",
".",
"HTTP",
",",
"new",
"InetSocketAddress",
"(",
... | Set the proxy for this instance of Resty.
Note, that the proxy settings will be carried over to Resty instances created by this instance only if you used
new Resty(Option.proxy(...))!
@param proxyhost name of the host
@param proxyport port to be used | [
"Set",
"the",
"proxy",
"for",
"this",
"instance",
"of",
"Resty",
".",
"Note",
"that",
"the",
"proxy",
"settings",
"will",
"be",
"carried",
"over",
"to",
"Resty",
"instances",
"created",
"by",
"this",
"instance",
"only",
"if",
"you",
"used",
"new",
"Resty",... | train | https://github.com/beders/Resty/blob/4493603e9689c942cc3e53b9c5018010e414a364/src/main/java/us/monoid/web/Resty.java#L678-L680 |
axibase/atsd-api-java | src/main/java/com/axibase/tsd/client/AtsdPropertyExtractor.java | AtsdPropertyExtractor.getAsBoolean | public boolean getAsBoolean(final String name, final boolean defaultValue) {
return AtsdUtil.getPropertyBoolValue(fullName(name), clientProperties, defaultValue);
} | java | public boolean getAsBoolean(final String name, final boolean defaultValue) {
return AtsdUtil.getPropertyBoolValue(fullName(name), clientProperties, defaultValue);
} | [
"public",
"boolean",
"getAsBoolean",
"(",
"final",
"String",
"name",
",",
"final",
"boolean",
"defaultValue",
")",
"{",
"return",
"AtsdUtil",
".",
"getPropertyBoolValue",
"(",
"fullName",
"(",
"name",
")",
",",
"clientProperties",
",",
"defaultValue",
")",
";",
... | Get property by name as boolean value
@param name name of property without the prefix.
@param defaultValue default value for case when the property is not set.
@return property's value. | [
"Get",
"property",
"by",
"name",
"as",
"boolean",
"value"
] | train | https://github.com/axibase/atsd-api-java/blob/63a0767d08b202dad2ebef4372ff947d6fba0246/src/main/java/com/axibase/tsd/client/AtsdPropertyExtractor.java#L45-L47 |
Harium/keel | src/main/java/com/harium/keel/catalano/math/transform/FourierTransform.java | FourierTransform.convolve | private static void convolve(double[] xreal, double[] ximag, double[] yreal, double[] yimag, double[] outreal, double[] outimag) {
// if (xreal.length != ximag.length || xreal.length != yreal.length || yreal.length != yimag.length || xreal.length != outreal.length || outreal.length != outimag.length)
// throw new IllegalArgumentException("Mismatched lengths");
int n = xreal.length;
FFT(xreal, ximag);
FFT(yreal, yimag);
for (int i = 0; i < n; i++) {
double temp = xreal[i] * yreal[i] - ximag[i] * yimag[i];
ximag[i] = ximag[i] * yreal[i] + xreal[i] * yimag[i];
xreal[i] = temp;
}
inverseTransform(xreal, ximag);
// Scaling (because this FFT implementation omits it)
for (int i = 0; i < n; i++) {
outreal[i] = xreal[i] / n;
outimag[i] = ximag[i] / n;
}
} | java | private static void convolve(double[] xreal, double[] ximag, double[] yreal, double[] yimag, double[] outreal, double[] outimag) {
// if (xreal.length != ximag.length || xreal.length != yreal.length || yreal.length != yimag.length || xreal.length != outreal.length || outreal.length != outimag.length)
// throw new IllegalArgumentException("Mismatched lengths");
int n = xreal.length;
FFT(xreal, ximag);
FFT(yreal, yimag);
for (int i = 0; i < n; i++) {
double temp = xreal[i] * yreal[i] - ximag[i] * yimag[i];
ximag[i] = ximag[i] * yreal[i] + xreal[i] * yimag[i];
xreal[i] = temp;
}
inverseTransform(xreal, ximag);
// Scaling (because this FFT implementation omits it)
for (int i = 0; i < n; i++) {
outreal[i] = xreal[i] / n;
outimag[i] = ximag[i] / n;
}
} | [
"private",
"static",
"void",
"convolve",
"(",
"double",
"[",
"]",
"xreal",
",",
"double",
"[",
"]",
"ximag",
",",
"double",
"[",
"]",
"yreal",
",",
"double",
"[",
"]",
"yimag",
",",
"double",
"[",
"]",
"outreal",
",",
"double",
"[",
"]",
"outimag",
... | /*
Computes the circular convolution of the given complex vectors. Each vector's length must be the same. | [
"/",
"*",
"Computes",
"the",
"circular",
"convolution",
"of",
"the",
"given",
"complex",
"vectors",
".",
"Each",
"vector",
"s",
"length",
"must",
"be",
"the",
"same",
"."
] | train | https://github.com/Harium/keel/blob/0369ae674f9e664bccc5f9e161ae7e7a3b949a1e/src/main/java/com/harium/keel/catalano/math/transform/FourierTransform.java#L357-L377 |
jbundle/jbundle | base/screen/model/src/main/java/org/jbundle/base/screen/view/ViewFactory.java | ViewFactory.getViewFactory | public static ViewFactory getViewFactory(String strSubPackage, char chPrefix)
{
ViewFactory viewFactory = null;
viewFactory = (ViewFactory)m_htFactories.get(strSubPackage);
if (viewFactory == null)
{
viewFactory = new ViewFactory(strSubPackage, chPrefix);
m_htFactories.put(strSubPackage, viewFactory);
}
return viewFactory;
} | java | public static ViewFactory getViewFactory(String strSubPackage, char chPrefix)
{
ViewFactory viewFactory = null;
viewFactory = (ViewFactory)m_htFactories.get(strSubPackage);
if (viewFactory == null)
{
viewFactory = new ViewFactory(strSubPackage, chPrefix);
m_htFactories.put(strSubPackage, viewFactory);
}
return viewFactory;
} | [
"public",
"static",
"ViewFactory",
"getViewFactory",
"(",
"String",
"strSubPackage",
",",
"char",
"chPrefix",
")",
"{",
"ViewFactory",
"viewFactory",
"=",
"null",
";",
"viewFactory",
"=",
"(",
"ViewFactory",
")",
"m_htFactories",
".",
"get",
"(",
"strSubPackage",
... | Lookup a standard view factory.
@param strSubPackage The subpackage name (such as swing/xml/etc.).
@param chPrefix The prefix to add on the view classes.
@return The View Factory for this sub-package. | [
"Lookup",
"a",
"standard",
"view",
"factory",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/screen/model/src/main/java/org/jbundle/base/screen/view/ViewFactory.java#L213-L223 |
Metatavu/edelphi | edelphi/src/main/java/fi/metatavu/edelphi/utils/GoogleDriveUtils.java | GoogleDriveUtils.exportSpreadsheet | public static DownloadResponse exportSpreadsheet(Drive drive, File file) throws IOException {
return exportSpreadsheet(drive, file.getId());
} | java | public static DownloadResponse exportSpreadsheet(Drive drive, File file) throws IOException {
return exportSpreadsheet(drive, file.getId());
} | [
"public",
"static",
"DownloadResponse",
"exportSpreadsheet",
"(",
"Drive",
"drive",
",",
"File",
"file",
")",
"throws",
"IOException",
"{",
"return",
"exportSpreadsheet",
"(",
"drive",
",",
"file",
".",
"getId",
"(",
")",
")",
";",
"}"
] | Exports a spreadsheet in HTML format
@param drive drive client
@param file file to be exported
@return Spreadsheet in HTML format
@throws IOException thrown when exporting fails unexpectedly | [
"Exports",
"a",
"spreadsheet",
"in",
"HTML",
"format"
] | train | https://github.com/Metatavu/edelphi/blob/d91a0b54f954b33b4ee674a1bdf03612d76c3305/edelphi/src/main/java/fi/metatavu/edelphi/utils/GoogleDriveUtils.java#L319-L321 |
fhoeben/hsac-fitnesse-fixtures | src/main/java/nl/hsac/fitnesse/fixture/util/FtpFileUtil.java | FtpFileUtil.uploadFileToFTPServer | public static String uploadFileToFTPServer(String hostName, Integer port, String userName,
String password, String localFileFullName, String remotePath) {
String result = null;
FTPClient ftpClient = new FTPClient();
String errorMessage = "Unable to upload file '%s' for FTP server '%s'.";
InputStream inputStream = null;
try {
connectAndLoginOnFTPServer(ftpClient, hostName, port, userName, password);
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
//String fullLocalPath = localPath + fileName;
File localFile = new File(localFileFullName);
//String fullRemotePath = remotePath + fileName;
String remoteFile = remotePath + FilenameUtils.getName(localFileFullName);
inputStream = new FileInputStream(localFile);
boolean uploadFinished = ftpClient.storeFile(remoteFile, inputStream);
if (uploadFinished) {
result = String.format("File '%s' successfully uploaded", localFileFullName);
} else {
result = String.format("Failed upload '%s' file to FTP server. Got reply: %s",
localFileFullName, ftpClient.getReplyString());
}
} catch (IOException ex) {
throw new RuntimeException(String.format(errorMessage, remotePath, hostName), ex);
} finally {
closeInputStream(inputStream);
disconnectAndLogoutFromFTPServer(ftpClient, hostName);
}
return result;
} | java | public static String uploadFileToFTPServer(String hostName, Integer port, String userName,
String password, String localFileFullName, String remotePath) {
String result = null;
FTPClient ftpClient = new FTPClient();
String errorMessage = "Unable to upload file '%s' for FTP server '%s'.";
InputStream inputStream = null;
try {
connectAndLoginOnFTPServer(ftpClient, hostName, port, userName, password);
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
//String fullLocalPath = localPath + fileName;
File localFile = new File(localFileFullName);
//String fullRemotePath = remotePath + fileName;
String remoteFile = remotePath + FilenameUtils.getName(localFileFullName);
inputStream = new FileInputStream(localFile);
boolean uploadFinished = ftpClient.storeFile(remoteFile, inputStream);
if (uploadFinished) {
result = String.format("File '%s' successfully uploaded", localFileFullName);
} else {
result = String.format("Failed upload '%s' file to FTP server. Got reply: %s",
localFileFullName, ftpClient.getReplyString());
}
} catch (IOException ex) {
throw new RuntimeException(String.format(errorMessage, remotePath, hostName), ex);
} finally {
closeInputStream(inputStream);
disconnectAndLogoutFromFTPServer(ftpClient, hostName);
}
return result;
} | [
"public",
"static",
"String",
"uploadFileToFTPServer",
"(",
"String",
"hostName",
",",
"Integer",
"port",
",",
"String",
"userName",
",",
"String",
"password",
",",
"String",
"localFileFullName",
",",
"String",
"remotePath",
")",
"{",
"String",
"result",
"=",
"n... | Upload a given file to FTP server.
@param hostName the FTP server host name to connect
@param port the port to connect
@param userName the user name
@param password the password
@param localFileFullName the full name (inclusive path) of the local file.
@param remotePath the path to the file on the FTP.
@return reply string from FTP server after the command has been executed.
@throws RuntimeException in case any exception has been thrown. | [
"Upload",
"a",
"given",
"file",
"to",
"FTP",
"server",
"."
] | train | https://github.com/fhoeben/hsac-fitnesse-fixtures/blob/4e9018d7386a9aa65bfcbf07eb28ae064edd1732/src/main/java/nl/hsac/fitnesse/fixture/util/FtpFileUtil.java#L95-L130 |
google/j2objc | xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/transformer/TransformerHandlerImpl.java | TransformerHandlerImpl.startPrefixMapping | public void startPrefixMapping(String prefix, String uri)
throws SAXException
{
if (DEBUG)
System.out.println("TransformerHandlerImpl#startPrefixMapping: "
+ prefix + ", " + uri);
if (m_contentHandler != null)
{
m_contentHandler.startPrefixMapping(prefix, uri);
}
} | java | public void startPrefixMapping(String prefix, String uri)
throws SAXException
{
if (DEBUG)
System.out.println("TransformerHandlerImpl#startPrefixMapping: "
+ prefix + ", " + uri);
if (m_contentHandler != null)
{
m_contentHandler.startPrefixMapping(prefix, uri);
}
} | [
"public",
"void",
"startPrefixMapping",
"(",
"String",
"prefix",
",",
"String",
"uri",
")",
"throws",
"SAXException",
"{",
"if",
"(",
"DEBUG",
")",
"System",
".",
"out",
".",
"println",
"(",
"\"TransformerHandlerImpl#startPrefixMapping: \"",
"+",
"prefix",
"+",
... | Filter a start Namespace prefix mapping event.
@param prefix The Namespace prefix.
@param uri The Namespace URI.
@throws SAXException The client may throw
an exception during processing.
@see org.xml.sax.ContentHandler#startPrefixMapping | [
"Filter",
"a",
"start",
"Namespace",
"prefix",
"mapping",
"event",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/transformer/TransformerHandlerImpl.java#L443-L455 |
Azure/azure-sdk-for-java | applicationinsights/resource-manager/v2015_05_01/src/main/java/com/microsoft/azure/management/applicationinsights/v2015_05_01/implementation/WorkItemConfigurationsInner.java | WorkItemConfigurationsInner.getDefault | public WorkItemConfigurationInner getDefault(String resourceGroupName, String resourceName) {
return getDefaultWithServiceResponseAsync(resourceGroupName, resourceName).toBlocking().single().body();
} | java | public WorkItemConfigurationInner getDefault(String resourceGroupName, String resourceName) {
return getDefaultWithServiceResponseAsync(resourceGroupName, resourceName).toBlocking().single().body();
} | [
"public",
"WorkItemConfigurationInner",
"getDefault",
"(",
"String",
"resourceGroupName",
",",
"String",
"resourceName",
")",
"{",
"return",
"getDefaultWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"resourceName",
")",
".",
"toBlocking",
"(",
")",
".",
"sing... | Gets default work item configurations that exist for the application.
@param resourceGroupName The name of the resource group.
@param resourceName The name of the Application Insights component resource.
@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 WorkItemConfigurationInner object if successful. | [
"Gets",
"default",
"work",
"item",
"configurations",
"that",
"exist",
"for",
"the",
"application",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/applicationinsights/resource-manager/v2015_05_01/src/main/java/com/microsoft/azure/management/applicationinsights/v2015_05_01/implementation/WorkItemConfigurationsInner.java#L274-L276 |
crnk-project/crnk-framework | crnk-setup/crnk-setup-rs/src/main/java/io/crnk/rs/CrnkFeature.java | CrnkFeature.registerActionRepositories | private void registerActionRepositories(FeatureContext context, CrnkBoot boot) {
ResourceRegistry resourceRegistry = boot.getResourceRegistry();
Collection<RegistryEntry> registryEntries = resourceRegistry.getEntries();
for (RegistryEntry registryEntry : registryEntries) {
ResourceRepositoryInformation repositoryInformation = registryEntry.getRepositoryInformation();
if (repositoryInformation != null && !repositoryInformation.getActions().isEmpty()) {
ResourceRepositoryAdapter repositoryAdapter = registryEntry.getResourceRepository();
Object resourceRepository = repositoryAdapter.getResourceRepository();
context.register(resourceRepository);
}
}
} | java | private void registerActionRepositories(FeatureContext context, CrnkBoot boot) {
ResourceRegistry resourceRegistry = boot.getResourceRegistry();
Collection<RegistryEntry> registryEntries = resourceRegistry.getEntries();
for (RegistryEntry registryEntry : registryEntries) {
ResourceRepositoryInformation repositoryInformation = registryEntry.getRepositoryInformation();
if (repositoryInformation != null && !repositoryInformation.getActions().isEmpty()) {
ResourceRepositoryAdapter repositoryAdapter = registryEntry.getResourceRepository();
Object resourceRepository = repositoryAdapter.getResourceRepository();
context.register(resourceRepository);
}
}
} | [
"private",
"void",
"registerActionRepositories",
"(",
"FeatureContext",
"context",
",",
"CrnkBoot",
"boot",
")",
"{",
"ResourceRegistry",
"resourceRegistry",
"=",
"boot",
".",
"getResourceRegistry",
"(",
")",
";",
"Collection",
"<",
"RegistryEntry",
">",
"registryEntr... | All repositories with JAX-RS action need to be registered with JAX-RS as singletons.
@param context of jaxrs
@param boot of crnk | [
"All",
"repositories",
"with",
"JAX",
"-",
"RS",
"action",
"need",
"to",
"be",
"registered",
"with",
"JAX",
"-",
"RS",
"as",
"singletons",
"."
] | train | https://github.com/crnk-project/crnk-framework/blob/2fd3ef9a991788d46fd2e83b43c8ea37cbaf8681/crnk-setup/crnk-setup-rs/src/main/java/io/crnk/rs/CrnkFeature.java#L94-L105 |
exoplatform/jcr | exo.jcr.component.webdav/src/main/java/org/exoplatform/services/jcr/webdav/util/NodeTypeUtil.java | NodeTypeUtil.getNodeType | public static String getNodeType(String nodeTypeHeader, String defaultNodeType, Set<String> allowedNodeTypes)
throws NoSuchNodeTypeException
{
if (nodeTypeHeader == null)
{
return defaultNodeType;
}
if (allowedNodeTypes.contains(nodeTypeHeader))
{
return nodeTypeHeader;
}
throw new NoSuchNodeTypeException("Unsupported node type: " + nodeTypeHeader);
} | java | public static String getNodeType(String nodeTypeHeader, String defaultNodeType, Set<String> allowedNodeTypes)
throws NoSuchNodeTypeException
{
if (nodeTypeHeader == null)
{
return defaultNodeType;
}
if (allowedNodeTypes.contains(nodeTypeHeader))
{
return nodeTypeHeader;
}
throw new NoSuchNodeTypeException("Unsupported node type: " + nodeTypeHeader);
} | [
"public",
"static",
"String",
"getNodeType",
"(",
"String",
"nodeTypeHeader",
",",
"String",
"defaultNodeType",
",",
"Set",
"<",
"String",
">",
"allowedNodeTypes",
")",
"throws",
"NoSuchNodeTypeException",
"{",
"if",
"(",
"nodeTypeHeader",
"==",
"null",
")",
"{",
... | Returns parsed nodeType obtained from node-type header.
This method is unified for files and folders.
@param nodeTypeHeader
@param defaultNodeType
@param allowedNodeTypes
@return
@throws NoSuchNodeTypeException is thrown if node-type header contains not allowed node type | [
"Returns",
"parsed",
"nodeType",
"obtained",
"from",
"node",
"-",
"type",
"header",
".",
"This",
"method",
"is",
"unified",
"for",
"files",
"and",
"folders",
"."
] | train | https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.webdav/src/main/java/org/exoplatform/services/jcr/webdav/util/NodeTypeUtil.java#L49-L62 |
samskivert/pythagoras | src/main/java/pythagoras/d/Rectangles.java | Rectangles.closestInteriorPoint | public static Point closestInteriorPoint (IRectangle r, IPoint p, Point out) {
out.set(MathUtil.clamp(p.x(), r.minX(), r.maxX()),
MathUtil.clamp(p.y(), r.minY(), r.maxY()));
return out;
} | java | public static Point closestInteriorPoint (IRectangle r, IPoint p, Point out) {
out.set(MathUtil.clamp(p.x(), r.minX(), r.maxX()),
MathUtil.clamp(p.y(), r.minY(), r.maxY()));
return out;
} | [
"public",
"static",
"Point",
"closestInteriorPoint",
"(",
"IRectangle",
"r",
",",
"IPoint",
"p",
",",
"Point",
"out",
")",
"{",
"out",
".",
"set",
"(",
"MathUtil",
".",
"clamp",
"(",
"p",
".",
"x",
"(",
")",
",",
"r",
".",
"minX",
"(",
")",
",",
... | Computes the point inside the bounds of the rectangle that's closest to the given point,
writing the result into {@code out}.
@return {@code out} for call chaining convenience. | [
"Computes",
"the",
"point",
"inside",
"the",
"bounds",
"of",
"the",
"rectangle",
"that",
"s",
"closest",
"to",
"the",
"given",
"point",
"writing",
"the",
"result",
"into",
"{"
] | train | https://github.com/samskivert/pythagoras/blob/b8fea743ee8a7d742ad9c06ee4f11f50571fbd32/src/main/java/pythagoras/d/Rectangles.java#L39-L43 |
aspectran/aspectran | core/src/main/java/com/aspectran/core/support/i18n/message/ResourceBundleMessageSource.java | ResourceBundleMessageSource.resolveCodeWithoutArguments | @Override
protected String resolveCodeWithoutArguments(String code, Locale locale) {
String result = null;
for (int i = 0; result == null && i < this.basenames.length; i++) {
ResourceBundle bundle = getResourceBundle(this.basenames[i], locale);
if (bundle != null) {
result = getStringOrNull(bundle, code);
}
}
return result;
} | java | @Override
protected String resolveCodeWithoutArguments(String code, Locale locale) {
String result = null;
for (int i = 0; result == null && i < this.basenames.length; i++) {
ResourceBundle bundle = getResourceBundle(this.basenames[i], locale);
if (bundle != null) {
result = getStringOrNull(bundle, code);
}
}
return result;
} | [
"@",
"Override",
"protected",
"String",
"resolveCodeWithoutArguments",
"(",
"String",
"code",
",",
"Locale",
"locale",
")",
"{",
"String",
"result",
"=",
"null",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"result",
"==",
"null",
"&&",
"i",
"<",
"this",
... | Resolves the given message code as key in the registered resource bundles,
returning the value found in the bundle as-is (without MessageFormat parsing). | [
"Resolves",
"the",
"given",
"message",
"code",
"as",
"key",
"in",
"the",
"registered",
"resource",
"bundles",
"returning",
"the",
"value",
"found",
"in",
"the",
"bundle",
"as",
"-",
"is",
"(",
"without",
"MessageFormat",
"parsing",
")",
"."
] | train | https://github.com/aspectran/aspectran/blob/2d758a2a28b71ee85b42823c12dc44674d7f2c70/core/src/main/java/com/aspectran/core/support/i18n/message/ResourceBundleMessageSource.java#L212-L222 |
joniles/mpxj | src/main/java/net/sf/mpxj/sdef/SDEFWriter.java | SDEFWriter.writeCalendarException | private void writeCalendarException(ProjectCalendar parentCalendar, ProjectCalendarException record) throws IOException
{
m_buffer.setLength(0);
Calendar stepDay = DateHelper.popCalendar(record.getFromDate()); // Start at From Date, then step through days...
Calendar lastDay = DateHelper.popCalendar(record.getToDate()); // last day in this exception
m_buffer.append("HOLI ");
m_buffer.append(SDEFmethods.lset(parentCalendar.getUniqueID().toString(), 2));
while (stepDay.compareTo(lastDay) <= 0)
{
m_buffer.append(m_formatter.format(stepDay.getTime()).toUpperCase() + " ");
stepDay.add(Calendar.DAY_OF_MONTH, 1);
}
m_writer.println(m_buffer.toString());
DateHelper.pushCalendar(stepDay);
DateHelper.pushCalendar(lastDay);
} | java | private void writeCalendarException(ProjectCalendar parentCalendar, ProjectCalendarException record) throws IOException
{
m_buffer.setLength(0);
Calendar stepDay = DateHelper.popCalendar(record.getFromDate()); // Start at From Date, then step through days...
Calendar lastDay = DateHelper.popCalendar(record.getToDate()); // last day in this exception
m_buffer.append("HOLI ");
m_buffer.append(SDEFmethods.lset(parentCalendar.getUniqueID().toString(), 2));
while (stepDay.compareTo(lastDay) <= 0)
{
m_buffer.append(m_formatter.format(stepDay.getTime()).toUpperCase() + " ");
stepDay.add(Calendar.DAY_OF_MONTH, 1);
}
m_writer.println(m_buffer.toString());
DateHelper.pushCalendar(stepDay);
DateHelper.pushCalendar(lastDay);
} | [
"private",
"void",
"writeCalendarException",
"(",
"ProjectCalendar",
"parentCalendar",
",",
"ProjectCalendarException",
"record",
")",
"throws",
"IOException",
"{",
"m_buffer",
".",
"setLength",
"(",
"0",
")",
";",
"Calendar",
"stepDay",
"=",
"DateHelper",
".",
"pop... | Write a calendar exception.
@param parentCalendar parent calendar instance
@param record calendar exception instance
@throws IOException | [
"Write",
"a",
"calendar",
"exception",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/sdef/SDEFWriter.java#L223-L241 |
openbaton/openbaton-client | sdk/src/main/java/org/openbaton/sdk/api/rest/NetworkServiceDescriptorAgent.java | NetworkServiceDescriptorAgent.createVNFDependency | @Help(
help =
"Create the VirtualNetworkFunctionDescriptor dependency of a NetworkServiceDescriptor with specific id"
)
public VNFDependency createVNFDependency(final String idNSD, final VNFDependency vnfDependency)
throws SDKException {
String url = idNSD + "/vnfdependencies" + "/";
return (VNFDependency) requestPost(url, vnfDependency);
} | java | @Help(
help =
"Create the VirtualNetworkFunctionDescriptor dependency of a NetworkServiceDescriptor with specific id"
)
public VNFDependency createVNFDependency(final String idNSD, final VNFDependency vnfDependency)
throws SDKException {
String url = idNSD + "/vnfdependencies" + "/";
return (VNFDependency) requestPost(url, vnfDependency);
} | [
"@",
"Help",
"(",
"help",
"=",
"\"Create the VirtualNetworkFunctionDescriptor dependency of a NetworkServiceDescriptor with specific id\"",
")",
"public",
"VNFDependency",
"createVNFDependency",
"(",
"final",
"String",
"idNSD",
",",
"final",
"VNFDependency",
"vnfDependency",
")",... | Add a new VNFDependency to a specific NetworkServiceDescriptor.
@param idNSD the ID of the NetworkServiceDescriptor
@param vnfDependency the new VNFDependency
@return the new VNFDependency
@throws SDKException if the request fails | [
"Add",
"a",
"new",
"VNFDependency",
"to",
"a",
"specific",
"NetworkServiceDescriptor",
"."
] | train | https://github.com/openbaton/openbaton-client/blob/6ca6dd6b62a23940d312213d6fa489d5b636061a/sdk/src/main/java/org/openbaton/sdk/api/rest/NetworkServiceDescriptorAgent.java#L261-L269 |
lucee/Lucee | core/src/main/java/lucee/commons/io/res/util/ResourceUtil.java | ResourceUtil.getExtension | public static String getExtension(Resource res, String defaultValue) {
return getExtension(res.getName(), defaultValue);
} | java | public static String getExtension(Resource res, String defaultValue) {
return getExtension(res.getName(), defaultValue);
} | [
"public",
"static",
"String",
"getExtension",
"(",
"Resource",
"res",
",",
"String",
"defaultValue",
")",
"{",
"return",
"getExtension",
"(",
"res",
".",
"getName",
"(",
")",
",",
"defaultValue",
")",
";",
"}"
] | get the Extension of a file
@param res
@return extension of file | [
"get",
"the",
"Extension",
"of",
"a",
"file"
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/commons/io/res/util/ResourceUtil.java#L840-L842 |
JodaOrg/joda-time | src/main/java/org/joda/time/format/DateTimeFormat.java | DateTimeFormat.createFormatterForStyleIndex | private static DateTimeFormatter createFormatterForStyleIndex(int dateStyle, int timeStyle) {
int index = ((dateStyle << 2) + dateStyle) + timeStyle; // (dateStyle * 5 + timeStyle);
// Should never happen but do a double check...
if (index >= cStyleCache.length()) {
return createDateTimeFormatter(dateStyle, timeStyle);
}
DateTimeFormatter f = cStyleCache.get(index);
if (f == null) {
f = createDateTimeFormatter(dateStyle, timeStyle);
if (cStyleCache.compareAndSet(index, null, f) == false) {
f = cStyleCache.get(index);
}
}
return f;
} | java | private static DateTimeFormatter createFormatterForStyleIndex(int dateStyle, int timeStyle) {
int index = ((dateStyle << 2) + dateStyle) + timeStyle; // (dateStyle * 5 + timeStyle);
// Should never happen but do a double check...
if (index >= cStyleCache.length()) {
return createDateTimeFormatter(dateStyle, timeStyle);
}
DateTimeFormatter f = cStyleCache.get(index);
if (f == null) {
f = createDateTimeFormatter(dateStyle, timeStyle);
if (cStyleCache.compareAndSet(index, null, f) == false) {
f = cStyleCache.get(index);
}
}
return f;
} | [
"private",
"static",
"DateTimeFormatter",
"createFormatterForStyleIndex",
"(",
"int",
"dateStyle",
",",
"int",
"timeStyle",
")",
"{",
"int",
"index",
"=",
"(",
"(",
"dateStyle",
"<<",
"2",
")",
"+",
"dateStyle",
")",
"+",
"timeStyle",
";",
"// (dateStyle * 5 + t... | Gets the formatter for the specified style.
@param dateStyle the date style
@param timeStyle the time style
@return the formatter | [
"Gets",
"the",
"formatter",
"for",
"the",
"specified",
"style",
"."
] | train | https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/format/DateTimeFormat.java#L729-L743 |
jeremylong/DependencyCheck | core/src/main/java/org/owasp/dependencycheck/data/update/nvd/ProcessTask.java | ProcessTask.importJSON | protected void importJSON(File file) throws ParserConfigurationException,
IOException, SQLException, DatabaseException, ClassNotFoundException, UpdateException {
final NvdCveParser parser = new NvdCveParser(settings, cveDB);
parser.parse(file);
} | java | protected void importJSON(File file) throws ParserConfigurationException,
IOException, SQLException, DatabaseException, ClassNotFoundException, UpdateException {
final NvdCveParser parser = new NvdCveParser(settings, cveDB);
parser.parse(file);
} | [
"protected",
"void",
"importJSON",
"(",
"File",
"file",
")",
"throws",
"ParserConfigurationException",
",",
"IOException",
",",
"SQLException",
",",
"DatabaseException",
",",
"ClassNotFoundException",
",",
"UpdateException",
"{",
"final",
"NvdCveParser",
"parser",
"=",
... | Imports the NVD CVE JSON File into the database.
@param file the file containing the NVD CVE JSON
@throws ParserConfigurationException is thrown if there is a parser
configuration exception
@throws IOException is thrown if there is a IO Exception
@throws SQLException is thrown if there is a SQL exception
@throws DatabaseException is thrown if there is a database exception
@throws ClassNotFoundException thrown if the h2 database driver cannot be
loaded
@throws UpdateException thrown if the file could not be found | [
"Imports",
"the",
"NVD",
"CVE",
"JSON",
"File",
"into",
"the",
"database",
"."
] | train | https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/data/update/nvd/ProcessTask.java#L135-L140 |
OpenLiberty/open-liberty | dev/com.ibm.ws.webcontainer/src/com/ibm/ws/webcontainer/srt/SRTServletRequest.java | SRTServletRequest.finish | public void finish() //280584.3 6021: Cleanup of defect 280584.2 WAS.webcontainer removed throws clause.
{
if (TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) { //306998.15
logger.logp(Level.FINE, CLASS_NAME,"finish", "entry");
}
if (WCCustomProperties.CHECK_REQUEST_OBJECT_IN_USE){
checkRequestObjectInUse();
}
try
{
int length = getContentLength();
if (length > 0)
{
_in.close();
}
// begin 280584.3 6021: Cleanup of defect 280584.2 WAS.webcontainer: moved from finally block
else
{
this._in.finish();
}
// end 280584.3 6021: Cleanup of defect 280584.2 WAS.webcontainer
}
catch (IOException e)
{
com.ibm.wsspi.webcontainer.util.FFDCWrapper.processException(e, "com.ibm.ws.webcontainer.srt.SRTServletRequest.finish", "875", this);
// begin 280584.3 6021: Cleanup of defect 280584.2 WAS.webcontainer
if (TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)){ //306998.15
logger.logp(Level.FINE, CLASS_NAME,"finish", "Error occurred while finishing request", e);
}
// logger.logp(Level.SEVERE, CLASS_NAME,"finish", "IO.Error", e);
//se = new ServletException(nls.getString("Error.occured.while.finishing.request", "Error occurred while finishing request"), e);
// end 280584.3 6021: Cleanup of defect 280584.2 WAS.webcontainer
}
finally
{
cleanupFromFinish();
}
} | java | public void finish() //280584.3 6021: Cleanup of defect 280584.2 WAS.webcontainer removed throws clause.
{
if (TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) { //306998.15
logger.logp(Level.FINE, CLASS_NAME,"finish", "entry");
}
if (WCCustomProperties.CHECK_REQUEST_OBJECT_IN_USE){
checkRequestObjectInUse();
}
try
{
int length = getContentLength();
if (length > 0)
{
_in.close();
}
// begin 280584.3 6021: Cleanup of defect 280584.2 WAS.webcontainer: moved from finally block
else
{
this._in.finish();
}
// end 280584.3 6021: Cleanup of defect 280584.2 WAS.webcontainer
}
catch (IOException e)
{
com.ibm.wsspi.webcontainer.util.FFDCWrapper.processException(e, "com.ibm.ws.webcontainer.srt.SRTServletRequest.finish", "875", this);
// begin 280584.3 6021: Cleanup of defect 280584.2 WAS.webcontainer
if (TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)){ //306998.15
logger.logp(Level.FINE, CLASS_NAME,"finish", "Error occurred while finishing request", e);
}
// logger.logp(Level.SEVERE, CLASS_NAME,"finish", "IO.Error", e);
//se = new ServletException(nls.getString("Error.occured.while.finishing.request", "Error occurred while finishing request"), e);
// end 280584.3 6021: Cleanup of defect 280584.2 WAS.webcontainer
}
finally
{
cleanupFromFinish();
}
} | [
"public",
"void",
"finish",
"(",
")",
"//280584.3 6021: Cleanup of defect 280584.2 WAS.webcontainer removed throws clause.",
"{",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"logger",
".",
"isLoggable",
"(",
"Level",
".",
"FINE",
")",
... | Close this request.
This method must be called after the request has been processed. | [
"Close",
"this",
"request",
".",
"This",
"method",
"must",
"be",
"called",
"after",
"the",
"request",
"has",
"been",
"processed",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.webcontainer/src/com/ibm/ws/webcontainer/srt/SRTServletRequest.java#L2700-L2738 |
jcuda/jcuda | JCudaJava/src/main/java/jcuda/cuDoubleComplex.java | cuDoubleComplex.cuCmplx | public static cuDoubleComplex cuCmplx (double r, double i)
{
cuDoubleComplex res = new cuDoubleComplex();
res.x = r;
res.y = i;
return res;
} | java | public static cuDoubleComplex cuCmplx (double r, double i)
{
cuDoubleComplex res = new cuDoubleComplex();
res.x = r;
res.y = i;
return res;
} | [
"public",
"static",
"cuDoubleComplex",
"cuCmplx",
"(",
"double",
"r",
",",
"double",
"i",
")",
"{",
"cuDoubleComplex",
"res",
"=",
"new",
"cuDoubleComplex",
"(",
")",
";",
"res",
".",
"x",
"=",
"r",
";",
"res",
".",
"y",
"=",
"i",
";",
"return",
"res... | Creates a new complex number consisting of the given real and
imaginary part.
@param r The real part of the complex number
@param i The imaginary part of the complex number
@return A complex number with the given real and imaginary part | [
"Creates",
"a",
"new",
"complex",
"number",
"consisting",
"of",
"the",
"given",
"real",
"and",
"imaginary",
"part",
"."
] | train | https://github.com/jcuda/jcuda/blob/468528b5b9b37dfceb6ed83fcfd889e9b359f984/JCudaJava/src/main/java/jcuda/cuDoubleComplex.java#L77-L83 |
netscaler/sdx_nitro | src/main/java/com/citrix/sdx/nitro/resource/config/mps/sdx_network_config.java | sdx_network_config.get_nitro_bulk_response | protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception
{
sdx_network_config_responses result = (sdx_network_config_responses) service.get_payload_formatter().string_to_resource(sdx_network_config_responses.class, response);
if(result.errorcode != 0)
{
if (result.errorcode == SESSION_NOT_EXISTS)
service.clear_session();
throw new nitro_exception(result.message, result.errorcode, (base_response [])result.sdx_network_config_response_array);
}
sdx_network_config[] result_sdx_network_config = new sdx_network_config[result.sdx_network_config_response_array.length];
for(int i = 0; i < result.sdx_network_config_response_array.length; i++)
{
result_sdx_network_config[i] = result.sdx_network_config_response_array[i].sdx_network_config[0];
}
return result_sdx_network_config;
} | java | protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception
{
sdx_network_config_responses result = (sdx_network_config_responses) service.get_payload_formatter().string_to_resource(sdx_network_config_responses.class, response);
if(result.errorcode != 0)
{
if (result.errorcode == SESSION_NOT_EXISTS)
service.clear_session();
throw new nitro_exception(result.message, result.errorcode, (base_response [])result.sdx_network_config_response_array);
}
sdx_network_config[] result_sdx_network_config = new sdx_network_config[result.sdx_network_config_response_array.length];
for(int i = 0; i < result.sdx_network_config_response_array.length; i++)
{
result_sdx_network_config[i] = result.sdx_network_config_response_array[i].sdx_network_config[0];
}
return result_sdx_network_config;
} | [
"protected",
"base_resource",
"[",
"]",
"get_nitro_bulk_response",
"(",
"nitro_service",
"service",
",",
"String",
"response",
")",
"throws",
"Exception",
"{",
"sdx_network_config_responses",
"result",
"=",
"(",
"sdx_network_config_responses",
")",
"service",
".",
"get_... | <pre>
Converts API response of bulk operation into object and returns the object array in case of get request.
</pre> | [
"<pre",
">",
"Converts",
"API",
"response",
"of",
"bulk",
"operation",
"into",
"object",
"and",
"returns",
"the",
"object",
"array",
"in",
"case",
"of",
"get",
"request",
".",
"<",
"/",
"pre",
">"
] | train | https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/config/mps/sdx_network_config.java#L308-L325 |
carrotsearch/hppc | hppc/src/main/templates/com/carrotsearch/hppc/KTypeArrayDeque.java | KTypeArrayDeque.descendingForEach | private void descendingForEach(KTypeProcedure<? super KType> procedure, int fromIndex, final int toIndex) {
if (fromIndex == toIndex)
return;
final KType[] buffer = Intrinsics.<KType[]> cast(this.buffer);
int i = toIndex;
do {
i = oneLeft(i, buffer.length);
procedure.apply(buffer[i]);
} while (i != fromIndex);
} | java | private void descendingForEach(KTypeProcedure<? super KType> procedure, int fromIndex, final int toIndex) {
if (fromIndex == toIndex)
return;
final KType[] buffer = Intrinsics.<KType[]> cast(this.buffer);
int i = toIndex;
do {
i = oneLeft(i, buffer.length);
procedure.apply(buffer[i]);
} while (i != fromIndex);
} | [
"private",
"void",
"descendingForEach",
"(",
"KTypeProcedure",
"<",
"?",
"super",
"KType",
">",
"procedure",
",",
"int",
"fromIndex",
",",
"final",
"int",
"toIndex",
")",
"{",
"if",
"(",
"fromIndex",
"==",
"toIndex",
")",
"return",
";",
"final",
"KType",
"... | Applies <code>procedure</code> to a slice of the deque,
<code>toIndex</code>, exclusive, down to <code>fromIndex</code>, inclusive. | [
"Applies",
"<code",
">",
"procedure<",
"/",
"code",
">",
"to",
"a",
"slice",
"of",
"the",
"deque",
"<code",
">",
"toIndex<",
"/",
"code",
">",
"exclusive",
"down",
"to",
"<code",
">",
"fromIndex<",
"/",
"code",
">",
"inclusive",
"."
] | train | https://github.com/carrotsearch/hppc/blob/e359e9da358e846fcbffc64a765611df954ba3f6/hppc/src/main/templates/com/carrotsearch/hppc/KTypeArrayDeque.java#L720-L730 |
RobotiumTech/robotium | robotium-solo/src/main/java/com/robotium/solo/Solo.java | Solo.waitForView | public boolean waitForView(Object tag){
if(config.commandLogging){
Log.d(config.commandLoggingTag, "waitForView("+tag+")");
}
return waitForView(tag, 0, Timeout.getLargeTimeout(), true);
} | java | public boolean waitForView(Object tag){
if(config.commandLogging){
Log.d(config.commandLoggingTag, "waitForView("+tag+")");
}
return waitForView(tag, 0, Timeout.getLargeTimeout(), true);
} | [
"public",
"boolean",
"waitForView",
"(",
"Object",
"tag",
")",
"{",
"if",
"(",
"config",
".",
"commandLogging",
")",
"{",
"Log",
".",
"d",
"(",
"config",
".",
"commandLoggingTag",
",",
"\"waitForView(\"",
"+",
"tag",
"+",
"\")\"",
")",
";",
"}",
"return"... | Waits for a View matching the specified tag. Default timeout is 20 seconds.
@param tag the {@link View#getTag() tag} of the {@link View} to wait for
@return {@code true} if the {@link View} is displayed and {@code false} if it is not displayed before the timeout | [
"Waits",
"for",
"a",
"View",
"matching",
"the",
"specified",
"tag",
".",
"Default",
"timeout",
"is",
"20",
"seconds",
"."
] | train | https://github.com/RobotiumTech/robotium/blob/75e567c38f26a6a87dc8bef90b3886a20e28d291/robotium-solo/src/main/java/com/robotium/solo/Solo.java#L506-L512 |
lessthanoptimal/ejml | main/ejml-ddense/src/org/ejml/dense/row/CommonOps_DDRM.java | CommonOps_DDRM.multCols | public static void multCols(DMatrixRMaj A , double values[] ) {
if( values.length < A.numCols ) {
throw new IllegalArgumentException("Not enough elements in values.");
}
int index = 0;
for (int row = 0; row < A.numRows; row++) {
for (int col = 0; col < A.numCols; col++, index++) {
A.data[index] *= values[col];
}
}
} | java | public static void multCols(DMatrixRMaj A , double values[] ) {
if( values.length < A.numCols ) {
throw new IllegalArgumentException("Not enough elements in values.");
}
int index = 0;
for (int row = 0; row < A.numRows; row++) {
for (int col = 0; col < A.numCols; col++, index++) {
A.data[index] *= values[col];
}
}
} | [
"public",
"static",
"void",
"multCols",
"(",
"DMatrixRMaj",
"A",
",",
"double",
"values",
"[",
"]",
")",
"{",
"if",
"(",
"values",
".",
"length",
"<",
"A",
".",
"numCols",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Not enough elements in v... | Multiplies every element in column i by value[i].
@param A Matrix. Modified.
@param values array. Not modified. | [
"Multiplies",
"every",
"element",
"in",
"column",
"i",
"by",
"value",
"[",
"i",
"]",
"."
] | train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/row/CommonOps_DDRM.java#L1786-L1797 |
camunda/camunda-bpm-platform | engine/src/main/java/org/camunda/bpm/engine/impl/pvm/runtime/PvmExecutionImpl.java | PvmExecutionImpl.dispatchDelayedEventsAndPerformOperation | public void dispatchDelayedEventsAndPerformOperation(final Callback<PvmExecutionImpl, Void> continuation) {
PvmExecutionImpl execution = this;
if (execution.getDelayedEvents().isEmpty()) {
continueExecutionIfNotCanceled(continuation, execution);
return;
}
continueIfExecutionDoesNotAffectNextOperation(new Callback<PvmExecutionImpl, Void>() {
@Override
public Void callback(PvmExecutionImpl execution) {
dispatchScopeEvents(execution);
return null;
}
}, new Callback<PvmExecutionImpl, Void>(){
@Override
public Void callback(PvmExecutionImpl execution) {
continueExecutionIfNotCanceled(continuation, execution);
return null;
}
}, execution);
} | java | public void dispatchDelayedEventsAndPerformOperation(final Callback<PvmExecutionImpl, Void> continuation) {
PvmExecutionImpl execution = this;
if (execution.getDelayedEvents().isEmpty()) {
continueExecutionIfNotCanceled(continuation, execution);
return;
}
continueIfExecutionDoesNotAffectNextOperation(new Callback<PvmExecutionImpl, Void>() {
@Override
public Void callback(PvmExecutionImpl execution) {
dispatchScopeEvents(execution);
return null;
}
}, new Callback<PvmExecutionImpl, Void>(){
@Override
public Void callback(PvmExecutionImpl execution) {
continueExecutionIfNotCanceled(continuation, execution);
return null;
}
}, execution);
} | [
"public",
"void",
"dispatchDelayedEventsAndPerformOperation",
"(",
"final",
"Callback",
"<",
"PvmExecutionImpl",
",",
"Void",
">",
"continuation",
")",
"{",
"PvmExecutionImpl",
"execution",
"=",
"this",
";",
"if",
"(",
"execution",
".",
"getDelayedEvents",
"(",
")",... | Dispatches the current delayed variable events and performs the given atomic operation
if the current state was not changed.
@param continuation the atomic operation continuation which should be executed | [
"Dispatches",
"the",
"current",
"delayed",
"variable",
"events",
"and",
"performs",
"the",
"given",
"atomic",
"operation",
"if",
"the",
"current",
"state",
"was",
"not",
"changed",
"."
] | train | https://github.com/camunda/camunda-bpm-platform/blob/1a464fc887ef3760e53d6f91b9e5b871a0d77cc0/engine/src/main/java/org/camunda/bpm/engine/impl/pvm/runtime/PvmExecutionImpl.java#L1937-L1958 |
maguro/aunit | junit/src/main/java/com/toolazydogs/aunit/internal/Util.java | Util.validateIsStatic | @SuppressWarnings({"ThrowableInstanceNeverThrown"})
public static void validateIsStatic(Method method, List<Throwable> errors)
{
if (!Modifier.isStatic(method.getModifiers()))
{
errors.add(new Exception("Method " + method.getName() + "() should be static"));
}
if (!Modifier.isPublic(method.getDeclaringClass().getModifiers()))
{
errors.add(new Exception("Class " + method.getDeclaringClass().getName() + " should be public"));
}
} | java | @SuppressWarnings({"ThrowableInstanceNeverThrown"})
public static void validateIsStatic(Method method, List<Throwable> errors)
{
if (!Modifier.isStatic(method.getModifiers()))
{
errors.add(new Exception("Method " + method.getName() + "() should be static"));
}
if (!Modifier.isPublic(method.getDeclaringClass().getModifiers()))
{
errors.add(new Exception("Class " + method.getDeclaringClass().getName() + " should be public"));
}
} | [
"@",
"SuppressWarnings",
"(",
"{",
"\"ThrowableInstanceNeverThrown\"",
"}",
")",
"public",
"static",
"void",
"validateIsStatic",
"(",
"Method",
"method",
",",
"List",
"<",
"Throwable",
">",
"errors",
")",
"{",
"if",
"(",
"!",
"Modifier",
".",
"isStatic",
"(",
... | Validate that a method is static.
@param method the method to be tested
@param errors a list to place the errors | [
"Validate",
"that",
"a",
"method",
"is",
"static",
"."
] | train | https://github.com/maguro/aunit/blob/1f972e35b28327e5e2e7881befc928df0546d74c/junit/src/main/java/com/toolazydogs/aunit/internal/Util.java#L85-L96 |
Azure/azure-sdk-for-java | sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/JobStepsInner.java | JobStepsInner.createOrUpdate | public JobStepInner createOrUpdate(String resourceGroupName, String serverName, String jobAgentName, String jobName, String stepName, JobStepInner parameters) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, jobAgentName, jobName, stepName, parameters).toBlocking().single().body();
} | java | public JobStepInner createOrUpdate(String resourceGroupName, String serverName, String jobAgentName, String jobName, String stepName, JobStepInner parameters) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, jobAgentName, jobName, stepName, parameters).toBlocking().single().body();
} | [
"public",
"JobStepInner",
"createOrUpdate",
"(",
"String",
"resourceGroupName",
",",
"String",
"serverName",
",",
"String",
"jobAgentName",
",",
"String",
"jobName",
",",
"String",
"stepName",
",",
"JobStepInner",
"parameters",
")",
"{",
"return",
"createOrUpdateWithS... | Creates or updates a job step. This will implicitly create a new job version.
@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 jobAgentName The name of the job agent.
@param jobName The name of the job.
@param stepName The name of the job step.
@param parameters The requested state of the job step.
@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 JobStepInner object if successful. | [
"Creates",
"or",
"updates",
"a",
"job",
"step",
".",
"This",
"will",
"implicitly",
"create",
"a",
"new",
"job",
"version",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/JobStepsInner.java#L613-L615 |
liyiorg/weixin-popular | src/main/java/weixin/popular/client/LocalHttpClient.java | LocalHttpClient.initMchKeyStore | public static void initMchKeyStore(String mch_id, InputStream inputStream) {
try {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(inputStream,mch_id.toCharArray());
inputStream.close();
CloseableHttpClient httpClient = HttpClientFactory.createKeyMaterialHttpClient(keyStore, mch_id,timeout,retryExecutionCount);
httpClient_mchKeyStore.put(mch_id, httpClient);
} catch (Exception e) {
logger.error("init mch error", e);
}
} | java | public static void initMchKeyStore(String mch_id, InputStream inputStream) {
try {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(inputStream,mch_id.toCharArray());
inputStream.close();
CloseableHttpClient httpClient = HttpClientFactory.createKeyMaterialHttpClient(keyStore, mch_id,timeout,retryExecutionCount);
httpClient_mchKeyStore.put(mch_id, httpClient);
} catch (Exception e) {
logger.error("init mch error", e);
}
} | [
"public",
"static",
"void",
"initMchKeyStore",
"(",
"String",
"mch_id",
",",
"InputStream",
"inputStream",
")",
"{",
"try",
"{",
"KeyStore",
"keyStore",
"=",
"KeyStore",
".",
"getInstance",
"(",
"\"PKCS12\"",
")",
";",
"keyStore",
".",
"load",
"(",
"inputStrea... | 初始化 MCH HttpClient KeyStore
@since 2.8.7
@param mch_id mch_id
@param inputStream p12 文件流 | [
"初始化",
"MCH",
"HttpClient",
"KeyStore"
] | train | https://github.com/liyiorg/weixin-popular/blob/c64255292d41463bdb671938feaabf42a335d82c/src/main/java/weixin/popular/client/LocalHttpClient.java#L103-L113 |
HadoopGenomics/Hadoop-BAM | src/main/java/org/seqdoop/hadoop_bam/BAMRecordReader.java | BAMRecordReader.getKey | public static long getKey(final SAMRecord rec) {
final int refIdx = rec.getReferenceIndex();
final int start = rec.getAlignmentStart();
if (!(rec.getReadUnmappedFlag() || refIdx < 0 || start < 0))
return getKey(refIdx, start);
// Put unmapped reads at the end, but don't give them all the exact same
// key so that they can be distributed to different reducers.
//
// A random number would probably be best, but to ensure that the same
// record always gets the same key we use a fast hash instead.
//
// We avoid using hashCode(), because it's not guaranteed to have the
// same value across different processes.
int hash = 0;
byte[] var;
if ((var = rec.getVariableBinaryRepresentation()) != null) {
// Undecoded BAM record: just hash its raw data.
hash = (int)MurmurHash3.murmurhash3(var, hash);
} else {
// Decoded BAM record or any SAM record: hash a few representative
// fields together.
hash = (int)MurmurHash3.murmurhash3(rec.getReadName(), hash);
hash = (int)MurmurHash3.murmurhash3(rec.getReadBases(), hash);
hash = (int)MurmurHash3.murmurhash3(rec.getBaseQualities(), hash);
hash = (int)MurmurHash3.murmurhash3(rec.getCigarString(), hash);
}
return getKey0(Integer.MAX_VALUE, hash);
} | java | public static long getKey(final SAMRecord rec) {
final int refIdx = rec.getReferenceIndex();
final int start = rec.getAlignmentStart();
if (!(rec.getReadUnmappedFlag() || refIdx < 0 || start < 0))
return getKey(refIdx, start);
// Put unmapped reads at the end, but don't give them all the exact same
// key so that they can be distributed to different reducers.
//
// A random number would probably be best, but to ensure that the same
// record always gets the same key we use a fast hash instead.
//
// We avoid using hashCode(), because it's not guaranteed to have the
// same value across different processes.
int hash = 0;
byte[] var;
if ((var = rec.getVariableBinaryRepresentation()) != null) {
// Undecoded BAM record: just hash its raw data.
hash = (int)MurmurHash3.murmurhash3(var, hash);
} else {
// Decoded BAM record or any SAM record: hash a few representative
// fields together.
hash = (int)MurmurHash3.murmurhash3(rec.getReadName(), hash);
hash = (int)MurmurHash3.murmurhash3(rec.getReadBases(), hash);
hash = (int)MurmurHash3.murmurhash3(rec.getBaseQualities(), hash);
hash = (int)MurmurHash3.murmurhash3(rec.getCigarString(), hash);
}
return getKey0(Integer.MAX_VALUE, hash);
} | [
"public",
"static",
"long",
"getKey",
"(",
"final",
"SAMRecord",
"rec",
")",
"{",
"final",
"int",
"refIdx",
"=",
"rec",
".",
"getReferenceIndex",
"(",
")",
";",
"final",
"int",
"start",
"=",
"rec",
".",
"getAlignmentStart",
"(",
")",
";",
"if",
"(",
"!... | Note: this is the only getKey function that handles unmapped reads
specially! | [
"Note",
":",
"this",
"is",
"the",
"only",
"getKey",
"function",
"that",
"handles",
"unmapped",
"reads",
"specially!"
] | train | https://github.com/HadoopGenomics/Hadoop-BAM/blob/9f974cf635a8d72f69604021cc3d5f3469d38d2f/src/main/java/org/seqdoop/hadoop_bam/BAMRecordReader.java#L80-L110 |
javalite/activejdbc | javalite-common/src/main/java/org/javalite/common/Util.java | Util.joinAndRepeat | public static void joinAndRepeat(StringBuilder sb, String str, String delimiter, int count) {
if (count > 0) {
sb.append(str);
for (int i = 1; i < count; i++) {
sb.append(delimiter);
sb.append(str);
}
}
} | java | public static void joinAndRepeat(StringBuilder sb, String str, String delimiter, int count) {
if (count > 0) {
sb.append(str);
for (int i = 1; i < count; i++) {
sb.append(delimiter);
sb.append(str);
}
}
} | [
"public",
"static",
"void",
"joinAndRepeat",
"(",
"StringBuilder",
"sb",
",",
"String",
"str",
",",
"String",
"delimiter",
",",
"int",
"count",
")",
"{",
"if",
"(",
"count",
">",
"0",
")",
"{",
"sb",
".",
"append",
"(",
"str",
")",
";",
"for",
"(",
... | Repeats string of characters a defined number of times with a delimiter, and appends result to StringBuilder.
<p>For example, <tt>joinAndRepeat(sb, "?", ",", 3)</tt> will append <tt>"?,?,?"</tt> to <tt>sb</tt>.
@param sb StringBuilder to append result to
@param str string of characters to be repeated.
@param delimiter delimiter to insert between repeated items.
@param count number of times to repeat, zero or a negative number produces no result | [
"Repeats",
"string",
"of",
"characters",
"a",
"defined",
"number",
"of",
"times",
"with",
"a",
"delimiter",
"and",
"appends",
"result",
"to",
"StringBuilder",
"."
] | train | https://github.com/javalite/activejdbc/blob/ffcf5457cace19622a8f71e856cbbbe9e7dd5fcc/javalite-common/src/main/java/org/javalite/common/Util.java#L387-L395 |
bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/protocols/channels/PaymentChannelClient.java | PaymentChannelClient.incrementPayment | @Override
public ListenableFuture<PaymentIncrementAck> incrementPayment(Coin size, @Nullable ByteString info, @Nullable KeyParameter userKey)
throws ValueOutOfRangeException, IllegalStateException, ECKey.KeyIsEncryptedException {
lock.lock();
try {
if (state() == null || !connectionOpen || step != InitStep.CHANNEL_OPEN)
throw new IllegalStateException("Channel is not fully initialized/has already been closed");
if (increasePaymentFuture != null)
throw new IllegalStateException("Already incrementing paying, wait for previous payment to complete.");
if (wallet.isEncrypted() && userKey == null)
throw new ECKey.KeyIsEncryptedException();
PaymentChannelV1ClientState.IncrementedPayment payment = state().incrementPaymentBy(size, userKey);
Protos.UpdatePayment.Builder updatePaymentBuilder = Protos.UpdatePayment.newBuilder()
.setSignature(ByteString.copyFrom(payment.signature.encodeToBitcoin()))
.setClientChangeValue(state.getValueRefunded().value);
if (info != null) updatePaymentBuilder.setInfo(info);
increasePaymentFuture = SettableFuture.create();
increasePaymentFuture.addListener(new Runnable() {
@Override
public void run() {
lock.lock();
increasePaymentFuture = null;
lock.unlock();
}
}, MoreExecutors.directExecutor());
conn.sendToServer(Protos.TwoWayChannelMessage.newBuilder()
.setUpdatePayment(updatePaymentBuilder)
.setType(Protos.TwoWayChannelMessage.MessageType.UPDATE_PAYMENT)
.build());
lastPaymentActualAmount = payment.amount;
return increasePaymentFuture;
} finally {
lock.unlock();
}
} | java | @Override
public ListenableFuture<PaymentIncrementAck> incrementPayment(Coin size, @Nullable ByteString info, @Nullable KeyParameter userKey)
throws ValueOutOfRangeException, IllegalStateException, ECKey.KeyIsEncryptedException {
lock.lock();
try {
if (state() == null || !connectionOpen || step != InitStep.CHANNEL_OPEN)
throw new IllegalStateException("Channel is not fully initialized/has already been closed");
if (increasePaymentFuture != null)
throw new IllegalStateException("Already incrementing paying, wait for previous payment to complete.");
if (wallet.isEncrypted() && userKey == null)
throw new ECKey.KeyIsEncryptedException();
PaymentChannelV1ClientState.IncrementedPayment payment = state().incrementPaymentBy(size, userKey);
Protos.UpdatePayment.Builder updatePaymentBuilder = Protos.UpdatePayment.newBuilder()
.setSignature(ByteString.copyFrom(payment.signature.encodeToBitcoin()))
.setClientChangeValue(state.getValueRefunded().value);
if (info != null) updatePaymentBuilder.setInfo(info);
increasePaymentFuture = SettableFuture.create();
increasePaymentFuture.addListener(new Runnable() {
@Override
public void run() {
lock.lock();
increasePaymentFuture = null;
lock.unlock();
}
}, MoreExecutors.directExecutor());
conn.sendToServer(Protos.TwoWayChannelMessage.newBuilder()
.setUpdatePayment(updatePaymentBuilder)
.setType(Protos.TwoWayChannelMessage.MessageType.UPDATE_PAYMENT)
.build());
lastPaymentActualAmount = payment.amount;
return increasePaymentFuture;
} finally {
lock.unlock();
}
} | [
"@",
"Override",
"public",
"ListenableFuture",
"<",
"PaymentIncrementAck",
">",
"incrementPayment",
"(",
"Coin",
"size",
",",
"@",
"Nullable",
"ByteString",
"info",
",",
"@",
"Nullable",
"KeyParameter",
"userKey",
")",
"throws",
"ValueOutOfRangeException",
",",
"Ill... | Increments the total value which we pay the server. Note that the amount of money sent may not be the same as the
amount of money actually requested. It can be larger if the amount left over in the channel would be too small to
be accepted by the Bitcoin network. ValueOutOfRangeException will be thrown, however, if there's not enough money
left in the channel to make the payment at all. Only one payment can be in-flight at once. You have to ensure
you wait for the previous increase payment future to complete before incrementing the payment again.
@param size How many satoshis to increment the payment by (note: not the new total).
@param info Information about this update, used to extend this protocol.
@param userKey Key derived from a user password, needed for any signing when the wallet is encrypted.
The wallet KeyCrypter is assumed.
@return a future that completes when the server acknowledges receipt and acceptance of the payment.
@throws ValueOutOfRangeException If the size is negative or would pay more than this channel's total value
({@link PaymentChannelClientConnection#state()}.getTotalValue())
@throws IllegalStateException If the channel has been closed or is not yet open
(see {@link PaymentChannelClientConnection#getChannelOpenFuture()} for the second)
@throws ECKey.KeyIsEncryptedException If the keys are encrypted and no AES key has been provided, | [
"Increments",
"the",
"total",
"value",
"which",
"we",
"pay",
"the",
"server",
".",
"Note",
"that",
"the",
"amount",
"of",
"money",
"sent",
"may",
"not",
"be",
"the",
"same",
"as",
"the",
"amount",
"of",
"money",
"actually",
"requested",
".",
"It",
"can",... | train | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/protocols/channels/PaymentChannelClient.java#L671-L708 |
skyscreamer/JSONassert | src/main/java/org/skyscreamer/jsonassert/JSONAssert.java | JSONAssert.assertEquals | public static void assertEquals(String expectedStr, String actualStr, JSONComparator comparator)
throws JSONException {
assertEquals("", expectedStr, actualStr, comparator);
} | java | public static void assertEquals(String expectedStr, String actualStr, JSONComparator comparator)
throws JSONException {
assertEquals("", expectedStr, actualStr, comparator);
} | [
"public",
"static",
"void",
"assertEquals",
"(",
"String",
"expectedStr",
",",
"String",
"actualStr",
",",
"JSONComparator",
"comparator",
")",
"throws",
"JSONException",
"{",
"assertEquals",
"(",
"\"\"",
",",
"expectedStr",
",",
"actualStr",
",",
"comparator",
")... | Asserts that the json string provided matches the expected string. If it isn't it throws an
{@link AssertionError}.
@param expectedStr Expected JSON string
@param actualStr String to compare
@param comparator Comparator
@throws JSONException JSON parsing error | [
"Asserts",
"that",
"the",
"json",
"string",
"provided",
"matches",
"the",
"expected",
"string",
".",
"If",
"it",
"isn",
"t",
"it",
"throws",
"an",
"{",
"@link",
"AssertionError",
"}",
"."
] | train | https://github.com/skyscreamer/JSONassert/blob/830efcf546d07f955d8a213cc5c8a1db34d78f04/src/main/java/org/skyscreamer/jsonassert/JSONAssert.java#L462-L466 |
gallandarakhneorg/afc | core/maths/mathphysics/src/main/java/org/arakhne/afc/math/physics/MeasureUnitUtil.java | MeasureUnitUtil.fromRadiansPerSecond | @Pure
public static double fromRadiansPerSecond(double value, AngularUnit outputUnit) {
switch (outputUnit) {
case TURNS_PER_SECOND:
return value / (2. * MathConstants.PI);
case DEGREES_PER_SECOND:
return Math.toDegrees(value);
case RADIANS_PER_SECOND:
default:
}
return value;
} | java | @Pure
public static double fromRadiansPerSecond(double value, AngularUnit outputUnit) {
switch (outputUnit) {
case TURNS_PER_SECOND:
return value / (2. * MathConstants.PI);
case DEGREES_PER_SECOND:
return Math.toDegrees(value);
case RADIANS_PER_SECOND:
default:
}
return value;
} | [
"@",
"Pure",
"public",
"static",
"double",
"fromRadiansPerSecond",
"(",
"double",
"value",
",",
"AngularUnit",
"outputUnit",
")",
"{",
"switch",
"(",
"outputUnit",
")",
"{",
"case",
"TURNS_PER_SECOND",
":",
"return",
"value",
"/",
"(",
"2.",
"*",
"MathConstant... | Convert the given value expressed in radians per second to the given unit.
@param value is the value to convert
@param outputUnit is the unit of result.
@return the result of the convertion. | [
"Convert",
"the",
"given",
"value",
"expressed",
"in",
"radians",
"per",
"second",
"to",
"the",
"given",
"unit",
"."
] | train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/maths/mathphysics/src/main/java/org/arakhne/afc/math/physics/MeasureUnitUtil.java#L677-L688 |
orbisgis/h2gis | postgis-jts/src/main/java/org/h2gis/postgis_jts/JtsBinaryParser.java | JtsBinaryParser.parseCS | private CoordinateSequence parseCS(ValueGetter data, boolean haveZ, boolean haveM) {
int count = data.getInt();
int dims = haveZ ? 3 : 2;
CoordinateSequence cs = new Double(count, dims);
for(int i = 0; i < count; ++i) {
for(int d = 0; d < dims; ++d) {
cs.setOrdinate(i, d, data.getDouble());
}
if (haveM) {
data.getDouble();
}
}
return cs;
} | java | private CoordinateSequence parseCS(ValueGetter data, boolean haveZ, boolean haveM) {
int count = data.getInt();
int dims = haveZ ? 3 : 2;
CoordinateSequence cs = new Double(count, dims);
for(int i = 0; i < count; ++i) {
for(int d = 0; d < dims; ++d) {
cs.setOrdinate(i, d, data.getDouble());
}
if (haveM) {
data.getDouble();
}
}
return cs;
} | [
"private",
"CoordinateSequence",
"parseCS",
"(",
"ValueGetter",
"data",
",",
"boolean",
"haveZ",
",",
"boolean",
"haveM",
")",
"{",
"int",
"count",
"=",
"data",
".",
"getInt",
"(",
")",
";",
"int",
"dims",
"=",
"haveZ",
"?",
"3",
":",
"2",
";",
"Coordi... | Parse the given {@link org.postgis.binary.ValueGetter} into a JTS
{@link org.locationtech.jts.geom.CoordinateSequence}.
@param data {@link org.postgis.binary.ValueGetter} to parse.
@param haveZ True if the {@link org.locationtech.jts.geom.CoordinateSequence} has a Z component.
@param haveM True if the {@link org.locationtech.jts.geom.CoordinateSequence} has a M component.
@return The parsed {@link org.locationtech.jts.geom.CoordinateSequence}. | [
"Parse",
"the",
"given",
"{",
"@link",
"org",
".",
"postgis",
".",
"binary",
".",
"ValueGetter",
"}",
"into",
"a",
"JTS",
"{",
"@link",
"org",
".",
"locationtech",
".",
"jts",
".",
"geom",
".",
"CoordinateSequence",
"}",
"."
] | train | https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/postgis-jts/src/main/java/org/h2gis/postgis_jts/JtsBinaryParser.java#L210-L226 |
spring-projects/spring-android | spring-android-rest-template/src/main/java/org/springframework/http/client/HttpComponentsClientHttpRequest.java | HttpComponentsClientHttpRequest.addHeaders | static void addHeaders(HttpUriRequest httpRequest, HttpHeaders headers) {
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
String headerName = entry.getKey();
if (HttpHeaders.COOKIE.equalsIgnoreCase(headerName)) { // RFC 6265
String headerValue = StringUtils.collectionToDelimitedString(entry.getValue(), "; ");
httpRequest.addHeader(headerName, headerValue);
}
else if (!HTTP.CONTENT_LEN.equalsIgnoreCase(headerName) &&
!HTTP.TRANSFER_ENCODING.equalsIgnoreCase(headerName)) {
for (String headerValue : entry.getValue()) {
httpRequest.addHeader(headerName, headerValue);
}
}
}
} | java | static void addHeaders(HttpUriRequest httpRequest, HttpHeaders headers) {
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
String headerName = entry.getKey();
if (HttpHeaders.COOKIE.equalsIgnoreCase(headerName)) { // RFC 6265
String headerValue = StringUtils.collectionToDelimitedString(entry.getValue(), "; ");
httpRequest.addHeader(headerName, headerValue);
}
else if (!HTTP.CONTENT_LEN.equalsIgnoreCase(headerName) &&
!HTTP.TRANSFER_ENCODING.equalsIgnoreCase(headerName)) {
for (String headerValue : entry.getValue()) {
httpRequest.addHeader(headerName, headerValue);
}
}
}
} | [
"static",
"void",
"addHeaders",
"(",
"HttpUriRequest",
"httpRequest",
",",
"HttpHeaders",
"headers",
")",
"{",
"for",
"(",
"Map",
".",
"Entry",
"<",
"String",
",",
"List",
"<",
"String",
">",
">",
"entry",
":",
"headers",
".",
"entrySet",
"(",
")",
")",
... | Add the given headers to the given HTTP request.
@param httpRequest the request to add the headers to
@param headers the headers to add | [
"Add",
"the",
"given",
"headers",
"to",
"the",
"given",
"HTTP",
"request",
"."
] | train | https://github.com/spring-projects/spring-android/blob/941296e152d49a40e0745a3e81628a974f72b7e4/spring-android-rest-template/src/main/java/org/springframework/http/client/HttpComponentsClientHttpRequest.java#L101-L115 |
Samsung/GearVRf | GVRf/Framework/framework/src/main/java/org/gearvrf/animation/keyframe/GVRSkeletonAnimation.java | GVRSkeletonAnimation.createSkeleton | public GVRSkeleton createSkeleton(List<String> boneNames)
{
int numBones = boneNames.size();
GVRSceneObject root = (GVRSceneObject) mTarget;
mSkeleton = new GVRSkeleton(root, boneNames);
for (int boneId = 0; boneId < numBones; ++boneId)
{
mSkeleton.setBoneOptions(boneId, GVRSkeleton.BONE_ANIMATE);
}
mBoneChannels = new GVRAnimationChannel[numBones];
return mSkeleton;
} | java | public GVRSkeleton createSkeleton(List<String> boneNames)
{
int numBones = boneNames.size();
GVRSceneObject root = (GVRSceneObject) mTarget;
mSkeleton = new GVRSkeleton(root, boneNames);
for (int boneId = 0; boneId < numBones; ++boneId)
{
mSkeleton.setBoneOptions(boneId, GVRSkeleton.BONE_ANIMATE);
}
mBoneChannels = new GVRAnimationChannel[numBones];
return mSkeleton;
} | [
"public",
"GVRSkeleton",
"createSkeleton",
"(",
"List",
"<",
"String",
">",
"boneNames",
")",
"{",
"int",
"numBones",
"=",
"boneNames",
".",
"size",
"(",
")",
";",
"GVRSceneObject",
"root",
"=",
"(",
"GVRSceneObject",
")",
"mTarget",
";",
"mSkeleton",
"=",
... | Create a skeleton from the target hierarchy which has the given bones.
<p>
The structure of the target hierarchy is used to determine bone parentage.
The skeleton will have only the bones designated in the list.
The hierarchy is expected to be connected with no gaps or unnamed nodes.
@param boneNames names of bones in the skeleton.
@return {@link GVRSkeleton} created from the target hierarchy. | [
"Create",
"a",
"skeleton",
"from",
"the",
"target",
"hierarchy",
"which",
"has",
"the",
"given",
"bones",
".",
"<p",
">",
"The",
"structure",
"of",
"the",
"target",
"hierarchy",
"is",
"used",
"to",
"determine",
"bone",
"parentage",
".",
"The",
"skeleton",
... | train | https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Framework/framework/src/main/java/org/gearvrf/animation/keyframe/GVRSkeletonAnimation.java#L157-L168 |
EdwardRaff/JSAT | JSAT/src/jsat/classifiers/linear/SDCA.java | SDCA.setLambda | @Parameter.WarmParameter(prefLowToHigh = false)
public void setLambda(double lambda)
{
if(lambda <= 0 || Double.isInfinite(lambda) || Double.isNaN(lambda))
throw new IllegalArgumentException("Regularization term lambda must be a positive value, not " + lambda);
this.lambda = lambda;
} | java | @Parameter.WarmParameter(prefLowToHigh = false)
public void setLambda(double lambda)
{
if(lambda <= 0 || Double.isInfinite(lambda) || Double.isNaN(lambda))
throw new IllegalArgumentException("Regularization term lambda must be a positive value, not " + lambda);
this.lambda = lambda;
} | [
"@",
"Parameter",
".",
"WarmParameter",
"(",
"prefLowToHigh",
"=",
"false",
")",
"public",
"void",
"setLambda",
"(",
"double",
"lambda",
")",
"{",
"if",
"(",
"lambda",
"<=",
"0",
"||",
"Double",
".",
"isInfinite",
"(",
"lambda",
")",
"||",
"Double",
".",... | Sets the regularization term, where larger values indicate a larger
regularization penalty.
@param lambda the positive regularization term | [
"Sets",
"the",
"regularization",
"term",
"where",
"larger",
"values",
"indicate",
"a",
"larger",
"regularization",
"penalty",
"."
] | train | https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/classifiers/linear/SDCA.java#L172-L178 |
actframework/actframework | src/main/java/act/internal/util/AppDescriptor.java | AppDescriptor.of | public static AppDescriptor of(String appName, Class<?> entryClass, Version appVersion) {
return new AppDescriptor(ensureAppName(appName, entryClass, $.requireNotNull(appVersion)),
JavaNames.packageNameOf(entryClass),
appVersion);
} | java | public static AppDescriptor of(String appName, Class<?> entryClass, Version appVersion) {
return new AppDescriptor(ensureAppName(appName, entryClass, $.requireNotNull(appVersion)),
JavaNames.packageNameOf(entryClass),
appVersion);
} | [
"public",
"static",
"AppDescriptor",
"of",
"(",
"String",
"appName",
",",
"Class",
"<",
"?",
">",
"entryClass",
",",
"Version",
"appVersion",
")",
"{",
"return",
"new",
"AppDescriptor",
"(",
"ensureAppName",
"(",
"appName",
",",
"entryClass",
",",
"$",
".",
... | Create an `AppDescriptor` with appName, entry class and app version.
If `appName` is `null` or blank, it will try the following
approach to get app name:
1. check the {@link Version#getArtifactId() artifact id} and use it unless
2. if artifact id is null or empty, then infer app name using {@link AppNameInferer}
@param appName
the app name, optional
@param entryClass
the entry class
@param appVersion
the app version
@return
an `AppDescriptor` | [
"Create",
"an",
"AppDescriptor",
"with",
"appName",
"entry",
"class",
"and",
"app",
"version",
"."
] | train | https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/internal/util/AppDescriptor.java#L174-L178 |
orbisgis/h2gis | h2gis-functions/src/main/java/org/h2gis/functions/io/geojson/GeoJsonWrite.java | GeoJsonWrite.writeGeoJson | public static void writeGeoJson(Connection connection, String fileName, String tableReference, String encoding) throws IOException, SQLException {
GeoJsonDriverFunction geoJsonDriver = new GeoJsonDriverFunction();
geoJsonDriver.exportTable(connection,tableReference, URIUtilities.fileFromString(fileName), new EmptyProgressVisitor(),encoding);
} | java | public static void writeGeoJson(Connection connection, String fileName, String tableReference, String encoding) throws IOException, SQLException {
GeoJsonDriverFunction geoJsonDriver = new GeoJsonDriverFunction();
geoJsonDriver.exportTable(connection,tableReference, URIUtilities.fileFromString(fileName), new EmptyProgressVisitor(),encoding);
} | [
"public",
"static",
"void",
"writeGeoJson",
"(",
"Connection",
"connection",
",",
"String",
"fileName",
",",
"String",
"tableReference",
",",
"String",
"encoding",
")",
"throws",
"IOException",
",",
"SQLException",
"{",
"GeoJsonDriverFunction",
"geoJsonDriver",
"=",
... | Write the GeoJSON file.
@param connection
@param fileName
@param tableReference
@param encoding
@throws IOException
@throws SQLException | [
"Write",
"the",
"GeoJSON",
"file",
"."
] | train | https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/io/geojson/GeoJsonWrite.java#L59-L62 |
actorapp/actor-platform | actor-sdk/sdk-core/runtime/runtime-shared/src/main/java/im/actor/runtime/actors/Actor.java | Actor.initActor | public final void initActor(String path, ActorContext context, Mailbox mailbox) {
this.path = path;
this.context = context;
this.mailbox = mailbox;
} | java | public final void initActor(String path, ActorContext context, Mailbox mailbox) {
this.path = path;
this.context = context;
this.mailbox = mailbox;
} | [
"public",
"final",
"void",
"initActor",
"(",
"String",
"path",
",",
"ActorContext",
"context",
",",
"Mailbox",
"mailbox",
")",
"{",
"this",
".",
"path",
"=",
"path",
";",
"this",
".",
"context",
"=",
"context",
";",
"this",
".",
"mailbox",
"=",
"mailbox"... | <p>INTERNAL API</p>
Initialization of actor
@param path path of actor
@param context context of actor
@param mailbox mailbox of actor | [
"<p",
">",
"INTERNAL",
"API<",
"/",
"p",
">",
"Initialization",
"of",
"actor"
] | train | https://github.com/actorapp/actor-platform/blob/5123c1584757c6eeea0ed2a0e7e043629871a0c6/actor-sdk/sdk-core/runtime/runtime-shared/src/main/java/im/actor/runtime/actors/Actor.java#L51-L55 |
Azure/azure-sdk-for-java | cosmosdb/resource-manager/v2015_04_08/src/main/java/com/microsoft/azure/management/cosmosdb/v2015_04_08/implementation/DatabaseAccountsInner.java | DatabaseAccountsInner.listReadOnlyKeys | public DatabaseAccountListReadOnlyKeysResultInner listReadOnlyKeys(String resourceGroupName, String accountName) {
return listReadOnlyKeysWithServiceResponseAsync(resourceGroupName, accountName).toBlocking().single().body();
} | java | public DatabaseAccountListReadOnlyKeysResultInner listReadOnlyKeys(String resourceGroupName, String accountName) {
return listReadOnlyKeysWithServiceResponseAsync(resourceGroupName, accountName).toBlocking().single().body();
} | [
"public",
"DatabaseAccountListReadOnlyKeysResultInner",
"listReadOnlyKeys",
"(",
"String",
"resourceGroupName",
",",
"String",
"accountName",
")",
"{",
"return",
"listReadOnlyKeysWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"accountName",
")",
".",
"toBlocking",
... | Lists the read-only access keys for the specified Azure Cosmos DB database account.
@param resourceGroupName Name of an Azure resource group.
@param accountName Cosmos DB database account name.
@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 DatabaseAccountListReadOnlyKeysResultInner object if successful. | [
"Lists",
"the",
"read",
"-",
"only",
"access",
"keys",
"for",
"the",
"specified",
"Azure",
"Cosmos",
"DB",
"database",
"account",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cosmosdb/resource-manager/v2015_04_08/src/main/java/com/microsoft/azure/management/cosmosdb/v2015_04_08/implementation/DatabaseAccountsInner.java#L1714-L1716 |
msteiger/jxmapviewer2 | jxmapviewer2/src/main/java/org/jxmapviewer/util/ShapeUtils.java | ShapeUtils.generatePolygon | public static Shape generatePolygon(int sides, int outsideRadius, int insideRadius) {
if (sides < 3) {
return new Ellipse2D.Float(0, 0, 10, 10);
}
AffineTransform trans = new AffineTransform();
Polygon poly = new Polygon();
for (int i = 0; i < sides; i++) {
trans.rotate(Math.PI * 2 / sides / 2);
Point2D out = trans.transform(new Point2D.Float(0, outsideRadius), null);
poly.addPoint((int) out.getX(), (int) out.getY());
trans.rotate(Math.PI * 2 / sides / 2);
if (insideRadius > 0) {
Point2D in = trans.transform(new Point2D.Float(0, insideRadius), null);
poly.addPoint((int) in.getX(), (int) in.getY());
}
}
return poly;
} | java | public static Shape generatePolygon(int sides, int outsideRadius, int insideRadius) {
if (sides < 3) {
return new Ellipse2D.Float(0, 0, 10, 10);
}
AffineTransform trans = new AffineTransform();
Polygon poly = new Polygon();
for (int i = 0; i < sides; i++) {
trans.rotate(Math.PI * 2 / sides / 2);
Point2D out = trans.transform(new Point2D.Float(0, outsideRadius), null);
poly.addPoint((int) out.getX(), (int) out.getY());
trans.rotate(Math.PI * 2 / sides / 2);
if (insideRadius > 0) {
Point2D in = trans.transform(new Point2D.Float(0, insideRadius), null);
poly.addPoint((int) in.getX(), (int) in.getY());
}
}
return poly;
} | [
"public",
"static",
"Shape",
"generatePolygon",
"(",
"int",
"sides",
",",
"int",
"outsideRadius",
",",
"int",
"insideRadius",
")",
"{",
"if",
"(",
"sides",
"<",
"3",
")",
"{",
"return",
"new",
"Ellipse2D",
".",
"Float",
"(",
"0",
",",
"0",
",",
"10",
... | Generates a polygon
@param sides number of sides
@param outsideRadius the outside radius
@param insideRadius the inside radius
@return the generated shape | [
"Generates",
"a",
"polygon"
] | train | https://github.com/msteiger/jxmapviewer2/blob/82639273b0aac983b6026fb90aa925c0cf596410/jxmapviewer2/src/main/java/org/jxmapviewer/util/ShapeUtils.java#L85-L104 |
google/j2objc | xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/utils/SystemIDResolver.java | SystemIDResolver.getAbsoluteURI | public static String getAbsoluteURI(String urlString, String base)
throws TransformerException
{
if (base == null)
return getAbsoluteURI(urlString);
String absoluteBase = getAbsoluteURI(base);
URI uri = null;
try
{
URI baseURI = new URI(absoluteBase);
uri = new URI(baseURI, urlString);
}
catch (MalformedURIException mue)
{
throw new TransformerException(mue);
}
return replaceChars(uri.toString());
} | java | public static String getAbsoluteURI(String urlString, String base)
throws TransformerException
{
if (base == null)
return getAbsoluteURI(urlString);
String absoluteBase = getAbsoluteURI(base);
URI uri = null;
try
{
URI baseURI = new URI(absoluteBase);
uri = new URI(baseURI, urlString);
}
catch (MalformedURIException mue)
{
throw new TransformerException(mue);
}
return replaceChars(uri.toString());
} | [
"public",
"static",
"String",
"getAbsoluteURI",
"(",
"String",
"urlString",
",",
"String",
"base",
")",
"throws",
"TransformerException",
"{",
"if",
"(",
"base",
"==",
"null",
")",
"return",
"getAbsoluteURI",
"(",
"urlString",
")",
";",
"String",
"absoluteBase",... | Take a SystemID string and try to turn it into a good absolute URI.
@param urlString SystemID string
@param base The URI string used as the base for resolving the systemID
@return The resolved absolute URI
@throws TransformerException thrown if the string can't be turned into a URI. | [
"Take",
"a",
"SystemID",
"string",
"and",
"try",
"to",
"turn",
"it",
"into",
"a",
"good",
"absolute",
"URI",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/utils/SystemIDResolver.java#L272-L291 |
GenesysPureEngage/authentication-client-java | src/main/java/com/genesys/authentication/AuthenticationApi.java | AuthenticationApi.getJwtUserInfo | public ModelApiResponse getJwtUserInfo(String authorization) throws AuthenticationApiException {
try {
return authenticationApi.getJwtInfoUsingGET(authorization);
} catch (ApiException e) {
throw new AuthenticationApiException("Error getting jwt userinfo", e);
}
} | java | public ModelApiResponse getJwtUserInfo(String authorization) throws AuthenticationApiException {
try {
return authenticationApi.getJwtInfoUsingGET(authorization);
} catch (ApiException e) {
throw new AuthenticationApiException("Error getting jwt userinfo", e);
}
} | [
"public",
"ModelApiResponse",
"getJwtUserInfo",
"(",
"String",
"authorization",
")",
"throws",
"AuthenticationApiException",
"{",
"try",
"{",
"return",
"authenticationApi",
".",
"getJwtInfoUsingGET",
"(",
"authorization",
")",
";",
"}",
"catch",
"(",
"ApiException",
"... | getJwtInfo
@param authorization The OAuth 2 bearer access token you received from [/auth/v3/oauth/token](/reference/authentication/Authentication/index.html#retrieveToken). For example: \"Authorization: bearer a4b5da75-a584-4053-9227-0f0ab23ff06e\" (required)
@return ModelApiResponse
@throws AuthenticationApiException if the call is unsuccessful. | [
"getJwtInfo"
] | train | https://github.com/GenesysPureEngage/authentication-client-java/blob/eb0d58343ee42ebd3c037163c1137f611dfcbb3a/src/main/java/com/genesys/authentication/AuthenticationApi.java#L134-L140 |
grails/grails-core | grails-core/src/main/groovy/grails/util/GrailsClassUtils.java | GrailsClassUtils.isPropertyInherited | @SuppressWarnings("rawtypes")
public static boolean isPropertyInherited(Class clz, String propertyName) {
if (clz == null) return false;
Assert.isTrue(StringUtils.hasText(propertyName), "Argument [propertyName] cannot be null or blank");
Class<?> superClass = clz.getSuperclass();
PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(superClass, propertyName);
if (pd != null && pd.getReadMethod() != null) {
return true;
}
return false;
} | java | @SuppressWarnings("rawtypes")
public static boolean isPropertyInherited(Class clz, String propertyName) {
if (clz == null) return false;
Assert.isTrue(StringUtils.hasText(propertyName), "Argument [propertyName] cannot be null or blank");
Class<?> superClass = clz.getSuperclass();
PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(superClass, propertyName);
if (pd != null && pd.getReadMethod() != null) {
return true;
}
return false;
} | [
"@",
"SuppressWarnings",
"(",
"\"rawtypes\"",
")",
"public",
"static",
"boolean",
"isPropertyInherited",
"(",
"Class",
"clz",
",",
"String",
"propertyName",
")",
"{",
"if",
"(",
"clz",
"==",
"null",
")",
"return",
"false",
";",
"Assert",
".",
"isTrue",
"(",
... | Checks whether the specified property is inherited from a super class
@param clz The class to check
@param propertyName The property name
@return true if the property is inherited | [
"Checks",
"whether",
"the",
"specified",
"property",
"is",
"inherited",
"from",
"a",
"super",
"class"
] | train | https://github.com/grails/grails-core/blob/c0b08aa995b0297143b75d05642abba8cb7b4122/grails-core/src/main/groovy/grails/util/GrailsClassUtils.java#L691-L703 |
sshtools/j2ssh-maverick | j2ssh-maverick/src/main/java/com/sshtools/sftp/SftpClient.java | SftpClient.chgrp | public void chgrp(String gid, String path) throws SftpStatusException,
SshException {
String actual = resolveRemotePath(path);
SftpFileAttributes attrs = sftp.getAttributes(actual);
attrs.setGID(gid);
sftp.setAttributes(actual, attrs);
} | java | public void chgrp(String gid, String path) throws SftpStatusException,
SshException {
String actual = resolveRemotePath(path);
SftpFileAttributes attrs = sftp.getAttributes(actual);
attrs.setGID(gid);
sftp.setAttributes(actual, attrs);
} | [
"public",
"void",
"chgrp",
"(",
"String",
"gid",
",",
"String",
"path",
")",
"throws",
"SftpStatusException",
",",
"SshException",
"{",
"String",
"actual",
"=",
"resolveRemotePath",
"(",
"path",
")",
";",
"SftpFileAttributes",
"attrs",
"=",
"sftp",
".",
"getAt... | <p>
Sets the group ID for the file or directory.
</p>
@param gid
the numeric group id for the new group
@param path
the path to the remote file/directory
@throws SftpStatusException
@throws SshException | [
"<p",
">",
"Sets",
"the",
"group",
"ID",
"for",
"the",
"file",
"or",
"directory",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/sshtools/j2ssh-maverick/blob/ce11ceaf0aa0b129b54327a6891973e1e34689f7/j2ssh-maverick/src/main/java/com/sshtools/sftp/SftpClient.java#L2024-L2032 |
oehf/ipf-oht-atna | auditor/src/main/java/org/openhealthtools/ihe/atna/auditor/events/ihe/GenericIHEAuditEventMessage.java | GenericIHEAuditEventMessage.addHumanRequestorActiveParticipant | @Deprecated
public void addHumanRequestorActiveParticipant(String userId, String altUserId, String userName, CodedValueType role)
{
addActiveParticipant(
userId,
altUserId,
userName,
true,
Collections.singletonList(role),
null);
} | java | @Deprecated
public void addHumanRequestorActiveParticipant(String userId, String altUserId, String userName, CodedValueType role)
{
addActiveParticipant(
userId,
altUserId,
userName,
true,
Collections.singletonList(role),
null);
} | [
"@",
"Deprecated",
"public",
"void",
"addHumanRequestorActiveParticipant",
"(",
"String",
"userId",
",",
"String",
"altUserId",
",",
"String",
"userName",
",",
"CodedValueType",
"role",
")",
"{",
"addActiveParticipant",
"(",
"userId",
",",
"altUserId",
",",
"userNam... | Adds an Active Participant block representing the human requestor participant
@param userId The Active Participant's User ID
@param altUserId The Active Participant's Alternate UserID
@param userName The Active Participant's UserName
@param role The participant's role | [
"Adds",
"an",
"Active",
"Participant",
"block",
"representing",
"the",
"human",
"requestor",
"participant"
] | train | https://github.com/oehf/ipf-oht-atna/blob/25ed1e926825169c94923a2c89a4618f60478ae8/auditor/src/main/java/org/openhealthtools/ihe/atna/auditor/events/ihe/GenericIHEAuditEventMessage.java#L151-L161 |
osmdroid/osmdroid | osmdroid-android/src/main/java/org/osmdroid/util/BoundingBox.java | BoundingBox.getCenterLongitude | public static double getCenterLongitude(final double pWest, final double pEast) {
double longitude = (pEast + pWest) / 2.0;
if (pEast < pWest) {
// center is on the other side of earth
longitude += 180;
}
return org.osmdroid.views.MapView.getTileSystem().cleanLongitude(longitude);
} | java | public static double getCenterLongitude(final double pWest, final double pEast) {
double longitude = (pEast + pWest) / 2.0;
if (pEast < pWest) {
// center is on the other side of earth
longitude += 180;
}
return org.osmdroid.views.MapView.getTileSystem().cleanLongitude(longitude);
} | [
"public",
"static",
"double",
"getCenterLongitude",
"(",
"final",
"double",
"pWest",
",",
"final",
"double",
"pEast",
")",
"{",
"double",
"longitude",
"=",
"(",
"pEast",
"+",
"pWest",
")",
"/",
"2.0",
";",
"if",
"(",
"pEast",
"<",
"pWest",
")",
"{",
"/... | Compute the center of two longitudes
Taking into account the case when "west is on the right and east is on the left"
@since 6.0.0 | [
"Compute",
"the",
"center",
"of",
"two",
"longitudes",
"Taking",
"into",
"account",
"the",
"case",
"when",
"west",
"is",
"on",
"the",
"right",
"and",
"east",
"is",
"on",
"the",
"left"
] | train | https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/osmdroid-android/src/main/java/org/osmdroid/util/BoundingBox.java#L143-L150 |
eclipse/xtext-lib | org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/ProcedureExtensions.java | ProcedureExtensions.curry | @Pure
public static <P1, P2, P3> Procedure2<P2, P3> curry(final Procedure3<? super P1, ? super P2, ? super P3> procedure, final P1 argument) {
if (procedure == null)
throw new NullPointerException("procedure");
return new Procedure2<P2, P3>() {
@Override
public void apply(P2 p2, P3 p3) {
procedure.apply(argument, p2, p3);
}
};
} | java | @Pure
public static <P1, P2, P3> Procedure2<P2, P3> curry(final Procedure3<? super P1, ? super P2, ? super P3> procedure, final P1 argument) {
if (procedure == null)
throw new NullPointerException("procedure");
return new Procedure2<P2, P3>() {
@Override
public void apply(P2 p2, P3 p3) {
procedure.apply(argument, p2, p3);
}
};
} | [
"@",
"Pure",
"public",
"static",
"<",
"P1",
",",
"P2",
",",
"P3",
">",
"Procedure2",
"<",
"P2",
",",
"P3",
">",
"curry",
"(",
"final",
"Procedure3",
"<",
"?",
"super",
"P1",
",",
"?",
"super",
"P2",
",",
"?",
"super",
"P3",
">",
"procedure",
",",... | Curries a procedure that takes three arguments.
@param procedure
the original procedure. May not be <code>null</code>.
@param argument
the fixed first argument of {@code procedure}.
@return a procedure that takes two arguments. Never <code>null</code>. | [
"Curries",
"a",
"procedure",
"that",
"takes",
"three",
"arguments",
"."
] | train | https://github.com/eclipse/xtext-lib/blob/7063572e1f1bd713a3aa53bdf3a8dc60e25c169a/org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/ProcedureExtensions.java#L79-L89 |
QSFT/Doradus | doradus-server/src/main/java/com/dell/doradus/service/rest/RESTServlet.java | RESTServlet.validateTenantAccess | private void validateTenantAccess(HttpServletRequest request, Tenant tenant, RegisteredCommand cmdModel) {
String authString = request.getHeader("Authorization");
StringBuilder userID = new StringBuilder();
StringBuilder password = new StringBuilder();
decodeAuthorizationHeader(authString, userID, password);
Permission perm = permissionForMethod(request.getMethod());
TenantService.instance().validateTenantAccess(tenant, userID.toString(), password.toString(),
perm, cmdModel.isPrivileged());
} | java | private void validateTenantAccess(HttpServletRequest request, Tenant tenant, RegisteredCommand cmdModel) {
String authString = request.getHeader("Authorization");
StringBuilder userID = new StringBuilder();
StringBuilder password = new StringBuilder();
decodeAuthorizationHeader(authString, userID, password);
Permission perm = permissionForMethod(request.getMethod());
TenantService.instance().validateTenantAccess(tenant, userID.toString(), password.toString(),
perm, cmdModel.isPrivileged());
} | [
"private",
"void",
"validateTenantAccess",
"(",
"HttpServletRequest",
"request",
",",
"Tenant",
"tenant",
",",
"RegisteredCommand",
"cmdModel",
")",
"{",
"String",
"authString",
"=",
"request",
".",
"getHeader",
"(",
"\"Authorization\"",
")",
";",
"StringBuilder",
"... | Extract Authorization header, if any, and validate this command for the given tenant. | [
"Extract",
"Authorization",
"header",
"if",
"any",
"and",
"validate",
"this",
"command",
"for",
"the",
"given",
"tenant",
"."
] | train | https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/rest/RESTServlet.java#L227-L235 |
baidubce/bce-sdk-java | src/main/java/com/baidubce/AbstractBceClient.java | AbstractBceClient.invokeHttpClient | protected <T extends AbstractBceResponse> T invokeHttpClient(InternalRequest request, Class<T> responseClass) {
if (!request.getHeaders().containsKey(Headers.CONTENT_TYPE)) {
request.addHeader(Headers.CONTENT_TYPE, DEFAULT_CONTENT_TYPE);
}
if (!request.getHeaders().containsKey(Headers.DATE)) {
request.addHeader(Headers.DATE, DateUtils.formatRfc822Date(new Date()));
}
return this.client.execute(request, responseClass, this.responseHandlers);
} | java | protected <T extends AbstractBceResponse> T invokeHttpClient(InternalRequest request, Class<T> responseClass) {
if (!request.getHeaders().containsKey(Headers.CONTENT_TYPE)) {
request.addHeader(Headers.CONTENT_TYPE, DEFAULT_CONTENT_TYPE);
}
if (!request.getHeaders().containsKey(Headers.DATE)) {
request.addHeader(Headers.DATE, DateUtils.formatRfc822Date(new Date()));
}
return this.client.execute(request, responseClass, this.responseHandlers);
} | [
"protected",
"<",
"T",
"extends",
"AbstractBceResponse",
">",
"T",
"invokeHttpClient",
"(",
"InternalRequest",
"request",
",",
"Class",
"<",
"T",
">",
"responseClass",
")",
"{",
"if",
"(",
"!",
"request",
".",
"getHeaders",
"(",
")",
".",
"containsKey",
"(",... | Subclasses should invoke this method for sending request to the target service.
<p>
This method will add "Content-Type" and "Date" to headers with default values if not present.
@param request the request to build up the HTTP request.
@param responseClass the response class.
@param <T> the type of response
@return the final response object. | [
"Subclasses",
"should",
"invoke",
"this",
"method",
"for",
"sending",
"request",
"to",
"the",
"target",
"service",
".",
"<p",
">",
"This",
"method",
"will",
"add",
"Content",
"-",
"Type",
"and",
"Date",
"to",
"headers",
"with",
"default",
"values",
"if",
"... | train | https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/AbstractBceClient.java#L180-L190 |
Samsung/GearVRf | GVRf/Framework/framework/src/main/java/org/gearvrf/GVRPicker.java | GVRPicker.findCollider | protected GVRPickedObject findCollider(GVRPickedObject[] pickList, GVRCollider findme)
{
if (pickList == null)
{
return null;
}
for (GVRPickedObject hit : pickList)
{
if ((hit != null) && (hit.hitCollider == findme))
{
return hit;
}
}
return null;
} | java | protected GVRPickedObject findCollider(GVRPickedObject[] pickList, GVRCollider findme)
{
if (pickList == null)
{
return null;
}
for (GVRPickedObject hit : pickList)
{
if ((hit != null) && (hit.hitCollider == findme))
{
return hit;
}
}
return null;
} | [
"protected",
"GVRPickedObject",
"findCollider",
"(",
"GVRPickedObject",
"[",
"]",
"pickList",
",",
"GVRCollider",
"findme",
")",
"{",
"if",
"(",
"pickList",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"for",
"(",
"GVRPickedObject",
"hit",
":",
"pickL... | Find the collision against a specific collider in a list of collisions.
@param pickList collision list
@param findme collider to find
@return collision with the specified collider, null if not found | [
"Find",
"the",
"collision",
"against",
"a",
"specific",
"collider",
"in",
"a",
"list",
"of",
"collisions",
"."
] | train | https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Framework/framework/src/main/java/org/gearvrf/GVRPicker.java#L894-L908 |
amzn/ion-java | src/com/amazon/ion/Timestamp.java | Timestamp.addMonth | public final Timestamp addMonth(int amount)
{
if (amount == 0 && _precision.includes(Precision.MONTH)) return this;
return addMonthForPrecision(amount, _precision.includes(Precision.MONTH) ? _precision : Precision.MONTH);
} | java | public final Timestamp addMonth(int amount)
{
if (amount == 0 && _precision.includes(Precision.MONTH)) return this;
return addMonthForPrecision(amount, _precision.includes(Precision.MONTH) ? _precision : Precision.MONTH);
} | [
"public",
"final",
"Timestamp",
"addMonth",
"(",
"int",
"amount",
")",
"{",
"if",
"(",
"amount",
"==",
"0",
"&&",
"_precision",
".",
"includes",
"(",
"Precision",
".",
"MONTH",
")",
")",
"return",
"this",
";",
"return",
"addMonthForPrecision",
"(",
"amount... | Returns a timestamp relative to this one by the given number of months.
The day field may be adjusted to account for different month length and
leap days. For example, adding one month to {@code 2011-01-31}
results in {@code 2011-02-28}.
@param amount a number of months. | [
"Returns",
"a",
"timestamp",
"relative",
"to",
"this",
"one",
"by",
"the",
"given",
"number",
"of",
"months",
".",
"The",
"day",
"field",
"may",
"be",
"adjusted",
"to",
"account",
"for",
"different",
"month",
"length",
"and",
"leap",
"days",
".",
"For",
... | train | https://github.com/amzn/ion-java/blob/4ce1f0f58c6a5a8e42d0425ccdb36e38be3e2270/src/com/amazon/ion/Timestamp.java#L2494-L2498 |
JOML-CI/JOML | src/org/joml/Matrix4d.java | Matrix4d.transformProject | public Vector4d transformProject(double x, double y, double z, double w, Vector4d dest) {
double invW = 1.0 / (m03 * x + m13 * y + m23 * z + m33 * w);
dest.set((m00 * x + m10 * y + m20 * z + m30 * w) * invW,
(m01 * x + m11 * y + m21 * z + m31 * w) * invW,
(m02 * x + m12 * y + m22 * z + m32 * w) * invW,
1.0);
return dest;
} | java | public Vector4d transformProject(double x, double y, double z, double w, Vector4d dest) {
double invW = 1.0 / (m03 * x + m13 * y + m23 * z + m33 * w);
dest.set((m00 * x + m10 * y + m20 * z + m30 * w) * invW,
(m01 * x + m11 * y + m21 * z + m31 * w) * invW,
(m02 * x + m12 * y + m22 * z + m32 * w) * invW,
1.0);
return dest;
} | [
"public",
"Vector4d",
"transformProject",
"(",
"double",
"x",
",",
"double",
"y",
",",
"double",
"z",
",",
"double",
"w",
",",
"Vector4d",
"dest",
")",
"{",
"double",
"invW",
"=",
"1.0",
"/",
"(",
"m03",
"*",
"x",
"+",
"m13",
"*",
"y",
"+",
"m23",
... | /* (non-Javadoc)
@see org.joml.Matrix4dc#transformProject(double, double, double, double, org.joml.Vector4d) | [
"/",
"*",
"(",
"non",
"-",
"Javadoc",
")"
] | train | https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4d.java#L4130-L4137 |
haraldk/TwelveMonkeys | imageio/imageio-core/src/main/java/com/twelvemonkeys/imageio/ImageWriterBase.java | ImageWriterBase.fakeAOI | protected static BufferedImage fakeAOI(final BufferedImage pImage, final ImageWriteParam pParam) {
return IIOUtil.fakeAOI(pImage, getSourceRegion(pParam, pImage.getWidth(), pImage.getHeight()));
} | java | protected static BufferedImage fakeAOI(final BufferedImage pImage, final ImageWriteParam pParam) {
return IIOUtil.fakeAOI(pImage, getSourceRegion(pParam, pImage.getWidth(), pImage.getHeight()));
} | [
"protected",
"static",
"BufferedImage",
"fakeAOI",
"(",
"final",
"BufferedImage",
"pImage",
",",
"final",
"ImageWriteParam",
"pParam",
")",
"{",
"return",
"IIOUtil",
".",
"fakeAOI",
"(",
"pImage",
",",
"getSourceRegion",
"(",
"pParam",
",",
"pImage",
".",
"getWi... | Utility method for getting the area of interest (AOI) of an image.
The AOI is defined by the {@link javax.imageio.IIOParam#setSourceRegion(java.awt.Rectangle)}
method.
<p/>
Note: If it is possible for the writer to write the AOI directly, such a
method should be used instead, for efficiency.
@param pImage the image to get AOI from
@param pParam the param optionally specifying the AOI
@return a {@code BufferedImage} containing the area of interest (source
region), or the original image, if no source region was set, or
{@code pParam} was {@code null} | [
"Utility",
"method",
"for",
"getting",
"the",
"area",
"of",
"interest",
"(",
"AOI",
")",
"of",
"an",
"image",
".",
"The",
"AOI",
"is",
"defined",
"by",
"the",
"{",
"@link",
"javax",
".",
"imageio",
".",
"IIOParam#setSourceRegion",
"(",
"java",
".",
"awt"... | train | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/imageio/imageio-core/src/main/java/com/twelvemonkeys/imageio/ImageWriterBase.java#L159-L161 |
WiQuery/wiquery | wiquery-jquery-ui/src/main/java/org/odlabs/wiquery/ui/slider/AjaxSlider.java | AjaxSlider.setAjaxStopEvent | public void setAjaxStopEvent(ISliderAjaxEvent ajaxStopEvent)
{
this.ajaxEvents.put(SliderAjaxEvent.ajaxStopEvent, ajaxStopEvent);
setStopEvent(new SliderAjaxJsScopeUiEvent(this, SliderAjaxEvent.ajaxStopEvent));
} | java | public void setAjaxStopEvent(ISliderAjaxEvent ajaxStopEvent)
{
this.ajaxEvents.put(SliderAjaxEvent.ajaxStopEvent, ajaxStopEvent);
setStopEvent(new SliderAjaxJsScopeUiEvent(this, SliderAjaxEvent.ajaxStopEvent));
} | [
"public",
"void",
"setAjaxStopEvent",
"(",
"ISliderAjaxEvent",
"ajaxStopEvent",
")",
"{",
"this",
".",
"ajaxEvents",
".",
"put",
"(",
"SliderAjaxEvent",
".",
"ajaxStopEvent",
",",
"ajaxStopEvent",
")",
";",
"setStopEvent",
"(",
"new",
"SliderAjaxJsScopeUiEvent",
"("... | Sets the call-back for the AJAX stop event.
@param ajaxStopEvent
The ISliderAjaxEvent. | [
"Sets",
"the",
"call",
"-",
"back",
"for",
"the",
"AJAX",
"stop",
"event",
"."
] | train | https://github.com/WiQuery/wiquery/blob/1b8d60c7a3c37b90fd68c9cd0ff97178fcbcbb08/wiquery-jquery-ui/src/main/java/org/odlabs/wiquery/ui/slider/AjaxSlider.java#L294-L298 |
sagiegurari/fax4j | src/main/java/org/fax4j/spi/vbs/VBSFaxClientSpi.java | VBSFaxClientSpi.generateScript | protected String generateScript(String name,Object[] input)
{
//get template
String template=VBSFaxClientSpi.VBS_SCRIPTS.get(name);
if((template==null)||(template.length()==0))
{
this.throwUnsupportedException();
}
//get common script
String commonScript=VBSFaxClientSpi.VBS_SCRIPTS.get(VBSFaxClientSpi.VBS_SCRIPT);
//format input
Object[] formattedInput=null;
if(input!=null)
{
//get size
int size=input.length;
//create array
formattedInput=new Object[size];
Object object=null;
for(int index=0;index<size;index++)
{
//get next element
object=input[index];
//format object
object=this.formatObject(object);
//push to array
formattedInput[index]=object;
}
}
//push input to template
String updatedScript=MessageFormat.format(template,formattedInput);
//merge scripts
StringBuilder buffer=new StringBuilder(commonScript.length()+updatedScript.length());
buffer.append(commonScript);
buffer.append(updatedScript);
String script=buffer.toString();
return script;
} | java | protected String generateScript(String name,Object[] input)
{
//get template
String template=VBSFaxClientSpi.VBS_SCRIPTS.get(name);
if((template==null)||(template.length()==0))
{
this.throwUnsupportedException();
}
//get common script
String commonScript=VBSFaxClientSpi.VBS_SCRIPTS.get(VBSFaxClientSpi.VBS_SCRIPT);
//format input
Object[] formattedInput=null;
if(input!=null)
{
//get size
int size=input.length;
//create array
formattedInput=new Object[size];
Object object=null;
for(int index=0;index<size;index++)
{
//get next element
object=input[index];
//format object
object=this.formatObject(object);
//push to array
formattedInput[index]=object;
}
}
//push input to template
String updatedScript=MessageFormat.format(template,formattedInput);
//merge scripts
StringBuilder buffer=new StringBuilder(commonScript.length()+updatedScript.length());
buffer.append(commonScript);
buffer.append(updatedScript);
String script=buffer.toString();
return script;
} | [
"protected",
"String",
"generateScript",
"(",
"String",
"name",
",",
"Object",
"[",
"]",
"input",
")",
"{",
"//get template",
"String",
"template",
"=",
"VBSFaxClientSpi",
".",
"VBS_SCRIPTS",
".",
"get",
"(",
"name",
")",
";",
"if",
"(",
"(",
"template",
"... | This function generates the script and returns it.
@param name
The script name
@param input
The script input
@return The formatted script | [
"This",
"function",
"generates",
"the",
"script",
"and",
"returns",
"it",
"."
] | train | https://github.com/sagiegurari/fax4j/blob/42fa51acabe7bf279e27ab3dd1cf76146b27955f/src/main/java/org/fax4j/spi/vbs/VBSFaxClientSpi.java#L719-L765 |
aws/aws-sdk-java | aws-java-sdk-iotjobsdataplane/src/main/java/com/amazonaws/services/iotjobsdataplane/model/JobExecutionState.java | JobExecutionState.withStatusDetails | public JobExecutionState withStatusDetails(java.util.Map<String, String> statusDetails) {
setStatusDetails(statusDetails);
return this;
} | java | public JobExecutionState withStatusDetails(java.util.Map<String, String> statusDetails) {
setStatusDetails(statusDetails);
return this;
} | [
"public",
"JobExecutionState",
"withStatusDetails",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"String",
">",
"statusDetails",
")",
"{",
"setStatusDetails",
"(",
"statusDetails",
")",
";",
"return",
"this",
";",
"}"
] | <p>
A collection of name/value pairs that describe the status of the job execution.
</p>
@param statusDetails
A collection of name/value pairs that describe the status of the job execution.
@return Returns a reference to this object so that method calls can be chained together. | [
"<p",
">",
"A",
"collection",
"of",
"name",
"/",
"value",
"pairs",
"that",
"describe",
"the",
"status",
"of",
"the",
"job",
"execution",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-iotjobsdataplane/src/main/java/com/amazonaws/services/iotjobsdataplane/model/JobExecutionState.java#L153-L156 |
bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Block.java | Block.createNextBlockWithCoinbase | @VisibleForTesting
Block createNextBlockWithCoinbase(long version, byte[] pubKey, final int height) {
return createNextBlock(null, version, (TransactionOutPoint) null,
Utils.currentTimeSeconds(), pubKey, FIFTY_COINS, height);
} | java | @VisibleForTesting
Block createNextBlockWithCoinbase(long version, byte[] pubKey, final int height) {
return createNextBlock(null, version, (TransactionOutPoint) null,
Utils.currentTimeSeconds(), pubKey, FIFTY_COINS, height);
} | [
"@",
"VisibleForTesting",
"Block",
"createNextBlockWithCoinbase",
"(",
"long",
"version",
",",
"byte",
"[",
"]",
"pubKey",
",",
"final",
"int",
"height",
")",
"{",
"return",
"createNextBlock",
"(",
"null",
",",
"version",
",",
"(",
"TransactionOutPoint",
")",
... | Create a block sending 50BTC as a coinbase transaction to the public key specified.
This method is intended for test use only. | [
"Create",
"a",
"block",
"sending",
"50BTC",
"as",
"a",
"coinbase",
"transaction",
"to",
"the",
"public",
"key",
"specified",
".",
"This",
"method",
"is",
"intended",
"for",
"test",
"use",
"only",
"."
] | train | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Block.java#L1028-L1032 |
keenon/loglinear | src/main/java/com/github/keenon/loglinear/model/ConcatVectorNamespace.java | ConcatVectorNamespace.setSparseFeature | public void setSparseFeature(ConcatVector vector, String featureName, Collection<String> sparseFeatures) {
int[] indices = new int[sparseFeatures.size()];
double[] values = new double[sparseFeatures.size()];
int offset = 0;
for (String index : sparseFeatures) {
indices[offset] = ensureSparseFeature(featureName, index);
values[offset] = 1.0;
offset++;
}
vector.setSparseComponent(ensureFeature(featureName), indices, values);
} | java | public void setSparseFeature(ConcatVector vector, String featureName, Collection<String> sparseFeatures) {
int[] indices = new int[sparseFeatures.size()];
double[] values = new double[sparseFeatures.size()];
int offset = 0;
for (String index : sparseFeatures) {
indices[offset] = ensureSparseFeature(featureName, index);
values[offset] = 1.0;
offset++;
}
vector.setSparseComponent(ensureFeature(featureName), indices, values);
} | [
"public",
"void",
"setSparseFeature",
"(",
"ConcatVector",
"vector",
",",
"String",
"featureName",
",",
"Collection",
"<",
"String",
">",
"sparseFeatures",
")",
"{",
"int",
"[",
"]",
"indices",
"=",
"new",
"int",
"[",
"sparseFeatures",
".",
"size",
"(",
")",... | This adds a sparse set feature to a vector, setting the appropriate components of the given vector to the passed
in value.
@param vector the vector
@param featureName the feature whose value to set
@param sparseFeatures the indices we wish to set, whose values will all be set to 1.0 | [
"This",
"adds",
"a",
"sparse",
"set",
"feature",
"to",
"a",
"vector",
"setting",
"the",
"appropriate",
"components",
"of",
"the",
"given",
"vector",
"to",
"the",
"passed",
"in",
"value",
"."
] | train | https://github.com/keenon/loglinear/blob/fa0c370ab6782015412f676ef2ab11c97be58e29/src/main/java/com/github/keenon/loglinear/model/ConcatVectorNamespace.java#L176-L186 |
chyxion/table-to-xls | src/main/java/me/chyxion/xls/css/CssUtils.java | CssUtils.parseColor | public static HSSFColor parseColor(HSSFWorkbook workBook, String color) {
HSSFColor poiColor = null;
if (StringUtils.isNotBlank(color)) {
Color awtColor = Color.decode(color);
if (awtColor != null) {
int r = awtColor.getRed();
int g = awtColor.getGreen();
int b = awtColor.getBlue();
HSSFPalette palette = workBook.getCustomPalette();
poiColor = palette.findColor((byte) r, (byte) g, (byte) b);
if (poiColor == null) {
poiColor = palette.findSimilarColor(r, g, b);
}
}
}
return poiColor;
} | java | public static HSSFColor parseColor(HSSFWorkbook workBook, String color) {
HSSFColor poiColor = null;
if (StringUtils.isNotBlank(color)) {
Color awtColor = Color.decode(color);
if (awtColor != null) {
int r = awtColor.getRed();
int g = awtColor.getGreen();
int b = awtColor.getBlue();
HSSFPalette palette = workBook.getCustomPalette();
poiColor = palette.findColor((byte) r, (byte) g, (byte) b);
if (poiColor == null) {
poiColor = palette.findSimilarColor(r, g, b);
}
}
}
return poiColor;
} | [
"public",
"static",
"HSSFColor",
"parseColor",
"(",
"HSSFWorkbook",
"workBook",
",",
"String",
"color",
")",
"{",
"HSSFColor",
"poiColor",
"=",
"null",
";",
"if",
"(",
"StringUtils",
".",
"isNotBlank",
"(",
"color",
")",
")",
"{",
"Color",
"awtColor",
"=",
... | parse color
@param workBook work book
@param color string color
@return HSSFColor | [
"parse",
"color"
] | train | https://github.com/chyxion/table-to-xls/blob/8dc0ab06b336c65ce949a974fb4930ee24d54ba7/src/main/java/me/chyxion/xls/css/CssUtils.java#L144-L160 |
icode/ameba | src/main/java/ameba/db/ebean/filter/Filters.java | Filters.getBeanTypeByName | public static Class getBeanTypeByName(String className, SpiEbeanServer server) {
if (className == null) return null;
for (BeanDescriptor descriptor : server.getBeanDescriptors()) {
Class beanClass = descriptor.getBeanType();
if (beanClass.getName().equalsIgnoreCase(className)
|| beanClass.getSimpleName().equalsIgnoreCase(className)) {
return beanClass;
}
}
return null;
} | java | public static Class getBeanTypeByName(String className, SpiEbeanServer server) {
if (className == null) return null;
for (BeanDescriptor descriptor : server.getBeanDescriptors()) {
Class beanClass = descriptor.getBeanType();
if (beanClass.getName().equalsIgnoreCase(className)
|| beanClass.getSimpleName().equalsIgnoreCase(className)) {
return beanClass;
}
}
return null;
} | [
"public",
"static",
"Class",
"getBeanTypeByName",
"(",
"String",
"className",
",",
"SpiEbeanServer",
"server",
")",
"{",
"if",
"(",
"className",
"==",
"null",
")",
"return",
"null",
";",
"for",
"(",
"BeanDescriptor",
"descriptor",
":",
"server",
".",
"getBeanD... | <p>getBeanTypeByName.</p>
@param className a {@link java.lang.String} object.
@param server a {@link io.ebeaninternal.api.SpiEbeanServer} object.
@return a {@link java.lang.Class} object. | [
"<p",
">",
"getBeanTypeByName",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/icode/ameba/blob/9d4956e935898e41331b2745e400ef869cd265e0/src/main/java/ameba/db/ebean/filter/Filters.java#L25-L35 |
fozziethebeat/S-Space | hadoop/src/main/java/edu/ucla/sspace/hadoop/HadoopJob.java | HadoopJob.run | public HadoopJobResults run(Collection<String> inputPaths)
throws Exception {
// Create a mostly unique file name for the output directory.
String outputDir = "output-" + System.currentTimeMillis();
//conf.setBoolean("mapred.task.profile", true);
Job job = new Job(conf, mapperClass.getName() + "-"
+ reducerClass.getName());
job.setJarByClass(HadoopJob.class);
job.setMapperClass(mapperClass);
job.setReducerClass(reducerClass);
job.setMapOutputKeyClass(mapperOutputKey);
job.setMapOutputValueClass(mapperOutputValue);
job.setOutputKeyClass(outputKey);
job.setOutputValueClass(outputValue);
// Add all the specified directories as input paths for the job
for (String inputDir : inputPaths)
FileInputFormat.addInputPath(job, new Path(inputDir));
Path outputDirPath = new Path(outputDir);
FileOutputFormat.setOutputPath(job, outputDirPath);
job.waitForCompletion(true);
// From the output directory, collect all the results files
FileSystem fs = FileSystem.get(conf);
FileStatus[] outputFiles =
fs.listStatus(outputDirPath, new OutputFilePathFilter());
Collection<Path> paths = new LinkedList<Path>();
for (FileStatus status : outputFiles) {
paths.add(status.getPath());
}
return new HadoopJobResults(fs, paths);
} | java | public HadoopJobResults run(Collection<String> inputPaths)
throws Exception {
// Create a mostly unique file name for the output directory.
String outputDir = "output-" + System.currentTimeMillis();
//conf.setBoolean("mapred.task.profile", true);
Job job = new Job(conf, mapperClass.getName() + "-"
+ reducerClass.getName());
job.setJarByClass(HadoopJob.class);
job.setMapperClass(mapperClass);
job.setReducerClass(reducerClass);
job.setMapOutputKeyClass(mapperOutputKey);
job.setMapOutputValueClass(mapperOutputValue);
job.setOutputKeyClass(outputKey);
job.setOutputValueClass(outputValue);
// Add all the specified directories as input paths for the job
for (String inputDir : inputPaths)
FileInputFormat.addInputPath(job, new Path(inputDir));
Path outputDirPath = new Path(outputDir);
FileOutputFormat.setOutputPath(job, outputDirPath);
job.waitForCompletion(true);
// From the output directory, collect all the results files
FileSystem fs = FileSystem.get(conf);
FileStatus[] outputFiles =
fs.listStatus(outputDirPath, new OutputFilePathFilter());
Collection<Path> paths = new LinkedList<Path>();
for (FileStatus status : outputFiles) {
paths.add(status.getPath());
}
return new HadoopJobResults(fs, paths);
} | [
"public",
"HadoopJobResults",
"run",
"(",
"Collection",
"<",
"String",
">",
"inputPaths",
")",
"throws",
"Exception",
"{",
"// Create a mostly unique file name for the output directory.",
"String",
"outputDir",
"=",
"\"output-\"",
"+",
"System",
".",
"currentTimeMillis",
... | Exceutes the word co-occurrence counting job on the corpus files in the
input directory using the current Hadoop instance, returning an iterator
over all the occurrences frequences found in the corpus.
@param inputPaths the directories on the Hadoop distributed file system
containing all the corpus files that will be processed
@return an iterator over the unique {@link WordCooccurrence} counts found
in the corpus. Note that if two words co-occur the same distance
apart multiple times, only one {@code WordCooccurrence} is
returned, where the number of co-occurrences is reflected by the
the {@link WordCooccurrence#getCount() getCount()} method.
@throws Exception if Hadoop throws an {@code Exception} during its
execution or if the resulting output files cannot be read. | [
"Exceutes",
"the",
"word",
"co",
"-",
"occurrence",
"counting",
"job",
"on",
"the",
"corpus",
"files",
"in",
"the",
"input",
"directory",
"using",
"the",
"current",
"Hadoop",
"instance",
"returning",
"an",
"iterator",
"over",
"all",
"the",
"occurrences",
"freq... | train | https://github.com/fozziethebeat/S-Space/blob/a608102737dfd3d59038a9ead33fe60356bc6029/hadoop/src/main/java/edu/ucla/sspace/hadoop/HadoopJob.java#L184-L221 |
neoremind/fluent-validator | fluent-validator/src/main/java/com/baidu/unbiz/fluentvalidator/QuickValidator.java | QuickValidator.validate | public static <T extends GenericResult<ValidationError>> T validate(Decorator decorator, FluentValidator fluentValidator, ValidatorContext context, ResultCollector<T> resultCollector) {
FluentValidator fv = decorator.decorate(fluentValidator);
if (context != null) {
fv.withContext(context);
}
T localResult = fv.failOver()
.doValidate()
.result(resultCollector);
return localResult;
} | java | public static <T extends GenericResult<ValidationError>> T validate(Decorator decorator, FluentValidator fluentValidator, ValidatorContext context, ResultCollector<T> resultCollector) {
FluentValidator fv = decorator.decorate(fluentValidator);
if (context != null) {
fv.withContext(context);
}
T localResult = fv.failOver()
.doValidate()
.result(resultCollector);
return localResult;
} | [
"public",
"static",
"<",
"T",
"extends",
"GenericResult",
"<",
"ValidationError",
">",
">",
"T",
"validate",
"(",
"Decorator",
"decorator",
",",
"FluentValidator",
"fluentValidator",
",",
"ValidatorContext",
"context",
",",
"ResultCollector",
"<",
"T",
">",
"resul... | Use the <code>decorator</code> to add or attach more functions the given <code>fluentValidator</code> instance.
<p>
The context can be shared and set up in the new FluentValidator instance.
<p>
The motivation for this method is to provide a quick way to launch a validation task. By just passing
the validation logic which is wrapped inside the decorator, users can do validation in a ease way.
<p>
Because Java7 lacks the ability to pass "action" to a method, so there is {@link Decorator} to help
to achieve a functional programming approach to get it done. In Java8, users can replace it with lambda.
@param decorator Same as decorator design pattern, provided to add more functions to the fluentValidator
@param fluentValidator The base fluentValidator to be executed upon
@param context Validation context which can be shared
@param resultCollector Result collector
@return Result | [
"Use",
"the",
"<code",
">",
"decorator<",
"/",
"code",
">",
"to",
"add",
"or",
"attach",
"more",
"functions",
"the",
"given",
"<code",
">",
"fluentValidator<",
"/",
"code",
">",
"instance",
".",
"<p",
">",
"The",
"context",
"can",
"be",
"shared",
"and",
... | train | https://github.com/neoremind/fluent-validator/blob/b516970591aa9468b44ba63938b98ec341fd6ead/fluent-validator/src/main/java/com/baidu/unbiz/fluentvalidator/QuickValidator.java#L83-L94 |
xcesco/kripton | kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/BindContentProviderBuilder.java | BindContentProviderBuilder.defineJavadocHeaderForContentOperation | private void defineJavadocHeaderForContentOperation(MethodSpec.Builder builder, String value) {
builder.addJavadoc("\n<h2>Supported $L operations</h2>\n", value);
builder.addJavadoc("<table>\n");
builder.addJavadoc("<tr><th>URI</th><th>DAO.METHOD</th></tr>\n");
classBuilder.addJavadoc("<h2>Supported $L operations</h2>\n", value);
classBuilder.addJavadoc("<table>\n");
classBuilder.addJavadoc("<tr><th>URI</th><th>DAO.METHOD</th></tr>\n");
} | java | private void defineJavadocHeaderForContentOperation(MethodSpec.Builder builder, String value) {
builder.addJavadoc("\n<h2>Supported $L operations</h2>\n", value);
builder.addJavadoc("<table>\n");
builder.addJavadoc("<tr><th>URI</th><th>DAO.METHOD</th></tr>\n");
classBuilder.addJavadoc("<h2>Supported $L operations</h2>\n", value);
classBuilder.addJavadoc("<table>\n");
classBuilder.addJavadoc("<tr><th>URI</th><th>DAO.METHOD</th></tr>\n");
} | [
"private",
"void",
"defineJavadocHeaderForContentOperation",
"(",
"MethodSpec",
".",
"Builder",
"builder",
",",
"String",
"value",
")",
"{",
"builder",
".",
"addJavadoc",
"(",
"\"\\n<h2>Supported $L operations</h2>\\n\"",
",",
"value",
")",
";",
"builder",
".",
"addJa... | Define javadoc header for content operation.
@param builder
the builder
@param value
the value | [
"Define",
"javadoc",
"header",
"for",
"content",
"operation",
"."
] | train | https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/BindContentProviderBuilder.java#L655-L664 |
lessthanoptimal/BoofCV | main/boofcv-feature/src/main/java/boofcv/alg/feature/disparity/impl/ImplDisparityScoreSadRect_S16.java | ImplDisparityScoreSadRect_S16.computeRemainingRows | private void computeRemainingRows(GrayS16 left, GrayS16 right )
{
for( int row = regionHeight; row < left.height; row++ ) {
int oldRow = row%regionHeight;
// subtract first row from vertical score
int scores[] = horizontalScore[oldRow];
for( int i = 0; i < lengthHorizontal; i++ ) {
verticalScore[i] -= scores[i];
}
UtilDisparityScore.computeScoreRow(left, right, row, scores,
minDisparity,maxDisparity,regionWidth,elementScore);
// add the new score
for( int i = 0; i < lengthHorizontal; i++ ) {
verticalScore[i] += scores[i];
}
// compute disparity
computeDisparity.process(row - regionHeight + 1 + radiusY, verticalScore);
}
} | java | private void computeRemainingRows(GrayS16 left, GrayS16 right )
{
for( int row = regionHeight; row < left.height; row++ ) {
int oldRow = row%regionHeight;
// subtract first row from vertical score
int scores[] = horizontalScore[oldRow];
for( int i = 0; i < lengthHorizontal; i++ ) {
verticalScore[i] -= scores[i];
}
UtilDisparityScore.computeScoreRow(left, right, row, scores,
minDisparity,maxDisparity,regionWidth,elementScore);
// add the new score
for( int i = 0; i < lengthHorizontal; i++ ) {
verticalScore[i] += scores[i];
}
// compute disparity
computeDisparity.process(row - regionHeight + 1 + radiusY, verticalScore);
}
} | [
"private",
"void",
"computeRemainingRows",
"(",
"GrayS16",
"left",
",",
"GrayS16",
"right",
")",
"{",
"for",
"(",
"int",
"row",
"=",
"regionHeight",
";",
"row",
"<",
"left",
".",
"height",
";",
"row",
"++",
")",
"{",
"int",
"oldRow",
"=",
"row",
"%",
... | Using previously computed results it efficiently finds the disparity in the remaining rows.
When a new block is processes the last row/column is subtracted and the new row/column is
added. | [
"Using",
"previously",
"computed",
"results",
"it",
"efficiently",
"finds",
"the",
"disparity",
"in",
"the",
"remaining",
"rows",
".",
"When",
"a",
"new",
"block",
"is",
"processes",
"the",
"last",
"row",
"/",
"column",
"is",
"subtracted",
"and",
"the",
"new... | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/feature/disparity/impl/ImplDisparityScoreSadRect_S16.java#L111-L133 |
TheHortonMachine/hortonmachine | gears/src/main/java/org/hortonmachine/gears/utils/style/StyleUtilities.java | StyleUtilities.changeMarkSize | public static void changeMarkSize( Rule rule, int newSize ) {
PointSymbolizer pointSymbolizer = StyleUtilities.pointSymbolizerFromRule(rule);
Graphic graphic = SLD.graphic(pointSymbolizer);
graphic.setSize(ff.literal(newSize));
// Mark oldMark = SLDs.mark(pointSymbolizer);
// oldMark.setSize(ff.literal(newSize));
// Graphic graphic = SLDs.graphic(pointSymbolizer);
} | java | public static void changeMarkSize( Rule rule, int newSize ) {
PointSymbolizer pointSymbolizer = StyleUtilities.pointSymbolizerFromRule(rule);
Graphic graphic = SLD.graphic(pointSymbolizer);
graphic.setSize(ff.literal(newSize));
// Mark oldMark = SLDs.mark(pointSymbolizer);
// oldMark.setSize(ff.literal(newSize));
// Graphic graphic = SLDs.graphic(pointSymbolizer);
} | [
"public",
"static",
"void",
"changeMarkSize",
"(",
"Rule",
"rule",
",",
"int",
"newSize",
")",
"{",
"PointSymbolizer",
"pointSymbolizer",
"=",
"StyleUtilities",
".",
"pointSymbolizerFromRule",
"(",
"rule",
")",
";",
"Graphic",
"graphic",
"=",
"SLD",
".",
"graphi... | Changes the size of a mark inside a rule.
@param rule the {@link Rule}.
@param newSize the new size. | [
"Changes",
"the",
"size",
"of",
"a",
"mark",
"inside",
"a",
"rule",
"."
] | train | https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/style/StyleUtilities.java#L666-L673 |
intive-FDV/DynamicJasper | src/main/java/ar/com/fdvs/dj/core/DynamicJasperHelper.java | DynamicJasperHelper.generateJasperPrint | public static JasperPrint generateJasperPrint(DynamicReport dr, LayoutManager layoutManager, Connection con, Map<String, Object> _parameters) throws JRException {
log.info("generating JasperPrint");
JasperPrint jp;
if (_parameters == null)
_parameters = new HashMap<String, Object>();
visitSubreports(dr, _parameters);
compileOrLoadSubreports(dr, _parameters, "r");
DynamicJasperDesign jd = generateJasperDesign(dr);
Map<String, Object> params = new HashMap<String, Object>();
if (!_parameters.isEmpty()) {
registerParams(jd, _parameters);
params.putAll(_parameters);
}
registerEntities(jd, dr, layoutManager);
layoutManager.applyLayout(jd, dr);
JRPropertiesUtil.getInstance(DefaultJasperReportsContext.getInstance()).setProperty(JRCompiler.COMPILER_PREFIX, DJCompilerFactory.getCompilerClassName());
//JRProperties.setProperty(JRCompiler.COMPILER_PREFIX, DJCompilerFactory.getCompilerClassName());
JasperReport jr = JasperCompileManager.compileReport(jd);
params.putAll(jd.getParametersWithValues());
jp = JasperFillManager.fillReport(jr, params, con);
return jp;
} | java | public static JasperPrint generateJasperPrint(DynamicReport dr, LayoutManager layoutManager, Connection con, Map<String, Object> _parameters) throws JRException {
log.info("generating JasperPrint");
JasperPrint jp;
if (_parameters == null)
_parameters = new HashMap<String, Object>();
visitSubreports(dr, _parameters);
compileOrLoadSubreports(dr, _parameters, "r");
DynamicJasperDesign jd = generateJasperDesign(dr);
Map<String, Object> params = new HashMap<String, Object>();
if (!_parameters.isEmpty()) {
registerParams(jd, _parameters);
params.putAll(_parameters);
}
registerEntities(jd, dr, layoutManager);
layoutManager.applyLayout(jd, dr);
JRPropertiesUtil.getInstance(DefaultJasperReportsContext.getInstance()).setProperty(JRCompiler.COMPILER_PREFIX, DJCompilerFactory.getCompilerClassName());
//JRProperties.setProperty(JRCompiler.COMPILER_PREFIX, DJCompilerFactory.getCompilerClassName());
JasperReport jr = JasperCompileManager.compileReport(jd);
params.putAll(jd.getParametersWithValues());
jp = JasperFillManager.fillReport(jr, params, con);
return jp;
} | [
"public",
"static",
"JasperPrint",
"generateJasperPrint",
"(",
"DynamicReport",
"dr",
",",
"LayoutManager",
"layoutManager",
",",
"Connection",
"con",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"_parameters",
")",
"throws",
"JRException",
"{",
"log",
".",
"i... | For running queries embebed in the report design
@param dr
@param layoutManager
@param con
@param _parameters
@return
@throws JRException | [
"For",
"running",
"queries",
"embebed",
"in",
"the",
"report",
"design"
] | train | https://github.com/intive-FDV/DynamicJasper/blob/63919574cc401ae40574d13129f628e66d1682a3/src/main/java/ar/com/fdvs/dj/core/DynamicJasperHelper.java#L259-L284 |
Netflix/netflix-commons | netflix-infix/src/main/java/com/netflix/infix/TimeUtil.java | TimeUtil.toDateTimeFormatter | public static DateTimeFormatter toDateTimeFormatter(String formatName, String timeFormat) {
DateTimeFormatter formatter = null;
try{
formatter = DateTimeFormat.forPattern(timeFormat);
}catch(IllegalArgumentException e){
//JODA's error message doesn't tell you which value sucked, so we create a better
// error message here.
IllegalArgumentException iae = new IllegalArgumentException(
String.format("Invalid time format for the property %s: '%s'",
formatName,
timeFormat),
e.getCause());
iae.setStackTrace(e.getStackTrace());
throw iae;
}
return formatter;
} | java | public static DateTimeFormatter toDateTimeFormatter(String formatName, String timeFormat) {
DateTimeFormatter formatter = null;
try{
formatter = DateTimeFormat.forPattern(timeFormat);
}catch(IllegalArgumentException e){
//JODA's error message doesn't tell you which value sucked, so we create a better
// error message here.
IllegalArgumentException iae = new IllegalArgumentException(
String.format("Invalid time format for the property %s: '%s'",
formatName,
timeFormat),
e.getCause());
iae.setStackTrace(e.getStackTrace());
throw iae;
}
return formatter;
} | [
"public",
"static",
"DateTimeFormatter",
"toDateTimeFormatter",
"(",
"String",
"formatName",
",",
"String",
"timeFormat",
")",
"{",
"DateTimeFormatter",
"formatter",
"=",
"null",
";",
"try",
"{",
"formatter",
"=",
"DateTimeFormat",
".",
"forPattern",
"(",
"timeForma... | Converts the given time format string to a {@link org.joda.time.format.DateTimeFormatter} instance.
@param formatName A name used to identify the given time format. This is mainly used for error reporting.
@param timeFormat The date time format to be converted.
@return A {@link org.joda.time.format.DateTimeFormatter} instance of the given time format.
@throws IllegalArgumentException if the given time format is invalid. | [
"Converts",
"the",
"given",
"time",
"format",
"string",
"to",
"a",
"{",
"@link",
"org",
".",
"joda",
".",
"time",
".",
"format",
".",
"DateTimeFormatter",
"}",
"instance",
"."
] | train | https://github.com/Netflix/netflix-commons/blob/7a158af76906d4a9b753e9344ce3e7abeb91dc01/netflix-infix/src/main/java/com/netflix/infix/TimeUtil.java#L18-L35 |
pressgang-ccms/PressGangCCMSContentSpec | src/main/java/org/jboss/pressgang/ccms/contentspec/utils/FixedURLGenerator.java | FixedURLGenerator.generateFixedUrls | public static void generateFixedUrls(final ContentSpec contentSpec, boolean missingOnly, final Integer fixedUrlPropertyTagId) {
final Set<String> existingFixedUrls = new HashSet<String>();
final Set<SpecNode> nodesWithoutFixedUrls = new HashSet<SpecNode>();
final List<SpecNode> specNodes = getAllSpecNodes(contentSpec);
// Collect any current fixed urls or nodes that need configuring
if (missingOnly) {
collectFixedUrlInformation(specNodes, nodesWithoutFixedUrls, existingFixedUrls);
}
generateFixedUrlForNodes(nodesWithoutFixedUrls, existingFixedUrls, fixedUrlPropertyTagId);
} | java | public static void generateFixedUrls(final ContentSpec contentSpec, boolean missingOnly, final Integer fixedUrlPropertyTagId) {
final Set<String> existingFixedUrls = new HashSet<String>();
final Set<SpecNode> nodesWithoutFixedUrls = new HashSet<SpecNode>();
final List<SpecNode> specNodes = getAllSpecNodes(contentSpec);
// Collect any current fixed urls or nodes that need configuring
if (missingOnly) {
collectFixedUrlInformation(specNodes, nodesWithoutFixedUrls, existingFixedUrls);
}
generateFixedUrlForNodes(nodesWithoutFixedUrls, existingFixedUrls, fixedUrlPropertyTagId);
} | [
"public",
"static",
"void",
"generateFixedUrls",
"(",
"final",
"ContentSpec",
"contentSpec",
",",
"boolean",
"missingOnly",
",",
"final",
"Integer",
"fixedUrlPropertyTagId",
")",
"{",
"final",
"Set",
"<",
"String",
">",
"existingFixedUrls",
"=",
"new",
"HashSet",
... | Generate the fixed urls and sets it where required for a content specification.
@param contentSpec The content spec to generate fixed urls for.
@param missingOnly Generate only the missing fixed urls.
@param fixedUrlPropertyTagId The Fixed URL Property Tag ID. | [
"Generate",
"the",
"fixed",
"urls",
"and",
"sets",
"it",
"where",
"required",
"for",
"a",
"content",
"specification",
"."
] | train | https://github.com/pressgang-ccms/PressGangCCMSContentSpec/blob/2bc02e2971e4522b47a130fb7ae5a0f5ad377df1/src/main/java/org/jboss/pressgang/ccms/contentspec/utils/FixedURLGenerator.java#L46-L57 |
BorderTech/wcomponents | wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/WListRenderer.java | WListRenderer.doRender | @Override
public void doRender(final WComponent component, final WebXmlRenderContext renderContext) {
WList list = (WList) component;
XmlStringBuilder xml = renderContext.getWriter();
WList.Type type = list.getType();
WList.Separator separator = list.getSeparator();
Size gap = list.getSpace();
String gapString = gap == null ? null : gap.toString();
xml.appendTagOpen("ui:panel");
xml.appendAttribute("id", component.getId());
xml.appendOptionalAttribute("class", component.getHtmlClass());
xml.appendOptionalAttribute("track", component.isTracking(), "true");
xml.appendOptionalAttribute("type", list.isRenderBorder(), "box");
xml.appendClose();
// Render margin
MarginRendererUtil.renderMargin(list, renderContext);
xml.appendTagOpen("ui:listlayout");
xml.appendOptionalAttribute("gap", gapString);
if (type != null) {
switch (type) {
case FLAT:
xml.appendAttribute("type", "flat");
break;
case STACKED:
xml.appendAttribute("type", "stacked");
break;
case STRIPED:
xml.appendAttribute("type", "striped");
break;
default:
throw new SystemException("Unknown list type: " + type);
}
}
if (separator != null) {
switch (separator) {
case BAR:
xml.appendAttribute("separator", "bar");
break;
case DOT:
xml.appendAttribute("separator", "dot");
break;
case NONE:
break;
default:
throw new SystemException("Unknown list type: " + type);
}
}
xml.appendClose();
paintRows(list, renderContext);
xml.appendEndTag("ui:listlayout");
xml.appendEndTag("ui:panel");
} | java | @Override
public void doRender(final WComponent component, final WebXmlRenderContext renderContext) {
WList list = (WList) component;
XmlStringBuilder xml = renderContext.getWriter();
WList.Type type = list.getType();
WList.Separator separator = list.getSeparator();
Size gap = list.getSpace();
String gapString = gap == null ? null : gap.toString();
xml.appendTagOpen("ui:panel");
xml.appendAttribute("id", component.getId());
xml.appendOptionalAttribute("class", component.getHtmlClass());
xml.appendOptionalAttribute("track", component.isTracking(), "true");
xml.appendOptionalAttribute("type", list.isRenderBorder(), "box");
xml.appendClose();
// Render margin
MarginRendererUtil.renderMargin(list, renderContext);
xml.appendTagOpen("ui:listlayout");
xml.appendOptionalAttribute("gap", gapString);
if (type != null) {
switch (type) {
case FLAT:
xml.appendAttribute("type", "flat");
break;
case STACKED:
xml.appendAttribute("type", "stacked");
break;
case STRIPED:
xml.appendAttribute("type", "striped");
break;
default:
throw new SystemException("Unknown list type: " + type);
}
}
if (separator != null) {
switch (separator) {
case BAR:
xml.appendAttribute("separator", "bar");
break;
case DOT:
xml.appendAttribute("separator", "dot");
break;
case NONE:
break;
default:
throw new SystemException("Unknown list type: " + type);
}
}
xml.appendClose();
paintRows(list, renderContext);
xml.appendEndTag("ui:listlayout");
xml.appendEndTag("ui:panel");
} | [
"@",
"Override",
"public",
"void",
"doRender",
"(",
"final",
"WComponent",
"component",
",",
"final",
"WebXmlRenderContext",
"renderContext",
")",
"{",
"WList",
"list",
"=",
"(",
"WList",
")",
"component",
";",
"XmlStringBuilder",
"xml",
"=",
"renderContext",
".... | Paints the given WList.
@param component the WList to paint.
@param renderContext the RenderContext to paint to. | [
"Paints",
"the",
"given",
"WList",
"."
] | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/WListRenderer.java#L28-L92 |
hal/core | gui/src/main/java/org/jboss/as/console/client/tools/ModelBrowserView.java | ModelBrowserView.onViewChild | @Override
public void onViewChild(ModelNode address, String childName) {
TreeItem rootNode = findTreeItem(tree, address);
TreeItem childNode = null;
for(int i=0; i<rootNode.getChildCount(); i++)
{
TreeItem candidate = rootNode.getChild(i);
if(childName.equals(candidate.getText()))
{
childNode = candidate;
break;
}
}
if(null==childNode)
throw new IllegalArgumentException("No such child "+ childName + " on "+ address.toString());
// deselect previous
tree.setSelectedItem(null, false);
// select next
tree.setSelectedItem(childNode, false);
tree.ensureSelectedItemVisible();
onItemSelected(childNode);
} | java | @Override
public void onViewChild(ModelNode address, String childName) {
TreeItem rootNode = findTreeItem(tree, address);
TreeItem childNode = null;
for(int i=0; i<rootNode.getChildCount(); i++)
{
TreeItem candidate = rootNode.getChild(i);
if(childName.equals(candidate.getText()))
{
childNode = candidate;
break;
}
}
if(null==childNode)
throw new IllegalArgumentException("No such child "+ childName + " on "+ address.toString());
// deselect previous
tree.setSelectedItem(null, false);
// select next
tree.setSelectedItem(childNode, false);
tree.ensureSelectedItemVisible();
onItemSelected(childNode);
} | [
"@",
"Override",
"public",
"void",
"onViewChild",
"(",
"ModelNode",
"address",
",",
"String",
"childName",
")",
"{",
"TreeItem",
"rootNode",
"=",
"findTreeItem",
"(",
"tree",
",",
"address",
")",
";",
"TreeItem",
"childNode",
"=",
"null",
";",
"for",
"(",
... | Child selection within editor components (outside left hand tree)
@param address
@param childName | [
"Child",
"selection",
"within",
"editor",
"components",
"(",
"outside",
"left",
"hand",
"tree",
")"
] | train | https://github.com/hal/core/blob/d6d03f0bb128dc0470f5dc75fdb1ea1014400602/gui/src/main/java/org/jboss/as/console/client/tools/ModelBrowserView.java#L298-L324 |
alkacon/opencms-core | src/org/opencms/staticexport/CmsLinkManager.java | CmsLinkManager.substituteLinkForUnknownTarget | public String substituteLinkForUnknownTarget(
CmsObject cms,
String link,
String targetDetailPage,
boolean forceSecure) {
if (CmsStringUtil.isEmpty(link)) {
return "";
}
String sitePath = link;
String siteRoot = null;
if (hasScheme(link)) {
// the link has a scheme, that is starts with something like "http://"
// usually this should be a link to an external resource, but check anyway
sitePath = getRootPath(cms, link);
if (sitePath == null) {
// probably an external link, don't touch this
return link;
}
}
// check if we can find a site from the link
siteRoot = OpenCms.getSiteManager().getSiteRoot(sitePath);
if (siteRoot == null) {
// use current site root in case no valid site root is available
// this will also be the case if a "/system" link is used
siteRoot = cms.getRequestContext().getSiteRoot();
} else {
// we found a site root, cut this from the resource path
sitePath = sitePath.substring(siteRoot.length());
}
return substituteLink(cms, sitePath, siteRoot, targetDetailPage, forceSecure);
} | java | public String substituteLinkForUnknownTarget(
CmsObject cms,
String link,
String targetDetailPage,
boolean forceSecure) {
if (CmsStringUtil.isEmpty(link)) {
return "";
}
String sitePath = link;
String siteRoot = null;
if (hasScheme(link)) {
// the link has a scheme, that is starts with something like "http://"
// usually this should be a link to an external resource, but check anyway
sitePath = getRootPath(cms, link);
if (sitePath == null) {
// probably an external link, don't touch this
return link;
}
}
// check if we can find a site from the link
siteRoot = OpenCms.getSiteManager().getSiteRoot(sitePath);
if (siteRoot == null) {
// use current site root in case no valid site root is available
// this will also be the case if a "/system" link is used
siteRoot = cms.getRequestContext().getSiteRoot();
} else {
// we found a site root, cut this from the resource path
sitePath = sitePath.substring(siteRoot.length());
}
return substituteLink(cms, sitePath, siteRoot, targetDetailPage, forceSecure);
} | [
"public",
"String",
"substituteLinkForUnknownTarget",
"(",
"CmsObject",
"cms",
",",
"String",
"link",
",",
"String",
"targetDetailPage",
",",
"boolean",
"forceSecure",
")",
"{",
"if",
"(",
"CmsStringUtil",
".",
"isEmpty",
"(",
"link",
")",
")",
"{",
"return",
... | Returns a link <i>from</i> the URI stored in the provided OpenCms user context
<i>to</i> the given <code>link</code>, for use on web pages.<p>
A number of tests are performed with the <code>link</code> in order to find out how to create the link:<ul>
<li>If <code>link</code> is empty, an empty String is returned.
<li>If <code>link</code> starts with an URI scheme component, for example <code>http://</code>,
and does not point to an internal OpenCms site, it is returned unchanged.
<li>If <code>link</code> is an absolute URI that starts with a configured site root,
the site root is cut from the link and
the same result as {@link #substituteLink(CmsObject, String, String)} is returned.
<li>Otherwise the same result as {@link #substituteLink(CmsObject, String)} is returned.
</ul>
@param cms the current OpenCms user context
@param link the link to process
@param targetDetailPage the target detail page, in case of linking to a specific detail page
@param forceSecure forces the secure server prefix if the link target is secure
@return a link <i>from</i> the URI stored in the provided OpenCms user context
<i>to</i> the given <code>link</code> | [
"Returns",
"a",
"link",
"<i",
">",
"from<",
"/",
"i",
">",
"the",
"URI",
"stored",
"in",
"the",
"provided",
"OpenCms",
"user",
"context",
"<i",
">",
"to<",
"/",
"i",
">",
"the",
"given",
"<code",
">",
"link<",
"/",
"code",
">",
"for",
"use",
"on",
... | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/staticexport/CmsLinkManager.java#L922-L953 |
RestComm/Restcomm-Connect | restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/AccountsEndpoint.java | AccountsEndpoint.updateLinkedClient | private void updateLinkedClient(Account account, MultivaluedMap<String, String> data) {
logger.debug("checking linked client");
String email = account.getEmailAddress();
if (email != null && !email.equals("")) {
logger.debug("account email is valid");
String username = email.split("@")[0];
Client client = clientDao.getClient(username, account.getOrganizationSid());
if (client != null) {
logger.debug("client found");
// TODO: need to encrypt this password because it's
// same with Account password.
// Don't implement now. Opened another issue for it.
if (data.containsKey("Password")) {
// Md5Hash(data.getFirst("Password")).toString();
logger.debug("password changed");
String password = data.getFirst("Password");
client = client.setPassword(client.getLogin(), password, organizationsDao.getOrganization(account.getOrganizationSid()).getDomainName());
}
if (data.containsKey("FriendlyName")) {
logger.debug("friendlyname changed");
client = client.setFriendlyName(data.getFirst("FriendlyName"));
}
logger.debug("updating linked client");
clientDao.updateClient(client);
}
}
} | java | private void updateLinkedClient(Account account, MultivaluedMap<String, String> data) {
logger.debug("checking linked client");
String email = account.getEmailAddress();
if (email != null && !email.equals("")) {
logger.debug("account email is valid");
String username = email.split("@")[0];
Client client = clientDao.getClient(username, account.getOrganizationSid());
if (client != null) {
logger.debug("client found");
// TODO: need to encrypt this password because it's
// same with Account password.
// Don't implement now. Opened another issue for it.
if (data.containsKey("Password")) {
// Md5Hash(data.getFirst("Password")).toString();
logger.debug("password changed");
String password = data.getFirst("Password");
client = client.setPassword(client.getLogin(), password, organizationsDao.getOrganization(account.getOrganizationSid()).getDomainName());
}
if (data.containsKey("FriendlyName")) {
logger.debug("friendlyname changed");
client = client.setFriendlyName(data.getFirst("FriendlyName"));
}
logger.debug("updating linked client");
clientDao.updateClient(client);
}
}
} | [
"private",
"void",
"updateLinkedClient",
"(",
"Account",
"account",
",",
"MultivaluedMap",
"<",
"String",
",",
"String",
">",
"data",
")",
"{",
"logger",
".",
"debug",
"(",
"\"checking linked client\"",
")",
";",
"String",
"email",
"=",
"account",
".",
"getEma... | update SIP client of the corresponding Account.Password and FriendlyName fields are synched. | [
"update",
"SIP",
"client",
"of",
"the",
"corresponding",
"Account",
".",
"Password",
"and",
"FriendlyName",
"fields",
"are",
"synched",
"."
] | train | https://github.com/RestComm/Restcomm-Connect/blob/2194dee4fc524cdfd0af77a218ba5f212f97f7c5/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/AccountsEndpoint.java#L576-L603 |
UrielCh/ovh-java-sdk | ovh-java-sdk-dedicatedserver/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedserver.java | ApiOvhDedicatedserver.serviceName_statistics_connection_GET | public ArrayList<OvhRtmConnection> serviceName_statistics_connection_GET(String serviceName) throws IOException {
String qPath = "/dedicated/server/{serviceName}/statistics/connection";
StringBuilder sb = path(qPath, serviceName);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t11);
} | java | public ArrayList<OvhRtmConnection> serviceName_statistics_connection_GET(String serviceName) throws IOException {
String qPath = "/dedicated/server/{serviceName}/statistics/connection";
StringBuilder sb = path(qPath, serviceName);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t11);
} | [
"public",
"ArrayList",
"<",
"OvhRtmConnection",
">",
"serviceName_statistics_connection_GET",
"(",
"String",
"serviceName",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/dedicated/server/{serviceName}/statistics/connection\"",
";",
"StringBuilder",
"sb",
"=",... | Get server opened connections
REST: GET /dedicated/server/{serviceName}/statistics/connection
@param serviceName [required] The internal name of your dedicated server | [
"Get",
"server",
"opened",
"connections"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dedicatedserver/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedserver.java#L1499-L1504 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.