repository_name
stringlengths 7
58
| func_path_in_repository
stringlengths 11
218
| func_name
stringlengths 4
140
| whole_func_string
stringlengths 153
5.32k
| language
stringclasses 1
value | func_code_string
stringlengths 72
4k
| func_code_tokens
listlengths 20
832
| func_documentation_string
stringlengths 61
2k
| func_documentation_tokens
listlengths 1
647
| split_name
stringclasses 1
value | func_code_url
stringlengths 102
339
|
---|---|---|---|---|---|---|---|---|---|---|
eurekaclinical/protempa
|
protempa-framework/src/main/java/org/protempa/proposition/PropositionUtil.java
|
PropositionUtil.binarySearchMinStart
|
private static int binarySearchMinStart(
List<? extends TemporalProposition> params, long timestamp) {
"""
Binary search for a primitive parameter by timestamp.
@param list
a <code>List</code> of <code>PrimitiveParameter</code>
objects all with the same paramId, cannot be <code>null</code>.
@param tstamp
the timestamp we're interested in finding.
@return a <code>PrimitiveParameter</code>, or null if not found.
"""
/*
* The conditions for using index versus iterator are grabbed from the
* JDK source code.
*/
if (params.size() < 5000 || params instanceof RandomAccess) {
return minStartIndexedBinarySearch(params, timestamp);
} else {
return minStartIteratorBinarySearch(params, timestamp);
}
}
|
java
|
private static int binarySearchMinStart(
List<? extends TemporalProposition> params, long timestamp) {
/*
* The conditions for using index versus iterator are grabbed from the
* JDK source code.
*/
if (params.size() < 5000 || params instanceof RandomAccess) {
return minStartIndexedBinarySearch(params, timestamp);
} else {
return minStartIteratorBinarySearch(params, timestamp);
}
}
|
[
"private",
"static",
"int",
"binarySearchMinStart",
"(",
"List",
"<",
"?",
"extends",
"TemporalProposition",
">",
"params",
",",
"long",
"timestamp",
")",
"{",
"/*\n * The conditions for using index versus iterator are grabbed from the\n * JDK source code.\n */",
"if",
"(",
"params",
".",
"size",
"(",
")",
"<",
"5000",
"||",
"params",
"instanceof",
"RandomAccess",
")",
"{",
"return",
"minStartIndexedBinarySearch",
"(",
"params",
",",
"timestamp",
")",
";",
"}",
"else",
"{",
"return",
"minStartIteratorBinarySearch",
"(",
"params",
",",
"timestamp",
")",
";",
"}",
"}"
] |
Binary search for a primitive parameter by timestamp.
@param list
a <code>List</code> of <code>PrimitiveParameter</code>
objects all with the same paramId, cannot be <code>null</code>.
@param tstamp
the timestamp we're interested in finding.
@return a <code>PrimitiveParameter</code>, or null if not found.
|
[
"Binary",
"search",
"for",
"a",
"primitive",
"parameter",
"by",
"timestamp",
"."
] |
train
|
https://github.com/eurekaclinical/protempa/blob/5a620d1a407c7a5426d1cf17d47b97717cf71634/protempa-framework/src/main/java/org/protempa/proposition/PropositionUtil.java#L203-L214
|
code4everything/util
|
src/main/java/com/zhazhapan/util/MailSender.java
|
MailSender.sendMail
|
public static void sendMail(String to, String title, String content) throws Exception {
"""
发送邮件,调用此方法前请先检查邮件服务器是否已经设置,如果没有设置,请先设置{@link MailSender#setHost(String)}, 如不设置将使用默认的QQ邮件服务器
@param to 收件箱
@param title 标题
@param content 内容
@throws Exception 异常
"""
if (!Checker.isEmail(to)) {
throw new Exception("this email address is not valid. please check it again");
}
// 获取系统属性
Properties properties = System.getProperties();
// 设置邮件服务器
properties.setProperty("mail.smtp.host", host);
if (port > 0) {
properties.setProperty("mail.smtp.port", String.valueOf(port));
}
properties.put("mail.smtp.auth", "true");
MailSSLSocketFactory sf;
sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable", sslEnable);
properties.put("mail.smtp.ssl.socketFactory", sf);
// 获取session对象
Session session = Session.getInstance(properties, new Authenticator() {
@Override
public PasswordAuthentication getPasswordAuthentication() {
// 发件人邮件用户名、密码
return new PasswordAuthentication(from, key);
}
});
// 创建默认的MimeMessage对象
MimeMessage message = new MimeMessage(session);
// Set From:头部头字段
message.setFrom(new InternetAddress(from, personal, "UTF-8"));
// Set To:头部头字段
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
// Set Subject:头部头字段
message.setSubject(title, "UTF-8");
// 设置消息体
message.setContent(content, "text/html;charset=UTF-8");
message.setSentDate(new Date());
// 发送消息
Transport.send(message);
}
|
java
|
public static void sendMail(String to, String title, String content) throws Exception {
if (!Checker.isEmail(to)) {
throw new Exception("this email address is not valid. please check it again");
}
// 获取系统属性
Properties properties = System.getProperties();
// 设置邮件服务器
properties.setProperty("mail.smtp.host", host);
if (port > 0) {
properties.setProperty("mail.smtp.port", String.valueOf(port));
}
properties.put("mail.smtp.auth", "true");
MailSSLSocketFactory sf;
sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable", sslEnable);
properties.put("mail.smtp.ssl.socketFactory", sf);
// 获取session对象
Session session = Session.getInstance(properties, new Authenticator() {
@Override
public PasswordAuthentication getPasswordAuthentication() {
// 发件人邮件用户名、密码
return new PasswordAuthentication(from, key);
}
});
// 创建默认的MimeMessage对象
MimeMessage message = new MimeMessage(session);
// Set From:头部头字段
message.setFrom(new InternetAddress(from, personal, "UTF-8"));
// Set To:头部头字段
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
// Set Subject:头部头字段
message.setSubject(title, "UTF-8");
// 设置消息体
message.setContent(content, "text/html;charset=UTF-8");
message.setSentDate(new Date());
// 发送消息
Transport.send(message);
}
|
[
"public",
"static",
"void",
"sendMail",
"(",
"String",
"to",
",",
"String",
"title",
",",
"String",
"content",
")",
"throws",
"Exception",
"{",
"if",
"(",
"!",
"Checker",
".",
"isEmail",
"(",
"to",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"\"this email address is not valid. please check it again\"",
")",
";",
"}",
"// 获取系统属性",
"Properties",
"properties",
"=",
"System",
".",
"getProperties",
"(",
")",
";",
"// 设置邮件服务器",
"properties",
".",
"setProperty",
"(",
"\"mail.smtp.host\"",
",",
"host",
")",
";",
"if",
"(",
"port",
">",
"0",
")",
"{",
"properties",
".",
"setProperty",
"(",
"\"mail.smtp.port\"",
",",
"String",
".",
"valueOf",
"(",
"port",
")",
")",
";",
"}",
"properties",
".",
"put",
"(",
"\"mail.smtp.auth\"",
",",
"\"true\"",
")",
";",
"MailSSLSocketFactory",
"sf",
";",
"sf",
"=",
"new",
"MailSSLSocketFactory",
"(",
")",
";",
"sf",
".",
"setTrustAllHosts",
"(",
"true",
")",
";",
"properties",
".",
"put",
"(",
"\"mail.smtp.ssl.enable\"",
",",
"sslEnable",
")",
";",
"properties",
".",
"put",
"(",
"\"mail.smtp.ssl.socketFactory\"",
",",
"sf",
")",
";",
"// 获取session对象",
"Session",
"session",
"=",
"Session",
".",
"getInstance",
"(",
"properties",
",",
"new",
"Authenticator",
"(",
")",
"{",
"@",
"Override",
"public",
"PasswordAuthentication",
"getPasswordAuthentication",
"(",
")",
"{",
"// 发件人邮件用户名、密码",
"return",
"new",
"PasswordAuthentication",
"(",
"from",
",",
"key",
")",
";",
"}",
"}",
")",
";",
"// 创建默认的MimeMessage对象",
"MimeMessage",
"message",
"=",
"new",
"MimeMessage",
"(",
"session",
")",
";",
"// Set From:头部头字段",
"message",
".",
"setFrom",
"(",
"new",
"InternetAddress",
"(",
"from",
",",
"personal",
",",
"\"UTF-8\"",
")",
")",
";",
"// Set To:头部头字段",
"message",
".",
"addRecipient",
"(",
"Message",
".",
"RecipientType",
".",
"TO",
",",
"new",
"InternetAddress",
"(",
"to",
")",
")",
";",
"// Set Subject:头部头字段",
"message",
".",
"setSubject",
"(",
"title",
",",
"\"UTF-8\"",
")",
";",
"// 设置消息体",
"message",
".",
"setContent",
"(",
"content",
",",
"\"text/html;charset=UTF-8\"",
")",
";",
"message",
".",
"setSentDate",
"(",
"new",
"Date",
"(",
")",
")",
";",
"// 发送消息",
"Transport",
".",
"send",
"(",
"message",
")",
";",
"}"
] |
发送邮件,调用此方法前请先检查邮件服务器是否已经设置,如果没有设置,请先设置{@link MailSender#setHost(String)}, 如不设置将使用默认的QQ邮件服务器
@param to 收件箱
@param title 标题
@param content 内容
@throws Exception 异常
|
[
"发送邮件,调用此方法前请先检查邮件服务器是否已经设置,如果没有设置,请先设置",
"{",
"@link",
"MailSender#setHost",
"(",
"String",
")",
"}",
",",
"如不设置将使用默认的QQ邮件服务器"
] |
train
|
https://github.com/code4everything/util/blob/1fc9f0ead1108f4d7208ba7c000df4244f708418/src/main/java/com/zhazhapan/util/MailSender.java#L194-L233
|
Stratio/deep-spark
|
deep-cassandra/src/main/java/com/stratio/deep/cassandra/cql/DeepCqlRecordWriter.java
|
DeepCqlRecordWriter.write
|
public void write(Cells keys, Cells values) {
"""
Adds the provided row to a batch. If the batch size reaches the threshold configured in
IDeepJobConfig.getBatchSize the batch will be sent to the data store.
@param keys the Cells object containing the row keys.
@param values the Cells object containing all the other row columns.
"""
if (!hasCurrentTask) {
String localCql = queryBuilder.prepareQuery(keys, values);
currentTask = new WriteTask(localCql);
hasCurrentTask = true;
}
// add primary key columns to the bind variables
List<Object> allValues = new ArrayList<>(values.getCellValues());
allValues.addAll(keys.getCellValues());
currentTask.add(allValues);
if (isBatchSizeReached()) {
executeTaskAsync();
}
}
|
java
|
public void write(Cells keys, Cells values) {
if (!hasCurrentTask) {
String localCql = queryBuilder.prepareQuery(keys, values);
currentTask = new WriteTask(localCql);
hasCurrentTask = true;
}
// add primary key columns to the bind variables
List<Object> allValues = new ArrayList<>(values.getCellValues());
allValues.addAll(keys.getCellValues());
currentTask.add(allValues);
if (isBatchSizeReached()) {
executeTaskAsync();
}
}
|
[
"public",
"void",
"write",
"(",
"Cells",
"keys",
",",
"Cells",
"values",
")",
"{",
"if",
"(",
"!",
"hasCurrentTask",
")",
"{",
"String",
"localCql",
"=",
"queryBuilder",
".",
"prepareQuery",
"(",
"keys",
",",
"values",
")",
";",
"currentTask",
"=",
"new",
"WriteTask",
"(",
"localCql",
")",
";",
"hasCurrentTask",
"=",
"true",
";",
"}",
"// add primary key columns to the bind variables",
"List",
"<",
"Object",
">",
"allValues",
"=",
"new",
"ArrayList",
"<>",
"(",
"values",
".",
"getCellValues",
"(",
")",
")",
";",
"allValues",
".",
"addAll",
"(",
"keys",
".",
"getCellValues",
"(",
")",
")",
";",
"currentTask",
".",
"add",
"(",
"allValues",
")",
";",
"if",
"(",
"isBatchSizeReached",
"(",
")",
")",
"{",
"executeTaskAsync",
"(",
")",
";",
"}",
"}"
] |
Adds the provided row to a batch. If the batch size reaches the threshold configured in
IDeepJobConfig.getBatchSize the batch will be sent to the data store.
@param keys the Cells object containing the row keys.
@param values the Cells object containing all the other row columns.
|
[
"Adds",
"the",
"provided",
"row",
"to",
"a",
"batch",
".",
"If",
"the",
"batch",
"size",
"reaches",
"the",
"threshold",
"configured",
"in",
"IDeepJobConfig",
".",
"getBatchSize",
"the",
"batch",
"will",
"be",
"sent",
"to",
"the",
"data",
"store",
"."
] |
train
|
https://github.com/Stratio/deep-spark/blob/b9621c9b7a6d996f80fce1d073d696a157bed095/deep-cassandra/src/main/java/com/stratio/deep/cassandra/cql/DeepCqlRecordWriter.java#L107-L123
|
alkacon/opencms-core
|
src-setup/org/opencms/setup/updater/dialogs/A_CmsUpdateDialog.java
|
A_CmsUpdateDialog.readSnippet
|
public String readSnippet(String name) {
"""
Reads an HTML snipped with the given name.
@param name name of file
@return the HTML data
"""
String path = CmsStringUtil.joinPaths(
m_ui.getUpdateBean().getWebAppRfsPath(),
CmsUpdateBean.FOLDER_UPDATE,
"html",
name);
try (InputStream stream = new FileInputStream(path)) {
byte[] data = CmsFileUtil.readFully(stream, false);
String result = new String(data, "UTF-8");
return result;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
|
java
|
public String readSnippet(String name) {
String path = CmsStringUtil.joinPaths(
m_ui.getUpdateBean().getWebAppRfsPath(),
CmsUpdateBean.FOLDER_UPDATE,
"html",
name);
try (InputStream stream = new FileInputStream(path)) {
byte[] data = CmsFileUtil.readFully(stream, false);
String result = new String(data, "UTF-8");
return result;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
|
[
"public",
"String",
"readSnippet",
"(",
"String",
"name",
")",
"{",
"String",
"path",
"=",
"CmsStringUtil",
".",
"joinPaths",
"(",
"m_ui",
".",
"getUpdateBean",
"(",
")",
".",
"getWebAppRfsPath",
"(",
")",
",",
"CmsUpdateBean",
".",
"FOLDER_UPDATE",
",",
"\"html\"",
",",
"name",
")",
";",
"try",
"(",
"InputStream",
"stream",
"=",
"new",
"FileInputStream",
"(",
"path",
")",
")",
"{",
"byte",
"[",
"]",
"data",
"=",
"CmsFileUtil",
".",
"readFully",
"(",
"stream",
",",
"false",
")",
";",
"String",
"result",
"=",
"new",
"String",
"(",
"data",
",",
"\"UTF-8\"",
")",
";",
"return",
"result",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"}"
] |
Reads an HTML snipped with the given name.
@param name name of file
@return the HTML data
|
[
"Reads",
"an",
"HTML",
"snipped",
"with",
"the",
"given",
"name",
".",
"@param",
"name",
"name",
"of",
"file"
] |
train
|
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-setup/org/opencms/setup/updater/dialogs/A_CmsUpdateDialog.java#L156-L170
|
hazelcast/hazelcast
|
hazelcast/src/main/java/com/hazelcast/config/Config.java
|
Config.setAtomicLongConfigs
|
public Config setAtomicLongConfigs(Map<String, AtomicLongConfig> atomicLongConfigs) {
"""
Sets the map of AtomicLong configurations, mapped by config name.
The config name may be a pattern with which the configuration will be obtained in the future.
@param atomicLongConfigs the AtomicLong configuration map to set
@return this config instance
"""
this.atomicLongConfigs.clear();
this.atomicLongConfigs.putAll(atomicLongConfigs);
for (Entry<String, AtomicLongConfig> entry : atomicLongConfigs.entrySet()) {
entry.getValue().setName(entry.getKey());
}
return this;
}
|
java
|
public Config setAtomicLongConfigs(Map<String, AtomicLongConfig> atomicLongConfigs) {
this.atomicLongConfigs.clear();
this.atomicLongConfigs.putAll(atomicLongConfigs);
for (Entry<String, AtomicLongConfig> entry : atomicLongConfigs.entrySet()) {
entry.getValue().setName(entry.getKey());
}
return this;
}
|
[
"public",
"Config",
"setAtomicLongConfigs",
"(",
"Map",
"<",
"String",
",",
"AtomicLongConfig",
">",
"atomicLongConfigs",
")",
"{",
"this",
".",
"atomicLongConfigs",
".",
"clear",
"(",
")",
";",
"this",
".",
"atomicLongConfigs",
".",
"putAll",
"(",
"atomicLongConfigs",
")",
";",
"for",
"(",
"Entry",
"<",
"String",
",",
"AtomicLongConfig",
">",
"entry",
":",
"atomicLongConfigs",
".",
"entrySet",
"(",
")",
")",
"{",
"entry",
".",
"getValue",
"(",
")",
".",
"setName",
"(",
"entry",
".",
"getKey",
"(",
")",
")",
";",
"}",
"return",
"this",
";",
"}"
] |
Sets the map of AtomicLong configurations, mapped by config name.
The config name may be a pattern with which the configuration will be obtained in the future.
@param atomicLongConfigs the AtomicLong configuration map to set
@return this config instance
|
[
"Sets",
"the",
"map",
"of",
"AtomicLong",
"configurations",
"mapped",
"by",
"config",
"name",
".",
"The",
"config",
"name",
"may",
"be",
"a",
"pattern",
"with",
"which",
"the",
"configuration",
"will",
"be",
"obtained",
"in",
"the",
"future",
"."
] |
train
|
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/config/Config.java#L1390-L1397
|
maxirosson/jdroid-android
|
jdroid-android-core/src/main/java/com/jdroid/android/utils/SharedPreferencesHelper.java
|
SharedPreferencesHelper.loadPreferenceAsFloat
|
public Float loadPreferenceAsFloat(String key, Float defaultValue) {
"""
Retrieve a Float value from the preferences.
@param key The name of the preference to retrieve
@param defaultValue Value to return if this preference does not exist
@return the preference value if it exists, or defaultValue.
"""
Float value = defaultValue;
if (hasPreference(key)) {
value = getSharedPreferences().getFloat(key, 0);
}
logLoad(key, value);
return value;
}
|
java
|
public Float loadPreferenceAsFloat(String key, Float defaultValue) {
Float value = defaultValue;
if (hasPreference(key)) {
value = getSharedPreferences().getFloat(key, 0);
}
logLoad(key, value);
return value;
}
|
[
"public",
"Float",
"loadPreferenceAsFloat",
"(",
"String",
"key",
",",
"Float",
"defaultValue",
")",
"{",
"Float",
"value",
"=",
"defaultValue",
";",
"if",
"(",
"hasPreference",
"(",
"key",
")",
")",
"{",
"value",
"=",
"getSharedPreferences",
"(",
")",
".",
"getFloat",
"(",
"key",
",",
"0",
")",
";",
"}",
"logLoad",
"(",
"key",
",",
"value",
")",
";",
"return",
"value",
";",
"}"
] |
Retrieve a Float value from the preferences.
@param key The name of the preference to retrieve
@param defaultValue Value to return if this preference does not exist
@return the preference value if it exists, or defaultValue.
|
[
"Retrieve",
"a",
"Float",
"value",
"from",
"the",
"preferences",
"."
] |
train
|
https://github.com/maxirosson/jdroid-android/blob/1ba9cae56a16fa36bdb2c9c04379853f0300707f/jdroid-android-core/src/main/java/com/jdroid/android/utils/SharedPreferencesHelper.java#L281-L288
|
msteiger/jxmapviewer2
|
jxmapviewer2/src/main/java/org/jxmapviewer/util/GraphicsUtilities.java
|
GraphicsUtilities.mergeClip
|
@Deprecated
public static Shape mergeClip(Graphics g, Shape clip) {
"""
Sets the clip on a graphics object by merging a supplied clip with the existing one. The new
clip will be an intersection of the old clip and the supplied clip. The old clip shape will
be returned. This is useful for resetting the old clip after an operation is performed.
@param g
the graphics object to update
@param clip
a new clipping region to add to the graphics clip.
@return the current clipping region of the supplied graphics object. This may return {@code
null} if the current clip is {@code null}.
@throws NullPointerException
if any parameter is {@code null}
@deprecated Use {@link ShapeUtils#mergeClip(Graphics,Shape)} instead
"""
return ShapeUtils.mergeClip(g, clip);
}
|
java
|
@Deprecated
public static Shape mergeClip(Graphics g, Shape clip) {
return ShapeUtils.mergeClip(g, clip);
}
|
[
"@",
"Deprecated",
"public",
"static",
"Shape",
"mergeClip",
"(",
"Graphics",
"g",
",",
"Shape",
"clip",
")",
"{",
"return",
"ShapeUtils",
".",
"mergeClip",
"(",
"g",
",",
"clip",
")",
";",
"}"
] |
Sets the clip on a graphics object by merging a supplied clip with the existing one. The new
clip will be an intersection of the old clip and the supplied clip. The old clip shape will
be returned. This is useful for resetting the old clip after an operation is performed.
@param g
the graphics object to update
@param clip
a new clipping region to add to the graphics clip.
@return the current clipping region of the supplied graphics object. This may return {@code
null} if the current clip is {@code null}.
@throws NullPointerException
if any parameter is {@code null}
@deprecated Use {@link ShapeUtils#mergeClip(Graphics,Shape)} instead
|
[
"Sets",
"the",
"clip",
"on",
"a",
"graphics",
"object",
"by",
"merging",
"a",
"supplied",
"clip",
"with",
"the",
"existing",
"one",
".",
"The",
"new",
"clip",
"will",
"be",
"an",
"intersection",
"of",
"the",
"old",
"clip",
"and",
"the",
"supplied",
"clip",
".",
"The",
"old",
"clip",
"shape",
"will",
"be",
"returned",
".",
"This",
"is",
"useful",
"for",
"resetting",
"the",
"old",
"clip",
"after",
"an",
"operation",
"is",
"performed",
"."
] |
train
|
https://github.com/msteiger/jxmapviewer2/blob/82639273b0aac983b6026fb90aa925c0cf596410/jxmapviewer2/src/main/java/org/jxmapviewer/util/GraphicsUtilities.java#L788-L791
|
line/armeria
|
core/src/main/java/com/linecorp/armeria/client/Clients.java
|
Clients.newDerivedClient
|
public static <T> T newDerivedClient(T client, Iterable<ClientOptionValue<?>> additionalOptions) {
"""
Creates a new derived client that connects to the same {@link URI} with the specified {@code client}
and the specified {@code additionalOptions}.
@see ClientBuilder ClientBuilder, for more information about how the base options and
additional options are merged when a derived client is created.
"""
final ClientBuilderParams params = builderParams(client);
final ClientBuilder builder = newDerivedBuilder(params);
builder.options(additionalOptions);
return newDerivedClient(builder, params.clientType());
}
|
java
|
public static <T> T newDerivedClient(T client, Iterable<ClientOptionValue<?>> additionalOptions) {
final ClientBuilderParams params = builderParams(client);
final ClientBuilder builder = newDerivedBuilder(params);
builder.options(additionalOptions);
return newDerivedClient(builder, params.clientType());
}
|
[
"public",
"static",
"<",
"T",
">",
"T",
"newDerivedClient",
"(",
"T",
"client",
",",
"Iterable",
"<",
"ClientOptionValue",
"<",
"?",
">",
">",
"additionalOptions",
")",
"{",
"final",
"ClientBuilderParams",
"params",
"=",
"builderParams",
"(",
"client",
")",
";",
"final",
"ClientBuilder",
"builder",
"=",
"newDerivedBuilder",
"(",
"params",
")",
";",
"builder",
".",
"options",
"(",
"additionalOptions",
")",
";",
"return",
"newDerivedClient",
"(",
"builder",
",",
"params",
".",
"clientType",
"(",
")",
")",
";",
"}"
] |
Creates a new derived client that connects to the same {@link URI} with the specified {@code client}
and the specified {@code additionalOptions}.
@see ClientBuilder ClientBuilder, for more information about how the base options and
additional options are merged when a derived client is created.
|
[
"Creates",
"a",
"new",
"derived",
"client",
"that",
"connects",
"to",
"the",
"same",
"{",
"@link",
"URI",
"}",
"with",
"the",
"specified",
"{",
"@code",
"client",
"}",
"and",
"the",
"specified",
"{",
"@code",
"additionalOptions",
"}",
"."
] |
train
|
https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/core/src/main/java/com/linecorp/armeria/client/Clients.java#L191-L197
|
johnkil/Android-AppMsg
|
library/src/com/devspark/appmsg/AppMsg.java
|
AppMsg.makeText
|
public static AppMsg makeText(Activity context, int resId, Style style, View customView, boolean floating) {
"""
Make a {@link AppMsg} with a custom view. It can be used to create non-floating notifications if floating is false.
@param context The context to use. Usually your
{@link android.app.Activity} object.
@param resId The resource id of the string resource to use. Can be
formatted text.
@param style The style with a background and a duration.
@param floating true if it'll float.
"""
return makeText(context, context.getResources().getText(resId), style, customView, floating);
}
|
java
|
public static AppMsg makeText(Activity context, int resId, Style style, View customView, boolean floating) {
return makeText(context, context.getResources().getText(resId), style, customView, floating);
}
|
[
"public",
"static",
"AppMsg",
"makeText",
"(",
"Activity",
"context",
",",
"int",
"resId",
",",
"Style",
"style",
",",
"View",
"customView",
",",
"boolean",
"floating",
")",
"{",
"return",
"makeText",
"(",
"context",
",",
"context",
".",
"getResources",
"(",
")",
".",
"getText",
"(",
"resId",
")",
",",
"style",
",",
"customView",
",",
"floating",
")",
";",
"}"
] |
Make a {@link AppMsg} with a custom view. It can be used to create non-floating notifications if floating is false.
@param context The context to use. Usually your
{@link android.app.Activity} object.
@param resId The resource id of the string resource to use. Can be
formatted text.
@param style The style with a background and a duration.
@param floating true if it'll float.
|
[
"Make",
"a",
"{",
"@link",
"AppMsg",
"}",
"with",
"a",
"custom",
"view",
".",
"It",
"can",
"be",
"used",
"to",
"create",
"non",
"-",
"floating",
"notifications",
"if",
"floating",
"is",
"false",
"."
] |
train
|
https://github.com/johnkil/Android-AppMsg/blob/e7fdd7870530a24e6d825278ee0863be0521e8b8/library/src/com/devspark/appmsg/AppMsg.java#L393-L395
|
wildfly/wildfly-core
|
controller/src/main/java/org/jboss/as/controller/AbstractAttributeDefinitionBuilder.java
|
AbstractAttributeDefinitionBuilder.setCapabilityReference
|
public BUILDER setCapabilityReference(String referencedCapability, AttributeDefinition ... dependantAttributes) {
"""
Records that this attribute's value represents a reference to an instance of a
{@link org.jboss.as.controller.capability.RuntimeCapability#isDynamicallyNamed() dynamic capability}.
<p>
This method is a convenience method equivalent to calling * {@link #setCapabilityReference(CapabilityReferenceRecorder)}
passing in a {@link CapabilityReferenceRecorder.CompositeAttributeDependencyRecorder}
constructed using the parameters passed to this method.
<p>
<strong>NOTE:</strong> This method of recording capability references is only suitable for use in attributes
only used in resources that themselves expose a single capability.
If your resource exposes more than single capability, you should use {@link #setCapabilityReference(RuntimeCapability, String, AttributeDefinition...)}
When the capability requirement
is registered, the dependent capability will be that capability.
@param referencedCapability the name of the dynamic capability the dynamic portion of whose name is
represented by the attribute's value
@param dependantAttributes attribute from same resource that will be used to derive multiple dynamic parts for the dependant capability
@return the builder
@see AttributeDefinition#addCapabilityRequirements(OperationContext, org.jboss.as.controller.registry.Resource, ModelNode)
@see AttributeDefinition#removeCapabilityRequirements(OperationContext, org.jboss.as.controller.registry.Resource, ModelNode)
"""
//noinspection deprecation
referenceRecorder = new CapabilityReferenceRecorder.CompositeAttributeDependencyRecorder(referencedCapability, dependantAttributes);
return (BUILDER) this;
}
|
java
|
public BUILDER setCapabilityReference(String referencedCapability, AttributeDefinition ... dependantAttributes) {
//noinspection deprecation
referenceRecorder = new CapabilityReferenceRecorder.CompositeAttributeDependencyRecorder(referencedCapability, dependantAttributes);
return (BUILDER) this;
}
|
[
"public",
"BUILDER",
"setCapabilityReference",
"(",
"String",
"referencedCapability",
",",
"AttributeDefinition",
"...",
"dependantAttributes",
")",
"{",
"//noinspection deprecation",
"referenceRecorder",
"=",
"new",
"CapabilityReferenceRecorder",
".",
"CompositeAttributeDependencyRecorder",
"(",
"referencedCapability",
",",
"dependantAttributes",
")",
";",
"return",
"(",
"BUILDER",
")",
"this",
";",
"}"
] |
Records that this attribute's value represents a reference to an instance of a
{@link org.jboss.as.controller.capability.RuntimeCapability#isDynamicallyNamed() dynamic capability}.
<p>
This method is a convenience method equivalent to calling * {@link #setCapabilityReference(CapabilityReferenceRecorder)}
passing in a {@link CapabilityReferenceRecorder.CompositeAttributeDependencyRecorder}
constructed using the parameters passed to this method.
<p>
<strong>NOTE:</strong> This method of recording capability references is only suitable for use in attributes
only used in resources that themselves expose a single capability.
If your resource exposes more than single capability, you should use {@link #setCapabilityReference(RuntimeCapability, String, AttributeDefinition...)}
When the capability requirement
is registered, the dependent capability will be that capability.
@param referencedCapability the name of the dynamic capability the dynamic portion of whose name is
represented by the attribute's value
@param dependantAttributes attribute from same resource that will be used to derive multiple dynamic parts for the dependant capability
@return the builder
@see AttributeDefinition#addCapabilityRequirements(OperationContext, org.jboss.as.controller.registry.Resource, ModelNode)
@see AttributeDefinition#removeCapabilityRequirements(OperationContext, org.jboss.as.controller.registry.Resource, ModelNode)
|
[
"Records",
"that",
"this",
"attribute",
"s",
"value",
"represents",
"a",
"reference",
"to",
"an",
"instance",
"of",
"a",
"{",
"@link",
"org",
".",
"jboss",
".",
"as",
".",
"controller",
".",
"capability",
".",
"RuntimeCapability#isDynamicallyNamed",
"()",
"dynamic",
"capability",
"}",
".",
"<p",
">",
"This",
"method",
"is",
"a",
"convenience",
"method",
"equivalent",
"to",
"calling",
"*",
"{",
"@link",
"#setCapabilityReference",
"(",
"CapabilityReferenceRecorder",
")",
"}",
"passing",
"in",
"a",
"{",
"@link",
"CapabilityReferenceRecorder",
".",
"CompositeAttributeDependencyRecorder",
"}",
"constructed",
"using",
"the",
"parameters",
"passed",
"to",
"this",
"method",
".",
"<p",
">",
"<strong",
">",
"NOTE",
":",
"<",
"/",
"strong",
">",
"This",
"method",
"of",
"recording",
"capability",
"references",
"is",
"only",
"suitable",
"for",
"use",
"in",
"attributes",
"only",
"used",
"in",
"resources",
"that",
"themselves",
"expose",
"a",
"single",
"capability",
".",
"If",
"your",
"resource",
"exposes",
"more",
"than",
"single",
"capability",
"you",
"should",
"use",
"{",
"@link",
"#setCapabilityReference",
"(",
"RuntimeCapability",
"String",
"AttributeDefinition",
"...",
")",
"}",
"When",
"the",
"capability",
"requirement",
"is",
"registered",
"the",
"dependent",
"capability",
"will",
"be",
"that",
"capability",
"."
] |
train
|
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/AbstractAttributeDefinitionBuilder.java#L910-L914
|
sdl/odata
|
odata_renderer/src/main/java/com/sdl/odata/renderer/metadata/MetadataDocumentWriter.java
|
MetadataDocumentWriter.startDocument
|
public void startDocument() throws ODataRenderException {
"""
Start the XML stream document by defining things like the type of encoding, and prefixes used.
It needs to be used before calling any write method.
@throws ODataRenderException if unable to render
"""
outputStream = new ByteArrayOutputStream();
try {
xmlWriter = XML_OUTPUT_FACTORY.createXMLStreamWriter(outputStream, UTF_8.name());
entityTypeWriter = new MetadataDocumentEntityTypeWriter(xmlWriter, entityDataModel);
complexTypeWriter = new MetadataDocumentComplexTypeWriter(xmlWriter, entityDataModel);
enumTypeWriter = new MetadataDocumentEnumTypeWriter(xmlWriter);
entitySetWriter = new MetadataDocumentEntitySetWriter(xmlWriter);
singletonWriter = new MetadataDocumentSingletonWriter(xmlWriter);
xmlWriter.writeStartDocument(UTF_8.name(), XML_VERSION);
xmlWriter.setPrefix(EDMX_PREFIX, EDMX_NS);
} catch (XMLStreamException e) {
LOG.error("Not possible to start stream XML");
throw new ODataRenderException("Not possible to start stream XML: ", e);
}
}
|
java
|
public void startDocument() throws ODataRenderException {
outputStream = new ByteArrayOutputStream();
try {
xmlWriter = XML_OUTPUT_FACTORY.createXMLStreamWriter(outputStream, UTF_8.name());
entityTypeWriter = new MetadataDocumentEntityTypeWriter(xmlWriter, entityDataModel);
complexTypeWriter = new MetadataDocumentComplexTypeWriter(xmlWriter, entityDataModel);
enumTypeWriter = new MetadataDocumentEnumTypeWriter(xmlWriter);
entitySetWriter = new MetadataDocumentEntitySetWriter(xmlWriter);
singletonWriter = new MetadataDocumentSingletonWriter(xmlWriter);
xmlWriter.writeStartDocument(UTF_8.name(), XML_VERSION);
xmlWriter.setPrefix(EDMX_PREFIX, EDMX_NS);
} catch (XMLStreamException e) {
LOG.error("Not possible to start stream XML");
throw new ODataRenderException("Not possible to start stream XML: ", e);
}
}
|
[
"public",
"void",
"startDocument",
"(",
")",
"throws",
"ODataRenderException",
"{",
"outputStream",
"=",
"new",
"ByteArrayOutputStream",
"(",
")",
";",
"try",
"{",
"xmlWriter",
"=",
"XML_OUTPUT_FACTORY",
".",
"createXMLStreamWriter",
"(",
"outputStream",
",",
"UTF_8",
".",
"name",
"(",
")",
")",
";",
"entityTypeWriter",
"=",
"new",
"MetadataDocumentEntityTypeWriter",
"(",
"xmlWriter",
",",
"entityDataModel",
")",
";",
"complexTypeWriter",
"=",
"new",
"MetadataDocumentComplexTypeWriter",
"(",
"xmlWriter",
",",
"entityDataModel",
")",
";",
"enumTypeWriter",
"=",
"new",
"MetadataDocumentEnumTypeWriter",
"(",
"xmlWriter",
")",
";",
"entitySetWriter",
"=",
"new",
"MetadataDocumentEntitySetWriter",
"(",
"xmlWriter",
")",
";",
"singletonWriter",
"=",
"new",
"MetadataDocumentSingletonWriter",
"(",
"xmlWriter",
")",
";",
"xmlWriter",
".",
"writeStartDocument",
"(",
"UTF_8",
".",
"name",
"(",
")",
",",
"XML_VERSION",
")",
";",
"xmlWriter",
".",
"setPrefix",
"(",
"EDMX_PREFIX",
",",
"EDMX_NS",
")",
";",
"}",
"catch",
"(",
"XMLStreamException",
"e",
")",
"{",
"LOG",
".",
"error",
"(",
"\"Not possible to start stream XML\"",
")",
";",
"throw",
"new",
"ODataRenderException",
"(",
"\"Not possible to start stream XML: \"",
",",
"e",
")",
";",
"}",
"}"
] |
Start the XML stream document by defining things like the type of encoding, and prefixes used.
It needs to be used before calling any write method.
@throws ODataRenderException if unable to render
|
[
"Start",
"the",
"XML",
"stream",
"document",
"by",
"defining",
"things",
"like",
"the",
"type",
"of",
"encoding",
"and",
"prefixes",
"used",
".",
"It",
"needs",
"to",
"be",
"used",
"before",
"calling",
"any",
"write",
"method",
"."
] |
train
|
https://github.com/sdl/odata/blob/eb747d73e9af0f4e59a25b82ed656e526a7e2189/odata_renderer/src/main/java/com/sdl/odata/renderer/metadata/MetadataDocumentWriter.java#L83-L99
|
couchbase/couchbase-java-client
|
src/main/java/com/couchbase/client/java/subdoc/MutateInBuilder.java
|
MutateInBuilder.upsert
|
public <T> MutateInBuilder upsert(String path, T fragment) {
"""
Insert a fragment, replacing the old value if the path exists.
@param path the path where to insert (or replace) a dictionary value.
@param fragment the new dictionary value to be applied.
"""
asyncBuilder.upsert(path, fragment);
return this;
}
|
java
|
public <T> MutateInBuilder upsert(String path, T fragment) {
asyncBuilder.upsert(path, fragment);
return this;
}
|
[
"public",
"<",
"T",
">",
"MutateInBuilder",
"upsert",
"(",
"String",
"path",
",",
"T",
"fragment",
")",
"{",
"asyncBuilder",
".",
"upsert",
"(",
"path",
",",
"fragment",
")",
";",
"return",
"this",
";",
"}"
] |
Insert a fragment, replacing the old value if the path exists.
@param path the path where to insert (or replace) a dictionary value.
@param fragment the new dictionary value to be applied.
|
[
"Insert",
"a",
"fragment",
"replacing",
"the",
"old",
"value",
"if",
"the",
"path",
"exists",
"."
] |
train
|
https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/subdoc/MutateInBuilder.java#L590-L593
|
spotbugs/spotbugs
|
spotbugs/src/main/java/edu/umd/cs/findbugs/SourceLineAnnotation.java
|
SourceLineAnnotation.fromVisitedInstruction
|
public static SourceLineAnnotation fromVisitedInstruction(JavaClass jclass, Method method, int pc) {
"""
Create from Method and bytecode offset in a visited class.
@param jclass
JavaClass of visited class
@param method
Method in visited class
@param pc
bytecode offset in visited method
@return SourceLineAnnotation describing visited instruction
"""
LineNumberTable lineNumberTable = method.getCode().getLineNumberTable();
String className = jclass.getClassName();
String sourceFile = jclass.getSourceFileName();
if (lineNumberTable == null) {
return createUnknown(className, sourceFile, pc, pc);
}
int startLine = lineNumberTable.getSourceLine(pc);
return new SourceLineAnnotation(className, sourceFile, startLine, startLine, pc, pc);
}
|
java
|
public static SourceLineAnnotation fromVisitedInstruction(JavaClass jclass, Method method, int pc) {
LineNumberTable lineNumberTable = method.getCode().getLineNumberTable();
String className = jclass.getClassName();
String sourceFile = jclass.getSourceFileName();
if (lineNumberTable == null) {
return createUnknown(className, sourceFile, pc, pc);
}
int startLine = lineNumberTable.getSourceLine(pc);
return new SourceLineAnnotation(className, sourceFile, startLine, startLine, pc, pc);
}
|
[
"public",
"static",
"SourceLineAnnotation",
"fromVisitedInstruction",
"(",
"JavaClass",
"jclass",
",",
"Method",
"method",
",",
"int",
"pc",
")",
"{",
"LineNumberTable",
"lineNumberTable",
"=",
"method",
".",
"getCode",
"(",
")",
".",
"getLineNumberTable",
"(",
")",
";",
"String",
"className",
"=",
"jclass",
".",
"getClassName",
"(",
")",
";",
"String",
"sourceFile",
"=",
"jclass",
".",
"getSourceFileName",
"(",
")",
";",
"if",
"(",
"lineNumberTable",
"==",
"null",
")",
"{",
"return",
"createUnknown",
"(",
"className",
",",
"sourceFile",
",",
"pc",
",",
"pc",
")",
";",
"}",
"int",
"startLine",
"=",
"lineNumberTable",
".",
"getSourceLine",
"(",
"pc",
")",
";",
"return",
"new",
"SourceLineAnnotation",
"(",
"className",
",",
"sourceFile",
",",
"startLine",
",",
"startLine",
",",
"pc",
",",
"pc",
")",
";",
"}"
] |
Create from Method and bytecode offset in a visited class.
@param jclass
JavaClass of visited class
@param method
Method in visited class
@param pc
bytecode offset in visited method
@return SourceLineAnnotation describing visited instruction
|
[
"Create",
"from",
"Method",
"and",
"bytecode",
"offset",
"in",
"a",
"visited",
"class",
"."
] |
train
|
https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/SourceLineAnnotation.java#L468-L478
|
morfologik/morfologik-stemming
|
morfologik-speller/src/main/java/morfologik/speller/Speller.java
|
Speller.setWordAndCandidate
|
void setWordAndCandidate(final String word, final String candidate) {
"""
Sets up the word and candidate. Used only to test the edit distance in
JUnit tests.
@param word
the first word
@param candidate
the second word used for edit distance calculation
"""
wordProcessed = word.toCharArray();
wordLen = wordProcessed.length;
this.candidate = candidate.toCharArray();
candLen = this.candidate.length;
effectEditDistance = wordLen <= editDistance ? wordLen - 1 : editDistance;
}
|
java
|
void setWordAndCandidate(final String word, final String candidate) {
wordProcessed = word.toCharArray();
wordLen = wordProcessed.length;
this.candidate = candidate.toCharArray();
candLen = this.candidate.length;
effectEditDistance = wordLen <= editDistance ? wordLen - 1 : editDistance;
}
|
[
"void",
"setWordAndCandidate",
"(",
"final",
"String",
"word",
",",
"final",
"String",
"candidate",
")",
"{",
"wordProcessed",
"=",
"word",
".",
"toCharArray",
"(",
")",
";",
"wordLen",
"=",
"wordProcessed",
".",
"length",
";",
"this",
".",
"candidate",
"=",
"candidate",
".",
"toCharArray",
"(",
")",
";",
"candLen",
"=",
"this",
".",
"candidate",
".",
"length",
";",
"effectEditDistance",
"=",
"wordLen",
"<=",
"editDistance",
"?",
"wordLen",
"-",
"1",
":",
"editDistance",
";",
"}"
] |
Sets up the word and candidate. Used only to test the edit distance in
JUnit tests.
@param word
the first word
@param candidate
the second word used for edit distance calculation
|
[
"Sets",
"up",
"the",
"word",
"and",
"candidate",
".",
"Used",
"only",
"to",
"test",
"the",
"edit",
"distance",
"in",
"JUnit",
"tests",
"."
] |
train
|
https://github.com/morfologik/morfologik-stemming/blob/9d9099cc5ec4155a0eb8dfecdc23d01cbd734f6e/morfologik-speller/src/main/java/morfologik/speller/Speller.java#L871-L877
|
UrielCh/ovh-java-sdk
|
ovh-java-sdk-dedicatedCloud/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedCloud.java
|
ApiOvhDedicatedCloud.serviceName_globalTasks_GET
|
public ArrayList<Long> serviceName_globalTasks_GET(String serviceName, Long datacenterId, Date endDate_from, Date endDate_to, Date executionDate_from, Date executionDate_to, Long filerId, Long hostId, Date lastModificationDate_from, Date lastModificationDate_to, String name, Long networkAccessId, Long orderId, Long parentTaskId, OvhTaskStateEnum[] state, Long userId, Long vlanId) throws IOException {
"""
Get filtered tasks associated with this Private Cloud
REST: GET /dedicatedCloud/{serviceName}/globalTasks
@param executionDate_to [required] Filter the tasks by execution date (<=)
@param datacenterId [required] Filter the tasks by datacenter Id
@param hostId [required] Filter the tasks by host Id
@param lastModificationDate_from [required] Filter the tasks by last modification date (>=)
@param parentTaskId [required] Filter the tasks by parent task Id
@param executionDate_from [required] Filter the tasks by execution date (>=)
@param endDate_from [required] Filter the tasks by end date (>=)
@param vlanId [required] Filter the tasks by vlan Id
@param networkAccessId [required] Filter the tasks by network access Id
@param orderId [required] Filter the tasks by order Id
@param userId [required] Filter the tasks by user Id
@param endDate_to [required] Filter the tasks by end date (<=)
@param state [required] Filter the tasks by state
@param name [required] Filter the tasks by name
@param lastModificationDate_to [required] Filter the tasks by last modification date (<=)
@param filerId [required] Filter the tasks by filer Id
@param serviceName [required] Domain of the service
"""
String qPath = "/dedicatedCloud/{serviceName}/globalTasks";
StringBuilder sb = path(qPath, serviceName);
query(sb, "datacenterId", datacenterId);
query(sb, "endDate.from", endDate_from);
query(sb, "endDate.to", endDate_to);
query(sb, "executionDate.from", executionDate_from);
query(sb, "executionDate.to", executionDate_to);
query(sb, "filerId", filerId);
query(sb, "hostId", hostId);
query(sb, "lastModificationDate.from", lastModificationDate_from);
query(sb, "lastModificationDate.to", lastModificationDate_to);
query(sb, "name", name);
query(sb, "networkAccessId", networkAccessId);
query(sb, "orderId", orderId);
query(sb, "parentTaskId", parentTaskId);
query(sb, "state", state);
query(sb, "userId", userId);
query(sb, "vlanId", vlanId);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t2);
}
|
java
|
public ArrayList<Long> serviceName_globalTasks_GET(String serviceName, Long datacenterId, Date endDate_from, Date endDate_to, Date executionDate_from, Date executionDate_to, Long filerId, Long hostId, Date lastModificationDate_from, Date lastModificationDate_to, String name, Long networkAccessId, Long orderId, Long parentTaskId, OvhTaskStateEnum[] state, Long userId, Long vlanId) throws IOException {
String qPath = "/dedicatedCloud/{serviceName}/globalTasks";
StringBuilder sb = path(qPath, serviceName);
query(sb, "datacenterId", datacenterId);
query(sb, "endDate.from", endDate_from);
query(sb, "endDate.to", endDate_to);
query(sb, "executionDate.from", executionDate_from);
query(sb, "executionDate.to", executionDate_to);
query(sb, "filerId", filerId);
query(sb, "hostId", hostId);
query(sb, "lastModificationDate.from", lastModificationDate_from);
query(sb, "lastModificationDate.to", lastModificationDate_to);
query(sb, "name", name);
query(sb, "networkAccessId", networkAccessId);
query(sb, "orderId", orderId);
query(sb, "parentTaskId", parentTaskId);
query(sb, "state", state);
query(sb, "userId", userId);
query(sb, "vlanId", vlanId);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t2);
}
|
[
"public",
"ArrayList",
"<",
"Long",
">",
"serviceName_globalTasks_GET",
"(",
"String",
"serviceName",
",",
"Long",
"datacenterId",
",",
"Date",
"endDate_from",
",",
"Date",
"endDate_to",
",",
"Date",
"executionDate_from",
",",
"Date",
"executionDate_to",
",",
"Long",
"filerId",
",",
"Long",
"hostId",
",",
"Date",
"lastModificationDate_from",
",",
"Date",
"lastModificationDate_to",
",",
"String",
"name",
",",
"Long",
"networkAccessId",
",",
"Long",
"orderId",
",",
"Long",
"parentTaskId",
",",
"OvhTaskStateEnum",
"[",
"]",
"state",
",",
"Long",
"userId",
",",
"Long",
"vlanId",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/dedicatedCloud/{serviceName}/globalTasks\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
",",
"serviceName",
")",
";",
"query",
"(",
"sb",
",",
"\"datacenterId\"",
",",
"datacenterId",
")",
";",
"query",
"(",
"sb",
",",
"\"endDate.from\"",
",",
"endDate_from",
")",
";",
"query",
"(",
"sb",
",",
"\"endDate.to\"",
",",
"endDate_to",
")",
";",
"query",
"(",
"sb",
",",
"\"executionDate.from\"",
",",
"executionDate_from",
")",
";",
"query",
"(",
"sb",
",",
"\"executionDate.to\"",
",",
"executionDate_to",
")",
";",
"query",
"(",
"sb",
",",
"\"filerId\"",
",",
"filerId",
")",
";",
"query",
"(",
"sb",
",",
"\"hostId\"",
",",
"hostId",
")",
";",
"query",
"(",
"sb",
",",
"\"lastModificationDate.from\"",
",",
"lastModificationDate_from",
")",
";",
"query",
"(",
"sb",
",",
"\"lastModificationDate.to\"",
",",
"lastModificationDate_to",
")",
";",
"query",
"(",
"sb",
",",
"\"name\"",
",",
"name",
")",
";",
"query",
"(",
"sb",
",",
"\"networkAccessId\"",
",",
"networkAccessId",
")",
";",
"query",
"(",
"sb",
",",
"\"orderId\"",
",",
"orderId",
")",
";",
"query",
"(",
"sb",
",",
"\"parentTaskId\"",
",",
"parentTaskId",
")",
";",
"query",
"(",
"sb",
",",
"\"state\"",
",",
"state",
")",
";",
"query",
"(",
"sb",
",",
"\"userId\"",
",",
"userId",
")",
";",
"query",
"(",
"sb",
",",
"\"vlanId\"",
",",
"vlanId",
")",
";",
"String",
"resp",
"=",
"exec",
"(",
"qPath",
",",
"\"GET\"",
",",
"sb",
".",
"toString",
"(",
")",
",",
"null",
")",
";",
"return",
"convertTo",
"(",
"resp",
",",
"t2",
")",
";",
"}"
] |
Get filtered tasks associated with this Private Cloud
REST: GET /dedicatedCloud/{serviceName}/globalTasks
@param executionDate_to [required] Filter the tasks by execution date (<=)
@param datacenterId [required] Filter the tasks by datacenter Id
@param hostId [required] Filter the tasks by host Id
@param lastModificationDate_from [required] Filter the tasks by last modification date (>=)
@param parentTaskId [required] Filter the tasks by parent task Id
@param executionDate_from [required] Filter the tasks by execution date (>=)
@param endDate_from [required] Filter the tasks by end date (>=)
@param vlanId [required] Filter the tasks by vlan Id
@param networkAccessId [required] Filter the tasks by network access Id
@param orderId [required] Filter the tasks by order Id
@param userId [required] Filter the tasks by user Id
@param endDate_to [required] Filter the tasks by end date (<=)
@param state [required] Filter the tasks by state
@param name [required] Filter the tasks by name
@param lastModificationDate_to [required] Filter the tasks by last modification date (<=)
@param filerId [required] Filter the tasks by filer Id
@param serviceName [required] Domain of the service
|
[
"Get",
"filtered",
"tasks",
"associated",
"with",
"this",
"Private",
"Cloud"
] |
train
|
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dedicatedCloud/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedCloud.java#L1012-L1033
|
jboss/jboss-servlet-api_spec
|
src/main/java/javax/servlet/http/HttpUtils.java
|
HttpUtils.parseQueryString
|
public static Hashtable<String, String[]> parseQueryString(String s) {
"""
Parses a query string passed from the client to the
server and builds a <code>HashTable</code> object
with key-value pairs.
The query string should be in the form of a string
packaged by the GET or POST method, that is, it
should have key-value pairs in the form <i>key=value</i>,
with each pair separated from the next by a & character.
<p>A key can appear more than once in the query string
with different values. However, the key appears only once in
the hashtable, with its value being
an array of strings containing the multiple values sent
by the query string.
<p>The keys and values in the hashtable are stored in their
decoded form, so
any + characters are converted to spaces, and characters
sent in hexadecimal notation (like <i>%xx</i>) are
converted to ASCII characters.
@param s a string containing the query to be parsed
@return a <code>HashTable</code> object built
from the parsed key-value pairs
@exception IllegalArgumentException if the query string is invalid
"""
String valArray[] = null;
if (s == null) {
throw new IllegalArgumentException();
}
Hashtable<String, String[]> ht = new Hashtable<String, String[]>();
StringBuilder sb = new StringBuilder();
StringTokenizer st = new StringTokenizer(s, "&");
while (st.hasMoreTokens()) {
String pair = st.nextToken();
int pos = pair.indexOf('=');
if (pos == -1) {
// XXX
// should give more detail about the illegal argument
throw new IllegalArgumentException();
}
String key = parseName(pair.substring(0, pos), sb);
String val = parseName(pair.substring(pos+1, pair.length()), sb);
if (ht.containsKey(key)) {
String oldVals[] = ht.get(key);
valArray = new String[oldVals.length + 1];
for (int i = 0; i < oldVals.length; i++) {
valArray[i] = oldVals[i];
}
valArray[oldVals.length] = val;
} else {
valArray = new String[1];
valArray[0] = val;
}
ht.put(key, valArray);
}
return ht;
}
|
java
|
public static Hashtable<String, String[]> parseQueryString(String s) {
String valArray[] = null;
if (s == null) {
throw new IllegalArgumentException();
}
Hashtable<String, String[]> ht = new Hashtable<String, String[]>();
StringBuilder sb = new StringBuilder();
StringTokenizer st = new StringTokenizer(s, "&");
while (st.hasMoreTokens()) {
String pair = st.nextToken();
int pos = pair.indexOf('=');
if (pos == -1) {
// XXX
// should give more detail about the illegal argument
throw new IllegalArgumentException();
}
String key = parseName(pair.substring(0, pos), sb);
String val = parseName(pair.substring(pos+1, pair.length()), sb);
if (ht.containsKey(key)) {
String oldVals[] = ht.get(key);
valArray = new String[oldVals.length + 1];
for (int i = 0; i < oldVals.length; i++) {
valArray[i] = oldVals[i];
}
valArray[oldVals.length] = val;
} else {
valArray = new String[1];
valArray[0] = val;
}
ht.put(key, valArray);
}
return ht;
}
|
[
"public",
"static",
"Hashtable",
"<",
"String",
",",
"String",
"[",
"]",
">",
"parseQueryString",
"(",
"String",
"s",
")",
"{",
"String",
"valArray",
"[",
"]",
"=",
"null",
";",
"if",
"(",
"s",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
")",
";",
"}",
"Hashtable",
"<",
"String",
",",
"String",
"[",
"]",
">",
"ht",
"=",
"new",
"Hashtable",
"<",
"String",
",",
"String",
"[",
"]",
">",
"(",
")",
";",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"StringTokenizer",
"st",
"=",
"new",
"StringTokenizer",
"(",
"s",
",",
"\"&\"",
")",
";",
"while",
"(",
"st",
".",
"hasMoreTokens",
"(",
")",
")",
"{",
"String",
"pair",
"=",
"st",
".",
"nextToken",
"(",
")",
";",
"int",
"pos",
"=",
"pair",
".",
"indexOf",
"(",
"'",
"'",
")",
";",
"if",
"(",
"pos",
"==",
"-",
"1",
")",
"{",
"// XXX",
"// should give more detail about the illegal argument",
"throw",
"new",
"IllegalArgumentException",
"(",
")",
";",
"}",
"String",
"key",
"=",
"parseName",
"(",
"pair",
".",
"substring",
"(",
"0",
",",
"pos",
")",
",",
"sb",
")",
";",
"String",
"val",
"=",
"parseName",
"(",
"pair",
".",
"substring",
"(",
"pos",
"+",
"1",
",",
"pair",
".",
"length",
"(",
")",
")",
",",
"sb",
")",
";",
"if",
"(",
"ht",
".",
"containsKey",
"(",
"key",
")",
")",
"{",
"String",
"oldVals",
"[",
"]",
"=",
"ht",
".",
"get",
"(",
"key",
")",
";",
"valArray",
"=",
"new",
"String",
"[",
"oldVals",
".",
"length",
"+",
"1",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"oldVals",
".",
"length",
";",
"i",
"++",
")",
"{",
"valArray",
"[",
"i",
"]",
"=",
"oldVals",
"[",
"i",
"]",
";",
"}",
"valArray",
"[",
"oldVals",
".",
"length",
"]",
"=",
"val",
";",
"}",
"else",
"{",
"valArray",
"=",
"new",
"String",
"[",
"1",
"]",
";",
"valArray",
"[",
"0",
"]",
"=",
"val",
";",
"}",
"ht",
".",
"put",
"(",
"key",
",",
"valArray",
")",
";",
"}",
"return",
"ht",
";",
"}"
] |
Parses a query string passed from the client to the
server and builds a <code>HashTable</code> object
with key-value pairs.
The query string should be in the form of a string
packaged by the GET or POST method, that is, it
should have key-value pairs in the form <i>key=value</i>,
with each pair separated from the next by a & character.
<p>A key can appear more than once in the query string
with different values. However, the key appears only once in
the hashtable, with its value being
an array of strings containing the multiple values sent
by the query string.
<p>The keys and values in the hashtable are stored in their
decoded form, so
any + characters are converted to spaces, and characters
sent in hexadecimal notation (like <i>%xx</i>) are
converted to ASCII characters.
@param s a string containing the query to be parsed
@return a <code>HashTable</code> object built
from the parsed key-value pairs
@exception IllegalArgumentException if the query string is invalid
|
[
"Parses",
"a",
"query",
"string",
"passed",
"from",
"the",
"client",
"to",
"the",
"server",
"and",
"builds",
"a",
"<code",
">",
"HashTable<",
"/",
"code",
">",
"object",
"with",
"key",
"-",
"value",
"pairs",
".",
"The",
"query",
"string",
"should",
"be",
"in",
"the",
"form",
"of",
"a",
"string",
"packaged",
"by",
"the",
"GET",
"or",
"POST",
"method",
"that",
"is",
"it",
"should",
"have",
"key",
"-",
"value",
"pairs",
"in",
"the",
"form",
"<i",
">",
"key",
"=",
"value<",
"/",
"i",
">",
"with",
"each",
"pair",
"separated",
"from",
"the",
"next",
"by",
"a",
"&",
";",
"character",
"."
] |
train
|
https://github.com/jboss/jboss-servlet-api_spec/blob/5bc96f2b833c072baff6eb8ae49bc7b5e503e9b2/src/main/java/javax/servlet/http/HttpUtils.java#L117-L153
|
biojava/biojava
|
biojava-structure/src/main/java/org/biojava/nbio/structure/secstruc/SecStrucCalc.java
|
SecStrucCalc.isBonded
|
private boolean isBonded(int i, int j) {
"""
Test if two groups are forming an H-Bond. The bond tested is
from the CO of group i to the NH of group j. Acceptor (i) and
donor (j). The donor of i has to be j, and the acceptor of j
has to be i.
DSSP defines H-Bonds if the energy < -500 cal/mol.
@param i group one
@param j group two
@return flag if the two are forming an Hbond
"""
SecStrucState one = getSecStrucState(i);
SecStrucState two = getSecStrucState(j);
double don1e = one.getDonor1().getEnergy();
double don2e = one.getDonor2().getEnergy();
double acc1e = two.getAccept1().getEnergy();
double acc2e = two.getAccept2().getEnergy();
int don1p = one.getDonor1().getPartner();
int don2p = one.getDonor2().getPartner();
int acc1p = two.getAccept1().getPartner();
int acc2p = two.getAccept2().getPartner();
//Either donor from i is j, or accept from j is i
boolean hbond = (don1p == j && don1e < HBONDHIGHENERGY) ||
(don2p == j && don2e < HBONDHIGHENERGY) ||
(acc1p == i && acc1e < HBONDHIGHENERGY) ||
(acc2p == i && acc2e < HBONDHIGHENERGY);
if (hbond){
logger.debug("*** H-bond from CO of {} to NH of {}", i, j);
return true;
}
return false ;
}
|
java
|
private boolean isBonded(int i, int j) {
SecStrucState one = getSecStrucState(i);
SecStrucState two = getSecStrucState(j);
double don1e = one.getDonor1().getEnergy();
double don2e = one.getDonor2().getEnergy();
double acc1e = two.getAccept1().getEnergy();
double acc2e = two.getAccept2().getEnergy();
int don1p = one.getDonor1().getPartner();
int don2p = one.getDonor2().getPartner();
int acc1p = two.getAccept1().getPartner();
int acc2p = two.getAccept2().getPartner();
//Either donor from i is j, or accept from j is i
boolean hbond = (don1p == j && don1e < HBONDHIGHENERGY) ||
(don2p == j && don2e < HBONDHIGHENERGY) ||
(acc1p == i && acc1e < HBONDHIGHENERGY) ||
(acc2p == i && acc2e < HBONDHIGHENERGY);
if (hbond){
logger.debug("*** H-bond from CO of {} to NH of {}", i, j);
return true;
}
return false ;
}
|
[
"private",
"boolean",
"isBonded",
"(",
"int",
"i",
",",
"int",
"j",
")",
"{",
"SecStrucState",
"one",
"=",
"getSecStrucState",
"(",
"i",
")",
";",
"SecStrucState",
"two",
"=",
"getSecStrucState",
"(",
"j",
")",
";",
"double",
"don1e",
"=",
"one",
".",
"getDonor1",
"(",
")",
".",
"getEnergy",
"(",
")",
";",
"double",
"don2e",
"=",
"one",
".",
"getDonor2",
"(",
")",
".",
"getEnergy",
"(",
")",
";",
"double",
"acc1e",
"=",
"two",
".",
"getAccept1",
"(",
")",
".",
"getEnergy",
"(",
")",
";",
"double",
"acc2e",
"=",
"two",
".",
"getAccept2",
"(",
")",
".",
"getEnergy",
"(",
")",
";",
"int",
"don1p",
"=",
"one",
".",
"getDonor1",
"(",
")",
".",
"getPartner",
"(",
")",
";",
"int",
"don2p",
"=",
"one",
".",
"getDonor2",
"(",
")",
".",
"getPartner",
"(",
")",
";",
"int",
"acc1p",
"=",
"two",
".",
"getAccept1",
"(",
")",
".",
"getPartner",
"(",
")",
";",
"int",
"acc2p",
"=",
"two",
".",
"getAccept2",
"(",
")",
".",
"getPartner",
"(",
")",
";",
"//Either donor from i is j, or accept from j is i",
"boolean",
"hbond",
"=",
"(",
"don1p",
"==",
"j",
"&&",
"don1e",
"<",
"HBONDHIGHENERGY",
")",
"||",
"(",
"don2p",
"==",
"j",
"&&",
"don2e",
"<",
"HBONDHIGHENERGY",
")",
"||",
"(",
"acc1p",
"==",
"i",
"&&",
"acc1e",
"<",
"HBONDHIGHENERGY",
")",
"||",
"(",
"acc2p",
"==",
"i",
"&&",
"acc2e",
"<",
"HBONDHIGHENERGY",
")",
";",
"if",
"(",
"hbond",
")",
"{",
"logger",
".",
"debug",
"(",
"\"*** H-bond from CO of {} to NH of {}\"",
",",
"i",
",",
"j",
")",
";",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] |
Test if two groups are forming an H-Bond. The bond tested is
from the CO of group i to the NH of group j. Acceptor (i) and
donor (j). The donor of i has to be j, and the acceptor of j
has to be i.
DSSP defines H-Bonds if the energy < -500 cal/mol.
@param i group one
@param j group two
@return flag if the two are forming an Hbond
|
[
"Test",
"if",
"two",
"groups",
"are",
"forming",
"an",
"H",
"-",
"Bond",
".",
"The",
"bond",
"tested",
"is",
"from",
"the",
"CO",
"of",
"group",
"i",
"to",
"the",
"NH",
"of",
"group",
"j",
".",
"Acceptor",
"(",
"i",
")",
"and",
"donor",
"(",
"j",
")",
".",
"The",
"donor",
"of",
"i",
"has",
"to",
"be",
"j",
"and",
"the",
"acceptor",
"of",
"j",
"has",
"to",
"be",
"i",
".",
"DSSP",
"defines",
"H",
"-",
"Bonds",
"if",
"the",
"energy",
"<",
"-",
"500",
"cal",
"/",
"mol",
"."
] |
train
|
https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/secstruc/SecStrucCalc.java#L974-L1000
|
jbundle/jbundle
|
thin/base/util/util/src/main/java/org/jbundle/thin/base/util/Application.java
|
Application.getLocale
|
public Locale getLocale() {
"""
Get the current locale.
(Based on the current language).
@return The current locale.
"""
String strLanguage = this.getProperty(Params.LANGUAGE);
if ((strLanguage != null) && (strLanguage.length() > 0))
{
Locale locale = Locale.getDefault();
if (!strLanguage.equalsIgnoreCase(locale.getLanguage()))
locale = new Locale(strLanguage, "");
if (locale != null)
{
try {
Locale.setDefault(locale);
} catch (java.security.AccessControlException ex) {
Util.getLogger().warning("Can't change locale"); // Ignore and continue
}
}
}
return Locale.getDefault();
}
|
java
|
public Locale getLocale()
{
String strLanguage = this.getProperty(Params.LANGUAGE);
if ((strLanguage != null) && (strLanguage.length() > 0))
{
Locale locale = Locale.getDefault();
if (!strLanguage.equalsIgnoreCase(locale.getLanguage()))
locale = new Locale(strLanguage, "");
if (locale != null)
{
try {
Locale.setDefault(locale);
} catch (java.security.AccessControlException ex) {
Util.getLogger().warning("Can't change locale"); // Ignore and continue
}
}
}
return Locale.getDefault();
}
|
[
"public",
"Locale",
"getLocale",
"(",
")",
"{",
"String",
"strLanguage",
"=",
"this",
".",
"getProperty",
"(",
"Params",
".",
"LANGUAGE",
")",
";",
"if",
"(",
"(",
"strLanguage",
"!=",
"null",
")",
"&&",
"(",
"strLanguage",
".",
"length",
"(",
")",
">",
"0",
")",
")",
"{",
"Locale",
"locale",
"=",
"Locale",
".",
"getDefault",
"(",
")",
";",
"if",
"(",
"!",
"strLanguage",
".",
"equalsIgnoreCase",
"(",
"locale",
".",
"getLanguage",
"(",
")",
")",
")",
"locale",
"=",
"new",
"Locale",
"(",
"strLanguage",
",",
"\"\"",
")",
";",
"if",
"(",
"locale",
"!=",
"null",
")",
"{",
"try",
"{",
"Locale",
".",
"setDefault",
"(",
"locale",
")",
";",
"}",
"catch",
"(",
"java",
".",
"security",
".",
"AccessControlException",
"ex",
")",
"{",
"Util",
".",
"getLogger",
"(",
")",
".",
"warning",
"(",
"\"Can't change locale\"",
")",
";",
"// Ignore and continue",
"}",
"}",
"}",
"return",
"Locale",
".",
"getDefault",
"(",
")",
";",
"}"
] |
Get the current locale.
(Based on the current language).
@return The current locale.
|
[
"Get",
"the",
"current",
"locale",
".",
"(",
"Based",
"on",
"the",
"current",
"language",
")",
"."
] |
train
|
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/thin/base/util/util/src/main/java/org/jbundle/thin/base/util/Application.java#L853-L871
|
apache/flink
|
flink-connectors/flink-connector-kinesis/src/main/java/org/apache/flink/streaming/connectors/kinesis/internals/KinesisDataFetcher.java
|
KinesisDataFetcher.emitRecordAndUpdateState
|
protected void emitRecordAndUpdateState(T record, long recordTimestamp, int shardStateIndex, SequenceNumber lastSequenceNumber) {
"""
Atomic operation to collect a record and update state to the sequence number of the record.
This method is called by {@link ShardConsumer}s.
@param record the record to collect
@param recordTimestamp timestamp to attach to the collected record
@param shardStateIndex index of the shard to update in subscribedShardsState;
this index should be the returned value from
{@link KinesisDataFetcher#registerNewSubscribedShardState(KinesisStreamShardState)}, called
when the shard state was registered.
@param lastSequenceNumber the last sequence number value to update
"""
// track per shard watermarks and emit timestamps extracted from the record,
// when a watermark assigner was configured.
if (periodicWatermarkAssigner != null) {
ShardWatermarkState sws = shardWatermarks.get(shardStateIndex);
Preconditions.checkNotNull(
sws, "shard watermark state initialized in registerNewSubscribedShardState");
recordTimestamp =
sws.periodicWatermarkAssigner.extractTimestamp(record, sws.lastRecordTimestamp);
sws.lastRecordTimestamp = recordTimestamp;
sws.lastUpdated = getCurrentTimeMillis();
}
synchronized (checkpointLock) {
if (record != null) {
sourceContext.collectWithTimestamp(record, recordTimestamp);
} else {
LOG.warn("Skipping non-deserializable record at sequence number {} of shard {}.",
lastSequenceNumber,
subscribedShardsState.get(shardStateIndex).getStreamShardHandle());
}
updateState(shardStateIndex, lastSequenceNumber);
}
}
|
java
|
protected void emitRecordAndUpdateState(T record, long recordTimestamp, int shardStateIndex, SequenceNumber lastSequenceNumber) {
// track per shard watermarks and emit timestamps extracted from the record,
// when a watermark assigner was configured.
if (periodicWatermarkAssigner != null) {
ShardWatermarkState sws = shardWatermarks.get(shardStateIndex);
Preconditions.checkNotNull(
sws, "shard watermark state initialized in registerNewSubscribedShardState");
recordTimestamp =
sws.periodicWatermarkAssigner.extractTimestamp(record, sws.lastRecordTimestamp);
sws.lastRecordTimestamp = recordTimestamp;
sws.lastUpdated = getCurrentTimeMillis();
}
synchronized (checkpointLock) {
if (record != null) {
sourceContext.collectWithTimestamp(record, recordTimestamp);
} else {
LOG.warn("Skipping non-deserializable record at sequence number {} of shard {}.",
lastSequenceNumber,
subscribedShardsState.get(shardStateIndex).getStreamShardHandle());
}
updateState(shardStateIndex, lastSequenceNumber);
}
}
|
[
"protected",
"void",
"emitRecordAndUpdateState",
"(",
"T",
"record",
",",
"long",
"recordTimestamp",
",",
"int",
"shardStateIndex",
",",
"SequenceNumber",
"lastSequenceNumber",
")",
"{",
"// track per shard watermarks and emit timestamps extracted from the record,",
"// when a watermark assigner was configured.",
"if",
"(",
"periodicWatermarkAssigner",
"!=",
"null",
")",
"{",
"ShardWatermarkState",
"sws",
"=",
"shardWatermarks",
".",
"get",
"(",
"shardStateIndex",
")",
";",
"Preconditions",
".",
"checkNotNull",
"(",
"sws",
",",
"\"shard watermark state initialized in registerNewSubscribedShardState\"",
")",
";",
"recordTimestamp",
"=",
"sws",
".",
"periodicWatermarkAssigner",
".",
"extractTimestamp",
"(",
"record",
",",
"sws",
".",
"lastRecordTimestamp",
")",
";",
"sws",
".",
"lastRecordTimestamp",
"=",
"recordTimestamp",
";",
"sws",
".",
"lastUpdated",
"=",
"getCurrentTimeMillis",
"(",
")",
";",
"}",
"synchronized",
"(",
"checkpointLock",
")",
"{",
"if",
"(",
"record",
"!=",
"null",
")",
"{",
"sourceContext",
".",
"collectWithTimestamp",
"(",
"record",
",",
"recordTimestamp",
")",
";",
"}",
"else",
"{",
"LOG",
".",
"warn",
"(",
"\"Skipping non-deserializable record at sequence number {} of shard {}.\"",
",",
"lastSequenceNumber",
",",
"subscribedShardsState",
".",
"get",
"(",
"shardStateIndex",
")",
".",
"getStreamShardHandle",
"(",
")",
")",
";",
"}",
"updateState",
"(",
"shardStateIndex",
",",
"lastSequenceNumber",
")",
";",
"}",
"}"
] |
Atomic operation to collect a record and update state to the sequence number of the record.
This method is called by {@link ShardConsumer}s.
@param record the record to collect
@param recordTimestamp timestamp to attach to the collected record
@param shardStateIndex index of the shard to update in subscribedShardsState;
this index should be the returned value from
{@link KinesisDataFetcher#registerNewSubscribedShardState(KinesisStreamShardState)}, called
when the shard state was registered.
@param lastSequenceNumber the last sequence number value to update
|
[
"Atomic",
"operation",
"to",
"collect",
"a",
"record",
"and",
"update",
"state",
"to",
"the",
"sequence",
"number",
"of",
"the",
"record",
".",
"This",
"method",
"is",
"called",
"by",
"{",
"@link",
"ShardConsumer",
"}",
"s",
"."
] |
train
|
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-connectors/flink-connector-kinesis/src/main/java/org/apache/flink/streaming/connectors/kinesis/internals/KinesisDataFetcher.java#L605-L629
|
mgormley/pacaya
|
src/main/java/edu/jhu/pacaya/autodiff/Toposort.java
|
Toposort.toposort
|
public static <T> List<T> toposort(List<T> inputs,
T root, final Deps<T> deps, boolean isFullCut) {
"""
Gets a topological sort for the graph, where the depth-first search is cutoff by an input set.
@param inputs The input set which is excluded from the graph.
@param root The root of the graph.
@param deps Functional description of the graph's dependencies.
@param isFullCut Whether the input set is a full cut of the graph.
@return The topological sort.
"""
// Get inputs as a set.
final HashSet<T> inputSet = new HashSet<T>(inputs);
if (inputSet.size() != inputs.size()) {
throw new IllegalStateException("Multiple copies of module in inputs list: " + inputs);
}
return toposort(inputSet, root, deps, isFullCut);
}
|
java
|
public static <T> List<T> toposort(List<T> inputs,
T root, final Deps<T> deps, boolean isFullCut) {
// Get inputs as a set.
final HashSet<T> inputSet = new HashSet<T>(inputs);
if (inputSet.size() != inputs.size()) {
throw new IllegalStateException("Multiple copies of module in inputs list: " + inputs);
}
return toposort(inputSet, root, deps, isFullCut);
}
|
[
"public",
"static",
"<",
"T",
">",
"List",
"<",
"T",
">",
"toposort",
"(",
"List",
"<",
"T",
">",
"inputs",
",",
"T",
"root",
",",
"final",
"Deps",
"<",
"T",
">",
"deps",
",",
"boolean",
"isFullCut",
")",
"{",
"// Get inputs as a set.",
"final",
"HashSet",
"<",
"T",
">",
"inputSet",
"=",
"new",
"HashSet",
"<",
"T",
">",
"(",
"inputs",
")",
";",
"if",
"(",
"inputSet",
".",
"size",
"(",
")",
"!=",
"inputs",
".",
"size",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"Multiple copies of module in inputs list: \"",
"+",
"inputs",
")",
";",
"}",
"return",
"toposort",
"(",
"inputSet",
",",
"root",
",",
"deps",
",",
"isFullCut",
")",
";",
"}"
] |
Gets a topological sort for the graph, where the depth-first search is cutoff by an input set.
@param inputs The input set which is excluded from the graph.
@param root The root of the graph.
@param deps Functional description of the graph's dependencies.
@param isFullCut Whether the input set is a full cut of the graph.
@return The topological sort.
|
[
"Gets",
"a",
"topological",
"sort",
"for",
"the",
"graph",
"where",
"the",
"depth",
"-",
"first",
"search",
"is",
"cutoff",
"by",
"an",
"input",
"set",
"."
] |
train
|
https://github.com/mgormley/pacaya/blob/786294cbac7cc65dbc32210c10acc32ed0c69233/src/main/java/edu/jhu/pacaya/autodiff/Toposort.java#L70-L78
|
jbundle/jbundle
|
app/program/db/src/main/java/org/jbundle/app/program/db/ClassInfoField.java
|
ClassInfoField.setupDefaultView
|
public ScreenComponent setupDefaultView(ScreenLoc itsLocation, ComponentParent targetScreen, Convert converter, int iDisplayFieldDesc, Map<String, Object> properties) {
"""
Set up the default screen control for this field.
@param itsLocation Location of this component on screen (ie., GridBagConstraint).
@param targetScreen Where to place this component (ie., Parent screen or GridBagLayout).
@param converter The converter to set the screenfield to.
@param iDisplayFieldDesc Display the label? (optional).
@param properties Extra properties
@return Return the component or ScreenField that is created for this field.
"""
return this.setupTableLookup(itsLocation, targetScreen, converter, iDisplayFieldDesc, this.makeReferenceRecord(), ClassInfo.CLASS_NAME_KEY, ClassInfo.CLASS_NAME, true, true);
}
|
java
|
public ScreenComponent setupDefaultView(ScreenLoc itsLocation, ComponentParent targetScreen, Convert converter, int iDisplayFieldDesc, Map<String, Object> properties)
{
return this.setupTableLookup(itsLocation, targetScreen, converter, iDisplayFieldDesc, this.makeReferenceRecord(), ClassInfo.CLASS_NAME_KEY, ClassInfo.CLASS_NAME, true, true);
}
|
[
"public",
"ScreenComponent",
"setupDefaultView",
"(",
"ScreenLoc",
"itsLocation",
",",
"ComponentParent",
"targetScreen",
",",
"Convert",
"converter",
",",
"int",
"iDisplayFieldDesc",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"properties",
")",
"{",
"return",
"this",
".",
"setupTableLookup",
"(",
"itsLocation",
",",
"targetScreen",
",",
"converter",
",",
"iDisplayFieldDesc",
",",
"this",
".",
"makeReferenceRecord",
"(",
")",
",",
"ClassInfo",
".",
"CLASS_NAME_KEY",
",",
"ClassInfo",
".",
"CLASS_NAME",
",",
"true",
",",
"true",
")",
";",
"}"
] |
Set up the default screen control for this field.
@param itsLocation Location of this component on screen (ie., GridBagConstraint).
@param targetScreen Where to place this component (ie., Parent screen or GridBagLayout).
@param converter The converter to set the screenfield to.
@param iDisplayFieldDesc Display the label? (optional).
@param properties Extra properties
@return Return the component or ScreenField that is created for this field.
|
[
"Set",
"up",
"the",
"default",
"screen",
"control",
"for",
"this",
"field",
"."
] |
train
|
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/app/program/db/src/main/java/org/jbundle/app/program/db/ClassInfoField.java#L75-L78
|
krummas/DrizzleJDBC
|
src/main/java/org/drizzle/jdbc/DrizzleDataBaseMetaData.java
|
DrizzleDataBaseMetaData.getPrimaryKeys
|
@Override
public ResultSet getPrimaryKeys(final String catalog, final String schema, final String table) throws SQLException {
"""
Retrieves a description of the given table's primary key columns. They are ordered by COLUMN_NAME.
<p/>
<P>Each primary key column description has the following columns: <OL> <LI><B>TABLE_CAT</B> String => table
catalog (may be <code>null</code>) <LI><B>TABLE_SCHEM</B> String => table schema (may be <code>null</code>)
<LI><B>TABLE_NAME</B> String => table name <LI><B>COLUMN_NAME</B> String => column name <LI><B>KEY_SEQ</B> short
=> sequence number within primary key( a value of 1 represents the first column of the primary key, a value of 2
would represent the second column within the primary key). <LI><B>PK_NAME</B> String => primary key name (may be
<code>null</code>) </OL>
@param catalog a catalog name; must match the catalog name as it is stored in the database; "" retrieves those
without a catalog; <code>null</code> means that the catalog name should not be used to narrow the
search
@param schema a schema name; must match the schema name as it is stored in the database; "" retrieves those
without a schema; <code>null</code> means that the schema name should not be used to narrow the
search
@param table a table name; must match the table name as it is stored in the database
@return <code>ResultSet</code> - each row is a primary key column description
@throws java.sql.SQLException if a database access error occurs
"""
String query = "SELECT null TABLE_CAT, " +
"columns.table_schema TABLE_SCHEM, " +
"columns.table_name, " +
"columns.column_name, " +
"kcu.ordinal_position KEY_SEQ," +
"null pk_name " +
"FROM information_schema.columns " +
"INNER JOIN information_schema.key_column_usage kcu "+
"ON kcu.constraint_schema = columns.table_schema AND " +
"columns.table_name = kcu.table_name AND " +
"columns.column_name = kcu.column_name " +
"WHERE columns.table_name='" + table + "' AND kcu.constraint_name='PRIMARY'";
if (schema != null) {
query += " AND columns.table_schema = '" + schema + "'";
}
query += " ORDER BY columns.column_name";
final Statement stmt = getConnection().createStatement();
return stmt.executeQuery(query);
}
|
java
|
@Override
public ResultSet getPrimaryKeys(final String catalog, final String schema, final String table) throws SQLException {
String query = "SELECT null TABLE_CAT, " +
"columns.table_schema TABLE_SCHEM, " +
"columns.table_name, " +
"columns.column_name, " +
"kcu.ordinal_position KEY_SEQ," +
"null pk_name " +
"FROM information_schema.columns " +
"INNER JOIN information_schema.key_column_usage kcu "+
"ON kcu.constraint_schema = columns.table_schema AND " +
"columns.table_name = kcu.table_name AND " +
"columns.column_name = kcu.column_name " +
"WHERE columns.table_name='" + table + "' AND kcu.constraint_name='PRIMARY'";
if (schema != null) {
query += " AND columns.table_schema = '" + schema + "'";
}
query += " ORDER BY columns.column_name";
final Statement stmt = getConnection().createStatement();
return stmt.executeQuery(query);
}
|
[
"@",
"Override",
"public",
"ResultSet",
"getPrimaryKeys",
"(",
"final",
"String",
"catalog",
",",
"final",
"String",
"schema",
",",
"final",
"String",
"table",
")",
"throws",
"SQLException",
"{",
"String",
"query",
"=",
"\"SELECT null TABLE_CAT, \"",
"+",
"\"columns.table_schema TABLE_SCHEM, \"",
"+",
"\"columns.table_name, \"",
"+",
"\"columns.column_name, \"",
"+",
"\"kcu.ordinal_position KEY_SEQ,\"",
"+",
"\"null pk_name \"",
"+",
"\"FROM information_schema.columns \"",
"+",
"\"INNER JOIN information_schema.key_column_usage kcu \"",
"+",
"\"ON kcu.constraint_schema = columns.table_schema AND \"",
"+",
"\"columns.table_name = kcu.table_name AND \"",
"+",
"\"columns.column_name = kcu.column_name \"",
"+",
"\"WHERE columns.table_name='\"",
"+",
"table",
"+",
"\"' AND kcu.constraint_name='PRIMARY'\"",
";",
"if",
"(",
"schema",
"!=",
"null",
")",
"{",
"query",
"+=",
"\" AND columns.table_schema = '\"",
"+",
"schema",
"+",
"\"'\"",
";",
"}",
"query",
"+=",
"\" ORDER BY columns.column_name\"",
";",
"final",
"Statement",
"stmt",
"=",
"getConnection",
"(",
")",
".",
"createStatement",
"(",
")",
";",
"return",
"stmt",
".",
"executeQuery",
"(",
"query",
")",
";",
"}"
] |
Retrieves a description of the given table's primary key columns. They are ordered by COLUMN_NAME.
<p/>
<P>Each primary key column description has the following columns: <OL> <LI><B>TABLE_CAT</B> String => table
catalog (may be <code>null</code>) <LI><B>TABLE_SCHEM</B> String => table schema (may be <code>null</code>)
<LI><B>TABLE_NAME</B> String => table name <LI><B>COLUMN_NAME</B> String => column name <LI><B>KEY_SEQ</B> short
=> sequence number within primary key( a value of 1 represents the first column of the primary key, a value of 2
would represent the second column within the primary key). <LI><B>PK_NAME</B> String => primary key name (may be
<code>null</code>) </OL>
@param catalog a catalog name; must match the catalog name as it is stored in the database; "" retrieves those
without a catalog; <code>null</code> means that the catalog name should not be used to narrow the
search
@param schema a schema name; must match the schema name as it is stored in the database; "" retrieves those
without a schema; <code>null</code> means that the schema name should not be used to narrow the
search
@param table a table name; must match the table name as it is stored in the database
@return <code>ResultSet</code> - each row is a primary key column description
@throws java.sql.SQLException if a database access error occurs
|
[
"Retrieves",
"a",
"description",
"of",
"the",
"given",
"table",
"s",
"primary",
"key",
"columns",
".",
"They",
"are",
"ordered",
"by",
"COLUMN_NAME",
".",
"<p",
"/",
">",
"<P",
">",
"Each",
"primary",
"key",
"column",
"description",
"has",
"the",
"following",
"columns",
":",
"<OL",
">",
"<LI",
">",
"<B",
">",
"TABLE_CAT<",
"/",
"B",
">",
"String",
"=",
">",
"table",
"catalog",
"(",
"may",
"be",
"<code",
">",
"null<",
"/",
"code",
">",
")",
"<LI",
">",
"<B",
">",
"TABLE_SCHEM<",
"/",
"B",
">",
"String",
"=",
">",
"table",
"schema",
"(",
"may",
"be",
"<code",
">",
"null<",
"/",
"code",
">",
")",
"<LI",
">",
"<B",
">",
"TABLE_NAME<",
"/",
"B",
">",
"String",
"=",
">",
"table",
"name",
"<LI",
">",
"<B",
">",
"COLUMN_NAME<",
"/",
"B",
">",
"String",
"=",
">",
"column",
"name",
"<LI",
">",
"<B",
">",
"KEY_SEQ<",
"/",
"B",
">",
"short",
"=",
">",
"sequence",
"number",
"within",
"primary",
"key",
"(",
"a",
"value",
"of",
"1",
"represents",
"the",
"first",
"column",
"of",
"the",
"primary",
"key",
"a",
"value",
"of",
"2",
"would",
"represent",
"the",
"second",
"column",
"within",
"the",
"primary",
"key",
")",
".",
"<LI",
">",
"<B",
">",
"PK_NAME<",
"/",
"B",
">",
"String",
"=",
">",
"primary",
"key",
"name",
"(",
"may",
"be",
"<code",
">",
"null<",
"/",
"code",
">",
")",
"<",
"/",
"OL",
">"
] |
train
|
https://github.com/krummas/DrizzleJDBC/blob/716f31fd71f3cc289edf69844d8117deb86d98d6/src/main/java/org/drizzle/jdbc/DrizzleDataBaseMetaData.java#L58-L79
|
xmlet/XsdAsmFaster
|
src/main/java/org/xmlet/xsdasmfaster/classes/XsdAsmInterfaces.java
|
XsdAsmInterfaces.createSequenceClasses
|
private void createSequenceClasses(XsdAbstractElement sequenceElement, ClassWriter classWriter, String className, String typeName, String nextTypeName, String apiName, boolean isFirst) {
"""
Creates classes and methods required to implement the sequence.
@param sequenceElement The current sequence element.
@param classWriter The {@link ClassWriter} of the first class, which contains the sequence.
@param className The name of the class which contains the sequence.
@param typeName The current sequence element type name.
@param nextTypeName The next sequence element type name.
@param apiName The name of the generated fluent interface.
@param isFirst Indication if this is the first element of the sequence.
"""
List<XsdElement> elements = null;
if (sequenceElement instanceof XsdElement) {
elements = Collections.singletonList((XsdElement) sequenceElement);
}
if (sequenceElement instanceof XsdGroup || sequenceElement instanceof XsdChoice || sequenceElement instanceof XsdAll) {
elements = getAllElementsRecursively(sequenceElement);
}
if (elements != null){
if (isFirst){
createFirstSequenceInterface(classWriter, className, nextTypeName, apiName, elements);
} else {
createElementsForSequence(className, typeName, nextTypeName, apiName, elements);
}
}
}
|
java
|
private void createSequenceClasses(XsdAbstractElement sequenceElement, ClassWriter classWriter, String className, String typeName, String nextTypeName, String apiName, boolean isFirst){
List<XsdElement> elements = null;
if (sequenceElement instanceof XsdElement) {
elements = Collections.singletonList((XsdElement) sequenceElement);
}
if (sequenceElement instanceof XsdGroup || sequenceElement instanceof XsdChoice || sequenceElement instanceof XsdAll) {
elements = getAllElementsRecursively(sequenceElement);
}
if (elements != null){
if (isFirst){
createFirstSequenceInterface(classWriter, className, nextTypeName, apiName, elements);
} else {
createElementsForSequence(className, typeName, nextTypeName, apiName, elements);
}
}
}
|
[
"private",
"void",
"createSequenceClasses",
"(",
"XsdAbstractElement",
"sequenceElement",
",",
"ClassWriter",
"classWriter",
",",
"String",
"className",
",",
"String",
"typeName",
",",
"String",
"nextTypeName",
",",
"String",
"apiName",
",",
"boolean",
"isFirst",
")",
"{",
"List",
"<",
"XsdElement",
">",
"elements",
"=",
"null",
";",
"if",
"(",
"sequenceElement",
"instanceof",
"XsdElement",
")",
"{",
"elements",
"=",
"Collections",
".",
"singletonList",
"(",
"(",
"XsdElement",
")",
"sequenceElement",
")",
";",
"}",
"if",
"(",
"sequenceElement",
"instanceof",
"XsdGroup",
"||",
"sequenceElement",
"instanceof",
"XsdChoice",
"||",
"sequenceElement",
"instanceof",
"XsdAll",
")",
"{",
"elements",
"=",
"getAllElementsRecursively",
"(",
"sequenceElement",
")",
";",
"}",
"if",
"(",
"elements",
"!=",
"null",
")",
"{",
"if",
"(",
"isFirst",
")",
"{",
"createFirstSequenceInterface",
"(",
"classWriter",
",",
"className",
",",
"nextTypeName",
",",
"apiName",
",",
"elements",
")",
";",
"}",
"else",
"{",
"createElementsForSequence",
"(",
"className",
",",
"typeName",
",",
"nextTypeName",
",",
"apiName",
",",
"elements",
")",
";",
"}",
"}",
"}"
] |
Creates classes and methods required to implement the sequence.
@param sequenceElement The current sequence element.
@param classWriter The {@link ClassWriter} of the first class, which contains the sequence.
@param className The name of the class which contains the sequence.
@param typeName The current sequence element type name.
@param nextTypeName The next sequence element type name.
@param apiName The name of the generated fluent interface.
@param isFirst Indication if this is the first element of the sequence.
|
[
"Creates",
"classes",
"and",
"methods",
"required",
"to",
"implement",
"the",
"sequence",
"."
] |
train
|
https://github.com/xmlet/XsdAsmFaster/blob/ccb78f9dd4b957ad5ac1ca349eaf24338c421e94/src/main/java/org/xmlet/xsdasmfaster/classes/XsdAsmInterfaces.java#L425-L443
|
micronaut-projects/micronaut-core
|
inject-java/src/main/java/io/micronaut/annotation/processing/JavaAnnotationMetadataBuilder.java
|
JavaAnnotationMetadataBuilder.hasAnnotation
|
@Override
public boolean hasAnnotation(Element element, Class<? extends Annotation> ann) {
"""
Checks if a method has an annotation.
@param element The method
@param ann The annotation to look for
@return Whether if the method has the annotation
"""
List<? extends AnnotationMirror> annotationMirrors = element.getAnnotationMirrors();
for (AnnotationMirror annotationMirror : annotationMirrors) {
if (annotationMirror.getAnnotationType().toString().equals(ann.getName())) {
return true;
}
}
return false;
}
|
java
|
@Override
public boolean hasAnnotation(Element element, Class<? extends Annotation> ann) {
List<? extends AnnotationMirror> annotationMirrors = element.getAnnotationMirrors();
for (AnnotationMirror annotationMirror : annotationMirrors) {
if (annotationMirror.getAnnotationType().toString().equals(ann.getName())) {
return true;
}
}
return false;
}
|
[
"@",
"Override",
"public",
"boolean",
"hasAnnotation",
"(",
"Element",
"element",
",",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
"ann",
")",
"{",
"List",
"<",
"?",
"extends",
"AnnotationMirror",
">",
"annotationMirrors",
"=",
"element",
".",
"getAnnotationMirrors",
"(",
")",
";",
"for",
"(",
"AnnotationMirror",
"annotationMirror",
":",
"annotationMirrors",
")",
"{",
"if",
"(",
"annotationMirror",
".",
"getAnnotationType",
"(",
")",
".",
"toString",
"(",
")",
".",
"equals",
"(",
"ann",
".",
"getName",
"(",
")",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] |
Checks if a method has an annotation.
@param element The method
@param ann The annotation to look for
@return Whether if the method has the annotation
|
[
"Checks",
"if",
"a",
"method",
"has",
"an",
"annotation",
"."
] |
train
|
https://github.com/micronaut-projects/micronaut-core/blob/c31f5b03ce0eb88c2f6470710987db03b8967d5c/inject-java/src/main/java/io/micronaut/annotation/processing/JavaAnnotationMetadataBuilder.java#L404-L413
|
googleapis/google-cloud-java
|
google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/deprecated/InstanceInfo.java
|
InstanceInfo.newBuilder
|
public static Builder newBuilder(InstanceId instanceId, MachineTypeId machineType) {
"""
Returns a builder for an {@code InstanceInfo} object given the instance identity and the
machine type.
"""
return new BuilderImpl(instanceId).setMachineType(machineType);
}
|
java
|
public static Builder newBuilder(InstanceId instanceId, MachineTypeId machineType) {
return new BuilderImpl(instanceId).setMachineType(machineType);
}
|
[
"public",
"static",
"Builder",
"newBuilder",
"(",
"InstanceId",
"instanceId",
",",
"MachineTypeId",
"machineType",
")",
"{",
"return",
"new",
"BuilderImpl",
"(",
"instanceId",
")",
".",
"setMachineType",
"(",
"machineType",
")",
";",
"}"
] |
Returns a builder for an {@code InstanceInfo} object given the instance identity and the
machine type.
|
[
"Returns",
"a",
"builder",
"for",
"an",
"{"
] |
train
|
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/deprecated/InstanceInfo.java#L636-L638
|
kaazing/gateway
|
samples/security/TokenLoginModule.java
|
TokenLoginModule.processToken
|
private void processToken(String tokenData) throws JSONException, LoginException {
"""
Validate the token and extract the username to add to shared state. An exception is thrown if the token is found to be
invalid
This method expects the token to be in JSON format:
{
username: "joe",
nonce: "5171483440790326",
tokenExpires: "2017-04-20T15:48:49.187Z"
}
"""
JSONObject json = new JSONObject(tokenData);
// Validate that the token hasn't expired.
ZonedDateTime expires = ZonedDateTime.parse(json.getString("tokenExpires"));
ZonedDateTime now = ZonedDateTime.now(expires.getZone());
if (expires.isBefore(now)) {
throw new LoginException("Token has expired");
}
/*
* The following check that expiringState is not null can be removed once the expiring state API is made public. Until then,
* it can be enabled by setting the early access flag "login.module.expiring.state". See the documentation for how to set
* the early access flag:
*
* https://kaazing.com/doc/5.0/admin-reference/p_configure_gateway_opts/index.html#enable-early-access-features
*/
if (expiringState != null) {
// Validate that the token hasn't been used already. If not, then store it until it expires in case it is replayed.
long duration = Duration.between(now, expires).toMillis();
String nonce = json.getString("nonce");
if (expiringState.putIfAbsent(nonce, nonce, duration, TimeUnit.MILLISECONDS) != null) {
throw new LoginException(String.format("Token nonce has already been used: %s", nonce));
}
}
// Token has passed validity checks. Store the username to be used by the commit() method.
this.username = json.getString("username");
logger.fine(String.format("Login: Token is valid for user %s", username));
}
|
java
|
private void processToken(String tokenData) throws JSONException, LoginException {
JSONObject json = new JSONObject(tokenData);
// Validate that the token hasn't expired.
ZonedDateTime expires = ZonedDateTime.parse(json.getString("tokenExpires"));
ZonedDateTime now = ZonedDateTime.now(expires.getZone());
if (expires.isBefore(now)) {
throw new LoginException("Token has expired");
}
/*
* The following check that expiringState is not null can be removed once the expiring state API is made public. Until then,
* it can be enabled by setting the early access flag "login.module.expiring.state". See the documentation for how to set
* the early access flag:
*
* https://kaazing.com/doc/5.0/admin-reference/p_configure_gateway_opts/index.html#enable-early-access-features
*/
if (expiringState != null) {
// Validate that the token hasn't been used already. If not, then store it until it expires in case it is replayed.
long duration = Duration.between(now, expires).toMillis();
String nonce = json.getString("nonce");
if (expiringState.putIfAbsent(nonce, nonce, duration, TimeUnit.MILLISECONDS) != null) {
throw new LoginException(String.format("Token nonce has already been used: %s", nonce));
}
}
// Token has passed validity checks. Store the username to be used by the commit() method.
this.username = json.getString("username");
logger.fine(String.format("Login: Token is valid for user %s", username));
}
|
[
"private",
"void",
"processToken",
"(",
"String",
"tokenData",
")",
"throws",
"JSONException",
",",
"LoginException",
"{",
"JSONObject",
"json",
"=",
"new",
"JSONObject",
"(",
"tokenData",
")",
";",
"// Validate that the token hasn't expired.",
"ZonedDateTime",
"expires",
"=",
"ZonedDateTime",
".",
"parse",
"(",
"json",
".",
"getString",
"(",
"\"tokenExpires\"",
")",
")",
";",
"ZonedDateTime",
"now",
"=",
"ZonedDateTime",
".",
"now",
"(",
"expires",
".",
"getZone",
"(",
")",
")",
";",
"if",
"(",
"expires",
".",
"isBefore",
"(",
"now",
")",
")",
"{",
"throw",
"new",
"LoginException",
"(",
"\"Token has expired\"",
")",
";",
"}",
"/*\n * The following check that expiringState is not null can be removed once the expiring state API is made public. Until then,\n * it can be enabled by setting the early access flag \"login.module.expiring.state\". See the documentation for how to set\n * the early access flag:\n *\n * https://kaazing.com/doc/5.0/admin-reference/p_configure_gateway_opts/index.html#enable-early-access-features\n */",
"if",
"(",
"expiringState",
"!=",
"null",
")",
"{",
"// Validate that the token hasn't been used already. If not, then store it until it expires in case it is replayed.",
"long",
"duration",
"=",
"Duration",
".",
"between",
"(",
"now",
",",
"expires",
")",
".",
"toMillis",
"(",
")",
";",
"String",
"nonce",
"=",
"json",
".",
"getString",
"(",
"\"nonce\"",
")",
";",
"if",
"(",
"expiringState",
".",
"putIfAbsent",
"(",
"nonce",
",",
"nonce",
",",
"duration",
",",
"TimeUnit",
".",
"MILLISECONDS",
")",
"!=",
"null",
")",
"{",
"throw",
"new",
"LoginException",
"(",
"String",
".",
"format",
"(",
"\"Token nonce has already been used: %s\"",
",",
"nonce",
")",
")",
";",
"}",
"}",
"// Token has passed validity checks. Store the username to be used by the commit() method.",
"this",
".",
"username",
"=",
"json",
".",
"getString",
"(",
"\"username\"",
")",
";",
"logger",
".",
"fine",
"(",
"String",
".",
"format",
"(",
"\"Login: Token is valid for user %s\"",
",",
"username",
")",
")",
";",
"}"
] |
Validate the token and extract the username to add to shared state. An exception is thrown if the token is found to be
invalid
This method expects the token to be in JSON format:
{
username: "joe",
nonce: "5171483440790326",
tokenExpires: "2017-04-20T15:48:49.187Z"
}
|
[
"Validate",
"the",
"token",
"and",
"extract",
"the",
"username",
"to",
"add",
"to",
"shared",
"state",
".",
"An",
"exception",
"is",
"thrown",
"if",
"the",
"token",
"is",
"found",
"to",
"be",
"invalid"
] |
train
|
https://github.com/kaazing/gateway/blob/06017b19273109b3b992e528e702586446168d57/samples/security/TokenLoginModule.java#L199-L230
|
joniles/mpxj
|
src/main/java/net/sf/mpxj/mpd/MPD9AbstractReader.java
|
MPD9AbstractReader.processCalendarException
|
private void processCalendarException(ProjectCalendar calendar, Row row) {
"""
Process a calendar exception.
@param calendar parent calendar
@param row calendar exception data
"""
Date fromDate = row.getDate("CD_FROM_DATE");
Date toDate = row.getDate("CD_TO_DATE");
boolean working = row.getInt("CD_WORKING") != 0;
ProjectCalendarException exception = calendar.addCalendarException(fromDate, toDate);
if (working)
{
exception.addRange(new DateRange(row.getDate("CD_FROM_TIME1"), row.getDate("CD_TO_TIME1")));
exception.addRange(new DateRange(row.getDate("CD_FROM_TIME2"), row.getDate("CD_TO_TIME2")));
exception.addRange(new DateRange(row.getDate("CD_FROM_TIME3"), row.getDate("CD_TO_TIME3")));
exception.addRange(new DateRange(row.getDate("CD_FROM_TIME4"), row.getDate("CD_TO_TIME4")));
exception.addRange(new DateRange(row.getDate("CD_FROM_TIME5"), row.getDate("CD_TO_TIME5")));
}
}
|
java
|
private void processCalendarException(ProjectCalendar calendar, Row row)
{
Date fromDate = row.getDate("CD_FROM_DATE");
Date toDate = row.getDate("CD_TO_DATE");
boolean working = row.getInt("CD_WORKING") != 0;
ProjectCalendarException exception = calendar.addCalendarException(fromDate, toDate);
if (working)
{
exception.addRange(new DateRange(row.getDate("CD_FROM_TIME1"), row.getDate("CD_TO_TIME1")));
exception.addRange(new DateRange(row.getDate("CD_FROM_TIME2"), row.getDate("CD_TO_TIME2")));
exception.addRange(new DateRange(row.getDate("CD_FROM_TIME3"), row.getDate("CD_TO_TIME3")));
exception.addRange(new DateRange(row.getDate("CD_FROM_TIME4"), row.getDate("CD_TO_TIME4")));
exception.addRange(new DateRange(row.getDate("CD_FROM_TIME5"), row.getDate("CD_TO_TIME5")));
}
}
|
[
"private",
"void",
"processCalendarException",
"(",
"ProjectCalendar",
"calendar",
",",
"Row",
"row",
")",
"{",
"Date",
"fromDate",
"=",
"row",
".",
"getDate",
"(",
"\"CD_FROM_DATE\"",
")",
";",
"Date",
"toDate",
"=",
"row",
".",
"getDate",
"(",
"\"CD_TO_DATE\"",
")",
";",
"boolean",
"working",
"=",
"row",
".",
"getInt",
"(",
"\"CD_WORKING\"",
")",
"!=",
"0",
";",
"ProjectCalendarException",
"exception",
"=",
"calendar",
".",
"addCalendarException",
"(",
"fromDate",
",",
"toDate",
")",
";",
"if",
"(",
"working",
")",
"{",
"exception",
".",
"addRange",
"(",
"new",
"DateRange",
"(",
"row",
".",
"getDate",
"(",
"\"CD_FROM_TIME1\"",
")",
",",
"row",
".",
"getDate",
"(",
"\"CD_TO_TIME1\"",
")",
")",
")",
";",
"exception",
".",
"addRange",
"(",
"new",
"DateRange",
"(",
"row",
".",
"getDate",
"(",
"\"CD_FROM_TIME2\"",
")",
",",
"row",
".",
"getDate",
"(",
"\"CD_TO_TIME2\"",
")",
")",
")",
";",
"exception",
".",
"addRange",
"(",
"new",
"DateRange",
"(",
"row",
".",
"getDate",
"(",
"\"CD_FROM_TIME3\"",
")",
",",
"row",
".",
"getDate",
"(",
"\"CD_TO_TIME3\"",
")",
")",
")",
";",
"exception",
".",
"addRange",
"(",
"new",
"DateRange",
"(",
"row",
".",
"getDate",
"(",
"\"CD_FROM_TIME4\"",
")",
",",
"row",
".",
"getDate",
"(",
"\"CD_TO_TIME4\"",
")",
")",
")",
";",
"exception",
".",
"addRange",
"(",
"new",
"DateRange",
"(",
"row",
".",
"getDate",
"(",
"\"CD_FROM_TIME5\"",
")",
",",
"row",
".",
"getDate",
"(",
"\"CD_TO_TIME5\"",
")",
")",
")",
";",
"}",
"}"
] |
Process a calendar exception.
@param calendar parent calendar
@param row calendar exception data
|
[
"Process",
"a",
"calendar",
"exception",
"."
] |
train
|
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpd/MPD9AbstractReader.java#L291-L305
|
nohana/Amalgam
|
amalgam/src/main/java/com/amalgam/content/SharedPreferencesUtils.java
|
SharedPreferencesUtils.getDouble
|
public static double getDouble(SharedPreferences preferences, String key, double defaultValue) {
"""
Retrieve a double value from the preferences.
@param preferences the preferences
@param key the key
@param defaultValue default value if the key is not present
@return the double value.
"""
String stored = preferences.getString(key, null);
if (TextUtils.isEmpty(stored)) {
return defaultValue;
}
return Double.parseDouble(stored);
}
|
java
|
public static double getDouble(SharedPreferences preferences, String key, double defaultValue) {
String stored = preferences.getString(key, null);
if (TextUtils.isEmpty(stored)) {
return defaultValue;
}
return Double.parseDouble(stored);
}
|
[
"public",
"static",
"double",
"getDouble",
"(",
"SharedPreferences",
"preferences",
",",
"String",
"key",
",",
"double",
"defaultValue",
")",
"{",
"String",
"stored",
"=",
"preferences",
".",
"getString",
"(",
"key",
",",
"null",
")",
";",
"if",
"(",
"TextUtils",
".",
"isEmpty",
"(",
"stored",
")",
")",
"{",
"return",
"defaultValue",
";",
"}",
"return",
"Double",
".",
"parseDouble",
"(",
"stored",
")",
";",
"}"
] |
Retrieve a double value from the preferences.
@param preferences the preferences
@param key the key
@param defaultValue default value if the key is not present
@return the double value.
|
[
"Retrieve",
"a",
"double",
"value",
"from",
"the",
"preferences",
"."
] |
train
|
https://github.com/nohana/Amalgam/blob/57809ddbfe7897e979cf507982ce0b3aa5e0ed8a/amalgam/src/main/java/com/amalgam/content/SharedPreferencesUtils.java#L23-L29
|
mapfish/mapfish-print
|
core/src/main/java/org/mapfish/print/config/ConfigurationFactory.java
|
ConfigurationFactory.getConfig
|
@VisibleForTesting
public final Configuration getConfig(final File configFile) throws IOException {
"""
Create a configuration object from a config file.
@param configFile the file to read the configuration from.
"""
try (FileInputStream in = new FileInputStream(configFile)) {
return getConfig(configFile, in);
}
}
|
java
|
@VisibleForTesting
public final Configuration getConfig(final File configFile) throws IOException {
try (FileInputStream in = new FileInputStream(configFile)) {
return getConfig(configFile, in);
}
}
|
[
"@",
"VisibleForTesting",
"public",
"final",
"Configuration",
"getConfig",
"(",
"final",
"File",
"configFile",
")",
"throws",
"IOException",
"{",
"try",
"(",
"FileInputStream",
"in",
"=",
"new",
"FileInputStream",
"(",
"configFile",
")",
")",
"{",
"return",
"getConfig",
"(",
"configFile",
",",
"in",
")",
";",
"}",
"}"
] |
Create a configuration object from a config file.
@param configFile the file to read the configuration from.
|
[
"Create",
"a",
"configuration",
"object",
"from",
"a",
"config",
"file",
"."
] |
train
|
https://github.com/mapfish/mapfish-print/blob/25a452cb39f592bd8a53b20db1037703898e1e22/core/src/main/java/org/mapfish/print/config/ConfigurationFactory.java#L43-L48
|
jamesagnew/hapi-fhir
|
hapi-fhir-validation/src/main/java/org/hl7/fhir/dstu3/validation/BaseValidator.java
|
BaseValidator.hint
|
protected boolean hint(List<ValidationMessage> errors, IssueType type, int line, int col, String path, boolean thePass, String msg) {
"""
Test a rule and add a {@link IssueSeverity#INFORMATION} validation message if the validation fails
@param thePass
Set this parameter to <code>false</code> if the validation does not pass
@return Returns <code>thePass</code> (in other words, returns <code>true</code> if the rule did not fail validation)
"""
if (!thePass) {
errors.add(new ValidationMessage(source, type, line, col, path, msg, IssueSeverity.INFORMATION));
}
return thePass;
}
|
java
|
protected boolean hint(List<ValidationMessage> errors, IssueType type, int line, int col, String path, boolean thePass, String msg) {
if (!thePass) {
errors.add(new ValidationMessage(source, type, line, col, path, msg, IssueSeverity.INFORMATION));
}
return thePass;
}
|
[
"protected",
"boolean",
"hint",
"(",
"List",
"<",
"ValidationMessage",
">",
"errors",
",",
"IssueType",
"type",
",",
"int",
"line",
",",
"int",
"col",
",",
"String",
"path",
",",
"boolean",
"thePass",
",",
"String",
"msg",
")",
"{",
"if",
"(",
"!",
"thePass",
")",
"{",
"errors",
".",
"add",
"(",
"new",
"ValidationMessage",
"(",
"source",
",",
"type",
",",
"line",
",",
"col",
",",
"path",
",",
"msg",
",",
"IssueSeverity",
".",
"INFORMATION",
")",
")",
";",
"}",
"return",
"thePass",
";",
"}"
] |
Test a rule and add a {@link IssueSeverity#INFORMATION} validation message if the validation fails
@param thePass
Set this parameter to <code>false</code> if the validation does not pass
@return Returns <code>thePass</code> (in other words, returns <code>true</code> if the rule did not fail validation)
|
[
"Test",
"a",
"rule",
"and",
"add",
"a",
"{",
"@link",
"IssueSeverity#INFORMATION",
"}",
"validation",
"message",
"if",
"the",
"validation",
"fails"
] |
train
|
https://github.com/jamesagnew/hapi-fhir/blob/150a84d52fe691b7f48fcb28247c4bddb7aec352/hapi-fhir-validation/src/main/java/org/hl7/fhir/dstu3/validation/BaseValidator.java#L125-L130
|
lessthanoptimal/BoofCV
|
main/boofcv-feature/src/main/java/boofcv/alg/feature/detect/interest/SiftDetector.java
|
SiftDetector.detectFeatures
|
protected void detectFeatures( int scaleIndex ) {
"""
Detect features inside the Difference-of-Gaussian image at the current scale
@param scaleIndex Which scale in the octave is it detecting features inside up.
Primarily provided here for use in child classes.
"""
extractor.process(dogTarget);
FastQueue<NonMaxLimiter.LocalExtreme> found = extractor.getLocalExtreme();
derivXX.setImage(dogTarget);
derivXY.setImage(dogTarget);
derivYY.setImage(dogTarget);
for (int i = 0; i < found.size; i++) {
NonMaxLimiter.LocalExtreme e = found.get(i);
if( e.max ) {
if( isScaleSpaceExtremum(e.location.x, e.location.y, e.getValue(), 1f)) {
processFeatureCandidate(e.location.x,e.location.y,e.getValue(),e.max);
}
} else if( isScaleSpaceExtremum(e.location.x, e.location.y, e.getValue(), -1f)) {
processFeatureCandidate(e.location.x,e.location.y,e.getValue(),e.max);
}
}
}
|
java
|
protected void detectFeatures( int scaleIndex ) {
extractor.process(dogTarget);
FastQueue<NonMaxLimiter.LocalExtreme> found = extractor.getLocalExtreme();
derivXX.setImage(dogTarget);
derivXY.setImage(dogTarget);
derivYY.setImage(dogTarget);
for (int i = 0; i < found.size; i++) {
NonMaxLimiter.LocalExtreme e = found.get(i);
if( e.max ) {
if( isScaleSpaceExtremum(e.location.x, e.location.y, e.getValue(), 1f)) {
processFeatureCandidate(e.location.x,e.location.y,e.getValue(),e.max);
}
} else if( isScaleSpaceExtremum(e.location.x, e.location.y, e.getValue(), -1f)) {
processFeatureCandidate(e.location.x,e.location.y,e.getValue(),e.max);
}
}
}
|
[
"protected",
"void",
"detectFeatures",
"(",
"int",
"scaleIndex",
")",
"{",
"extractor",
".",
"process",
"(",
"dogTarget",
")",
";",
"FastQueue",
"<",
"NonMaxLimiter",
".",
"LocalExtreme",
">",
"found",
"=",
"extractor",
".",
"getLocalExtreme",
"(",
")",
";",
"derivXX",
".",
"setImage",
"(",
"dogTarget",
")",
";",
"derivXY",
".",
"setImage",
"(",
"dogTarget",
")",
";",
"derivYY",
".",
"setImage",
"(",
"dogTarget",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"found",
".",
"size",
";",
"i",
"++",
")",
"{",
"NonMaxLimiter",
".",
"LocalExtreme",
"e",
"=",
"found",
".",
"get",
"(",
"i",
")",
";",
"if",
"(",
"e",
".",
"max",
")",
"{",
"if",
"(",
"isScaleSpaceExtremum",
"(",
"e",
".",
"location",
".",
"x",
",",
"e",
".",
"location",
".",
"y",
",",
"e",
".",
"getValue",
"(",
")",
",",
"1f",
")",
")",
"{",
"processFeatureCandidate",
"(",
"e",
".",
"location",
".",
"x",
",",
"e",
".",
"location",
".",
"y",
",",
"e",
".",
"getValue",
"(",
")",
",",
"e",
".",
"max",
")",
";",
"}",
"}",
"else",
"if",
"(",
"isScaleSpaceExtremum",
"(",
"e",
".",
"location",
".",
"x",
",",
"e",
".",
"location",
".",
"y",
",",
"e",
".",
"getValue",
"(",
")",
",",
"-",
"1f",
")",
")",
"{",
"processFeatureCandidate",
"(",
"e",
".",
"location",
".",
"x",
",",
"e",
".",
"location",
".",
"y",
",",
"e",
".",
"getValue",
"(",
")",
",",
"e",
".",
"max",
")",
";",
"}",
"}",
"}"
] |
Detect features inside the Difference-of-Gaussian image at the current scale
@param scaleIndex Which scale in the octave is it detecting features inside up.
Primarily provided here for use in child classes.
|
[
"Detect",
"features",
"inside",
"the",
"Difference",
"-",
"of",
"-",
"Gaussian",
"image",
"at",
"the",
"current",
"scale"
] |
train
|
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/feature/detect/interest/SiftDetector.java#L199-L218
|
apache/reef
|
lang/java/reef-runtime-hdinsight/src/main/java/org/apache/reef/runtime/hdinsight/cli/LogFetcher.java
|
LogFetcher.downloadToTempFolder
|
private File downloadToTempFolder(final String applicationId)
throws URISyntaxException, StorageException, IOException {
"""
Downloads the logs to a local temp folder.
@param applicationId
@return
@throws URISyntaxException
@throws StorageException
@throws IOException
"""
final File outputFolder = Files.createTempDirectory("reeflogs-" + applicationId).toFile();
if (!outputFolder.exists() && !outputFolder.mkdirs()) {
LOG.log(Level.WARNING, "Failed to create [{0}]", outputFolder.getAbsolutePath());
}
final CloudBlobDirectory logFolder = this.container.getDirectoryReference(LOG_FOLDER_PREFIX + applicationId + "/");
int fileCounter = 0;
for (final ListBlobItem blobItem : logFolder.listBlobs()) {
if (blobItem instanceof CloudBlob) {
try (final OutputStream outputStream = new FileOutputStream(new File(outputFolder, "File-" + fileCounter))) {
((CloudBlob) blobItem).download(outputStream);
++fileCounter;
}
}
}
LOG.log(Level.FINE, "Downloaded logs to: {0}", outputFolder.getAbsolutePath());
return outputFolder;
}
|
java
|
private File downloadToTempFolder(final String applicationId)
throws URISyntaxException, StorageException, IOException {
final File outputFolder = Files.createTempDirectory("reeflogs-" + applicationId).toFile();
if (!outputFolder.exists() && !outputFolder.mkdirs()) {
LOG.log(Level.WARNING, "Failed to create [{0}]", outputFolder.getAbsolutePath());
}
final CloudBlobDirectory logFolder = this.container.getDirectoryReference(LOG_FOLDER_PREFIX + applicationId + "/");
int fileCounter = 0;
for (final ListBlobItem blobItem : logFolder.listBlobs()) {
if (blobItem instanceof CloudBlob) {
try (final OutputStream outputStream = new FileOutputStream(new File(outputFolder, "File-" + fileCounter))) {
((CloudBlob) blobItem).download(outputStream);
++fileCounter;
}
}
}
LOG.log(Level.FINE, "Downloaded logs to: {0}", outputFolder.getAbsolutePath());
return outputFolder;
}
|
[
"private",
"File",
"downloadToTempFolder",
"(",
"final",
"String",
"applicationId",
")",
"throws",
"URISyntaxException",
",",
"StorageException",
",",
"IOException",
"{",
"final",
"File",
"outputFolder",
"=",
"Files",
".",
"createTempDirectory",
"(",
"\"reeflogs-\"",
"+",
"applicationId",
")",
".",
"toFile",
"(",
")",
";",
"if",
"(",
"!",
"outputFolder",
".",
"exists",
"(",
")",
"&&",
"!",
"outputFolder",
".",
"mkdirs",
"(",
")",
")",
"{",
"LOG",
".",
"log",
"(",
"Level",
".",
"WARNING",
",",
"\"Failed to create [{0}]\"",
",",
"outputFolder",
".",
"getAbsolutePath",
"(",
")",
")",
";",
"}",
"final",
"CloudBlobDirectory",
"logFolder",
"=",
"this",
".",
"container",
".",
"getDirectoryReference",
"(",
"LOG_FOLDER_PREFIX",
"+",
"applicationId",
"+",
"\"/\"",
")",
";",
"int",
"fileCounter",
"=",
"0",
";",
"for",
"(",
"final",
"ListBlobItem",
"blobItem",
":",
"logFolder",
".",
"listBlobs",
"(",
")",
")",
"{",
"if",
"(",
"blobItem",
"instanceof",
"CloudBlob",
")",
"{",
"try",
"(",
"final",
"OutputStream",
"outputStream",
"=",
"new",
"FileOutputStream",
"(",
"new",
"File",
"(",
"outputFolder",
",",
"\"File-\"",
"+",
"fileCounter",
")",
")",
")",
"{",
"(",
"(",
"CloudBlob",
")",
"blobItem",
")",
".",
"download",
"(",
"outputStream",
")",
";",
"++",
"fileCounter",
";",
"}",
"}",
"}",
"LOG",
".",
"log",
"(",
"Level",
".",
"FINE",
",",
"\"Downloaded logs to: {0}\"",
",",
"outputFolder",
".",
"getAbsolutePath",
"(",
")",
")",
";",
"return",
"outputFolder",
";",
"}"
] |
Downloads the logs to a local temp folder.
@param applicationId
@return
@throws URISyntaxException
@throws StorageException
@throws IOException
|
[
"Downloads",
"the",
"logs",
"to",
"a",
"local",
"temp",
"folder",
"."
] |
train
|
https://github.com/apache/reef/blob/e2c47121cde21108a602c560cf76565a40d0e916/lang/java/reef-runtime-hdinsight/src/main/java/org/apache/reef/runtime/hdinsight/cli/LogFetcher.java#L118-L136
|
demidenko05/beigesoft-webstore
|
src/main/java/org/beigesoft/webstore/processor/PrcRefreshItemsInList.java
|
PrcRefreshItemsInList.findItemInListFor
|
protected final ItemInList findItemInListFor(final List<ItemInList> pItemsList, final Long pItemId, final EShopItemType pItemType) {
"""
<p>Find ItemInList with given item ID and type.</p>
@param pItemsList items list
@param pItemId Item ID
@param pItemType Item type
@return ItemInList with given item and type if exist or null
"""
int j = 0;
while (j < pItemsList.size()) {
if (pItemsList.get(j).getItsType().equals(pItemType)
&& pItemsList.get(j).getItemId().equals(pItemId)) {
return pItemsList.get(j);
}
j++;
}
return null;
}
|
java
|
protected final ItemInList findItemInListFor(final List<ItemInList> pItemsList, final Long pItemId, final EShopItemType pItemType) {
int j = 0;
while (j < pItemsList.size()) {
if (pItemsList.get(j).getItsType().equals(pItemType)
&& pItemsList.get(j).getItemId().equals(pItemId)) {
return pItemsList.get(j);
}
j++;
}
return null;
}
|
[
"protected",
"final",
"ItemInList",
"findItemInListFor",
"(",
"final",
"List",
"<",
"ItemInList",
">",
"pItemsList",
",",
"final",
"Long",
"pItemId",
",",
"final",
"EShopItemType",
"pItemType",
")",
"{",
"int",
"j",
"=",
"0",
";",
"while",
"(",
"j",
"<",
"pItemsList",
".",
"size",
"(",
")",
")",
"{",
"if",
"(",
"pItemsList",
".",
"get",
"(",
"j",
")",
".",
"getItsType",
"(",
")",
".",
"equals",
"(",
"pItemType",
")",
"&&",
"pItemsList",
".",
"get",
"(",
"j",
")",
".",
"getItemId",
"(",
")",
".",
"equals",
"(",
"pItemId",
")",
")",
"{",
"return",
"pItemsList",
".",
"get",
"(",
"j",
")",
";",
"}",
"j",
"++",
";",
"}",
"return",
"null",
";",
"}"
] |
<p>Find ItemInList with given item ID and type.</p>
@param pItemsList items list
@param pItemId Item ID
@param pItemType Item type
@return ItemInList with given item and type if exist or null
|
[
"<p",
">",
"Find",
"ItemInList",
"with",
"given",
"item",
"ID",
"and",
"type",
".",
"<",
"/",
"p",
">"
] |
train
|
https://github.com/demidenko05/beigesoft-webstore/blob/41ed2e2f1c640d37951d5fb235f26856008b87e1/src/main/java/org/beigesoft/webstore/processor/PrcRefreshItemsInList.java#L1150-L1160
|
xiancloud/xian
|
xian-dao/xian-daocore/src/main/java/info/xiancloud/dao/core/units/DaoUnit.java
|
DaoUnit.logSql
|
public static void logSql(Class daoUnitClass, Map<String, Object> map) {
"""
打印sql语句,它不会将sql执行,只是打印sql语句。
仅供内部测试使用
@param daoUnitClass unit class
@param map parameter map
"""
XianConnection connection = PoolFactory.getPool().getMasterDatasource().getConnection().blockingGet();
DaoUnit daoUnit;
try {
daoUnit = (DaoUnit) daoUnitClass.newInstance();
for (SqlAction action : daoUnit.getActions()) {
((AbstractSqlAction) action).setConnection(connection);
((AbstractSqlAction) action).setMap(map);
action.logSql(map);
}
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
PoolFactory.getPool().destroyPoolIfNot();
}
|
java
|
public static void logSql(Class daoUnitClass, Map<String, Object> map) {
XianConnection connection = PoolFactory.getPool().getMasterDatasource().getConnection().blockingGet();
DaoUnit daoUnit;
try {
daoUnit = (DaoUnit) daoUnitClass.newInstance();
for (SqlAction action : daoUnit.getActions()) {
((AbstractSqlAction) action).setConnection(connection);
((AbstractSqlAction) action).setMap(map);
action.logSql(map);
}
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
PoolFactory.getPool().destroyPoolIfNot();
}
|
[
"public",
"static",
"void",
"logSql",
"(",
"Class",
"daoUnitClass",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"map",
")",
"{",
"XianConnection",
"connection",
"=",
"PoolFactory",
".",
"getPool",
"(",
")",
".",
"getMasterDatasource",
"(",
")",
".",
"getConnection",
"(",
")",
".",
"blockingGet",
"(",
")",
";",
"DaoUnit",
"daoUnit",
";",
"try",
"{",
"daoUnit",
"=",
"(",
"DaoUnit",
")",
"daoUnitClass",
".",
"newInstance",
"(",
")",
";",
"for",
"(",
"SqlAction",
"action",
":",
"daoUnit",
".",
"getActions",
"(",
")",
")",
"{",
"(",
"(",
"AbstractSqlAction",
")",
"action",
")",
".",
"setConnection",
"(",
"connection",
")",
";",
"(",
"(",
"AbstractSqlAction",
")",
"action",
")",
".",
"setMap",
"(",
"map",
")",
";",
"action",
".",
"logSql",
"(",
"map",
")",
";",
"}",
"}",
"catch",
"(",
"InstantiationException",
"|",
"IllegalAccessException",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"}",
"PoolFactory",
".",
"getPool",
"(",
")",
".",
"destroyPoolIfNot",
"(",
")",
";",
"}"
] |
打印sql语句,它不会将sql执行,只是打印sql语句。
仅供内部测试使用
@param daoUnitClass unit class
@param map parameter map
|
[
"打印sql语句,它不会将sql执行,只是打印sql语句。",
"仅供内部测试使用"
] |
train
|
https://github.com/xiancloud/xian/blob/1948e088545553d2745b2c86d8b5a64988bb850e/xian-dao/xian-daocore/src/main/java/info/xiancloud/dao/core/units/DaoUnit.java#L164-L178
|
zaproxy/zaproxy
|
src/org/zaproxy/zap/utils/I18N.java
|
I18N.getString
|
public String getString(String key, Object... params ) {
"""
Gets the message with the given key, formatted with the given parameters.
<p>
The message will be obtained either from the core {@link ResourceBundle} or a {@code ResourceBundle} of an add-on
(depending on the prefix of the key) and then {@link MessageFormat#format(String, Object...) formatted}.
<p>
<strong>Note:</strong> This method does not throw a {@code MissingResourceException} if the key does not exist, instead
it logs an error and returns the key itself. This avoids breaking ZAP when a resource message is accidentally missing.
Use {@link #containsKey(String)} instead to know if a message exists or not.
@param key the key.
@param params the parameters to format the message.
@return the message formatted.
@see #getString(String)
"""
try {
return MessageFormat.format(this.getStringImpl(key), params);
} catch (MissingResourceException e) {
return handleMissingResourceException(e);
}
}
|
java
|
public String getString(String key, Object... params ) {
try {
return MessageFormat.format(this.getStringImpl(key), params);
} catch (MissingResourceException e) {
return handleMissingResourceException(e);
}
}
|
[
"public",
"String",
"getString",
"(",
"String",
"key",
",",
"Object",
"...",
"params",
")",
"{",
"try",
"{",
"return",
"MessageFormat",
".",
"format",
"(",
"this",
".",
"getStringImpl",
"(",
"key",
")",
",",
"params",
")",
";",
"}",
"catch",
"(",
"MissingResourceException",
"e",
")",
"{",
"return",
"handleMissingResourceException",
"(",
"e",
")",
";",
"}",
"}"
] |
Gets the message with the given key, formatted with the given parameters.
<p>
The message will be obtained either from the core {@link ResourceBundle} or a {@code ResourceBundle} of an add-on
(depending on the prefix of the key) and then {@link MessageFormat#format(String, Object...) formatted}.
<p>
<strong>Note:</strong> This method does not throw a {@code MissingResourceException} if the key does not exist, instead
it logs an error and returns the key itself. This avoids breaking ZAP when a resource message is accidentally missing.
Use {@link #containsKey(String)} instead to know if a message exists or not.
@param key the key.
@param params the parameters to format the message.
@return the message formatted.
@see #getString(String)
|
[
"Gets",
"the",
"message",
"with",
"the",
"given",
"key",
"formatted",
"with",
"the",
"given",
"parameters",
".",
"<p",
">",
"The",
"message",
"will",
"be",
"obtained",
"either",
"from",
"the",
"core",
"{",
"@link",
"ResourceBundle",
"}",
"or",
"a",
"{",
"@code",
"ResourceBundle",
"}",
"of",
"an",
"add",
"-",
"on",
"(",
"depending",
"on",
"the",
"prefix",
"of",
"the",
"key",
")",
"and",
"then",
"{",
"@link",
"MessageFormat#format",
"(",
"String",
"Object",
"...",
")",
"formatted",
"}",
".",
"<p",
">",
"<strong",
">",
"Note",
":",
"<",
"/",
"strong",
">",
"This",
"method",
"does",
"not",
"throw",
"a",
"{",
"@code",
"MissingResourceException",
"}",
"if",
"the",
"key",
"does",
"not",
"exist",
"instead",
"it",
"logs",
"an",
"error",
"and",
"returns",
"the",
"key",
"itself",
".",
"This",
"avoids",
"breaking",
"ZAP",
"when",
"a",
"resource",
"message",
"is",
"accidentally",
"missing",
".",
"Use",
"{",
"@link",
"#containsKey",
"(",
"String",
")",
"}",
"instead",
"to",
"know",
"if",
"a",
"message",
"exists",
"or",
"not",
"."
] |
train
|
https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/utils/I18N.java#L261-L267
|
sdl/odata
|
odata_renderer/src/main/java/com/sdl/odata/renderer/metadata/MetadataDocumentWriter.java
|
MetadataDocumentWriter.writeMetadataDocument
|
public void writeMetadataDocument() throws ODataRenderException {
"""
Write the 'Metadata Document'.
@throws ODataRenderException if unable to render metadata document
"""
try {
xmlWriter.writeStartElement(EDMX_NS, EDMX);
xmlWriter.writeNamespace(EDMX_PREFIX, EDMX_NS);
xmlWriter.writeAttribute(VERSION, ODATA_VERSION);
xmlWriter.writeStartElement(EDMX_NS, EDMX_DATA_SERVICES);
boolean entityContinerWritten = false;
// Loop over all the schemas present in the Entity Data Model
for (Schema schema : entityDataModel.getSchemas()) {
xmlWriter.writeStartElement(SCHEMA);
xmlWriter.writeDefaultNamespace(EDM_NS);
xmlWriter.writeAttribute(NAMESPACE, schema.getNamespace());
for (Type type : schema.getTypes()) {
switch (type.getMetaType()) {
case ENTITY:
entityTypeWriter.write((EntityType) type);
break;
case COMPLEX:
complexTypeWriter.write((ComplexType) type);
break;
case ENUM:
enumTypeWriter.write((EnumType) type);
break;
default:
LOG.error("Unexpected type: {}", type.getFullyQualifiedName());
throw new ODataRenderException("Unexpected type: " + type.getFullyQualifiedName());
}
}
if (!entityContinerWritten) {
writeEntityContainer(entityDataModel.getEntityContainer());
entityContinerWritten = true;
}
// End of <Schema> element
xmlWriter.writeEndElement();
}
xmlWriter.writeEndElement();
} catch (XMLStreamException e) {
LOG.error("Not possible to start stream XML");
throw new ODataRenderException("Not possible to start stream XML: ", e);
}
}
|
java
|
public void writeMetadataDocument() throws ODataRenderException {
try {
xmlWriter.writeStartElement(EDMX_NS, EDMX);
xmlWriter.writeNamespace(EDMX_PREFIX, EDMX_NS);
xmlWriter.writeAttribute(VERSION, ODATA_VERSION);
xmlWriter.writeStartElement(EDMX_NS, EDMX_DATA_SERVICES);
boolean entityContinerWritten = false;
// Loop over all the schemas present in the Entity Data Model
for (Schema schema : entityDataModel.getSchemas()) {
xmlWriter.writeStartElement(SCHEMA);
xmlWriter.writeDefaultNamespace(EDM_NS);
xmlWriter.writeAttribute(NAMESPACE, schema.getNamespace());
for (Type type : schema.getTypes()) {
switch (type.getMetaType()) {
case ENTITY:
entityTypeWriter.write((EntityType) type);
break;
case COMPLEX:
complexTypeWriter.write((ComplexType) type);
break;
case ENUM:
enumTypeWriter.write((EnumType) type);
break;
default:
LOG.error("Unexpected type: {}", type.getFullyQualifiedName());
throw new ODataRenderException("Unexpected type: " + type.getFullyQualifiedName());
}
}
if (!entityContinerWritten) {
writeEntityContainer(entityDataModel.getEntityContainer());
entityContinerWritten = true;
}
// End of <Schema> element
xmlWriter.writeEndElement();
}
xmlWriter.writeEndElement();
} catch (XMLStreamException e) {
LOG.error("Not possible to start stream XML");
throw new ODataRenderException("Not possible to start stream XML: ", e);
}
}
|
[
"public",
"void",
"writeMetadataDocument",
"(",
")",
"throws",
"ODataRenderException",
"{",
"try",
"{",
"xmlWriter",
".",
"writeStartElement",
"(",
"EDMX_NS",
",",
"EDMX",
")",
";",
"xmlWriter",
".",
"writeNamespace",
"(",
"EDMX_PREFIX",
",",
"EDMX_NS",
")",
";",
"xmlWriter",
".",
"writeAttribute",
"(",
"VERSION",
",",
"ODATA_VERSION",
")",
";",
"xmlWriter",
".",
"writeStartElement",
"(",
"EDMX_NS",
",",
"EDMX_DATA_SERVICES",
")",
";",
"boolean",
"entityContinerWritten",
"=",
"false",
";",
"// Loop over all the schemas present in the Entity Data Model",
"for",
"(",
"Schema",
"schema",
":",
"entityDataModel",
".",
"getSchemas",
"(",
")",
")",
"{",
"xmlWriter",
".",
"writeStartElement",
"(",
"SCHEMA",
")",
";",
"xmlWriter",
".",
"writeDefaultNamespace",
"(",
"EDM_NS",
")",
";",
"xmlWriter",
".",
"writeAttribute",
"(",
"NAMESPACE",
",",
"schema",
".",
"getNamespace",
"(",
")",
")",
";",
"for",
"(",
"Type",
"type",
":",
"schema",
".",
"getTypes",
"(",
")",
")",
"{",
"switch",
"(",
"type",
".",
"getMetaType",
"(",
")",
")",
"{",
"case",
"ENTITY",
":",
"entityTypeWriter",
".",
"write",
"(",
"(",
"EntityType",
")",
"type",
")",
";",
"break",
";",
"case",
"COMPLEX",
":",
"complexTypeWriter",
".",
"write",
"(",
"(",
"ComplexType",
")",
"type",
")",
";",
"break",
";",
"case",
"ENUM",
":",
"enumTypeWriter",
".",
"write",
"(",
"(",
"EnumType",
")",
"type",
")",
";",
"break",
";",
"default",
":",
"LOG",
".",
"error",
"(",
"\"Unexpected type: {}\"",
",",
"type",
".",
"getFullyQualifiedName",
"(",
")",
")",
";",
"throw",
"new",
"ODataRenderException",
"(",
"\"Unexpected type: \"",
"+",
"type",
".",
"getFullyQualifiedName",
"(",
")",
")",
";",
"}",
"}",
"if",
"(",
"!",
"entityContinerWritten",
")",
"{",
"writeEntityContainer",
"(",
"entityDataModel",
".",
"getEntityContainer",
"(",
")",
")",
";",
"entityContinerWritten",
"=",
"true",
";",
"}",
"// End of <Schema> element",
"xmlWriter",
".",
"writeEndElement",
"(",
")",
";",
"}",
"xmlWriter",
".",
"writeEndElement",
"(",
")",
";",
"}",
"catch",
"(",
"XMLStreamException",
"e",
")",
"{",
"LOG",
".",
"error",
"(",
"\"Not possible to start stream XML\"",
")",
";",
"throw",
"new",
"ODataRenderException",
"(",
"\"Not possible to start stream XML: \"",
",",
"e",
")",
";",
"}",
"}"
] |
Write the 'Metadata Document'.
@throws ODataRenderException if unable to render metadata document
|
[
"Write",
"the",
"Metadata",
"Document",
"."
] |
train
|
https://github.com/sdl/odata/blob/eb747d73e9af0f4e59a25b82ed656e526a7e2189/odata_renderer/src/main/java/com/sdl/odata/renderer/metadata/MetadataDocumentWriter.java#L122-L166
|
actframework/actframework
|
src/main/java/act/util/LogSupport.java
|
LogSupport.printCenter
|
protected void printCenter(String format, Object... args) {
"""
Print formatted string in the center of 80 chars line, left and right padded.
@param format
The string format pattern
@param args
The string format arguments
"""
String text = S.fmt(format, args);
info(S.center(text, 80));
}
|
java
|
protected void printCenter(String format, Object... args) {
String text = S.fmt(format, args);
info(S.center(text, 80));
}
|
[
"protected",
"void",
"printCenter",
"(",
"String",
"format",
",",
"Object",
"...",
"args",
")",
"{",
"String",
"text",
"=",
"S",
".",
"fmt",
"(",
"format",
",",
"args",
")",
";",
"info",
"(",
"S",
".",
"center",
"(",
"text",
",",
"80",
")",
")",
";",
"}"
] |
Print formatted string in the center of 80 chars line, left and right padded.
@param format
The string format pattern
@param args
The string format arguments
|
[
"Print",
"formatted",
"string",
"in",
"the",
"center",
"of",
"80",
"chars",
"line",
"left",
"and",
"right",
"padded",
"."
] |
train
|
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/util/LogSupport.java#L95-L98
|
OpenNTF/JavascriptAggregator
|
jaggr-core/src/main/java/com/ibm/jaggr/core/deps/ModuleDeps.java
|
ModuleDeps.containsDep
|
public boolean containsDep(String moduleName, BooleanTerm term) {
"""
Returns true if the map contains the module name with the specified term.
See {@link ModuleDepInfo#containsTerm(BooleanTerm)} for a description of
containment.
@param moduleName
The module name
@param term
the boolean term
@return True if the map contains the module name with the specified term.
"""
boolean result = false;
ModuleDepInfo existing = get(moduleName);
if (existing != null) {
result = existing.containsTerm(term);
}
return result;
}
|
java
|
public boolean containsDep(String moduleName, BooleanTerm term) {
boolean result = false;
ModuleDepInfo existing = get(moduleName);
if (existing != null) {
result = existing.containsTerm(term);
}
return result;
}
|
[
"public",
"boolean",
"containsDep",
"(",
"String",
"moduleName",
",",
"BooleanTerm",
"term",
")",
"{",
"boolean",
"result",
"=",
"false",
";",
"ModuleDepInfo",
"existing",
"=",
"get",
"(",
"moduleName",
")",
";",
"if",
"(",
"existing",
"!=",
"null",
")",
"{",
"result",
"=",
"existing",
".",
"containsTerm",
"(",
"term",
")",
";",
"}",
"return",
"result",
";",
"}"
] |
Returns true if the map contains the module name with the specified term.
See {@link ModuleDepInfo#containsTerm(BooleanTerm)} for a description of
containment.
@param moduleName
The module name
@param term
the boolean term
@return True if the map contains the module name with the specified term.
|
[
"Returns",
"true",
"if",
"the",
"map",
"contains",
"the",
"module",
"name",
"with",
"the",
"specified",
"term",
".",
"See",
"{",
"@link",
"ModuleDepInfo#containsTerm",
"(",
"BooleanTerm",
")",
"}",
"for",
"a",
"description",
"of",
"containment",
"."
] |
train
|
https://github.com/OpenNTF/JavascriptAggregator/blob/9f47a96d778251638b1df9a368462176216d5b29/jaggr-core/src/main/java/com/ibm/jaggr/core/deps/ModuleDeps.java#L109-L116
|
finmath/finmath-lib
|
src/main/java/net/finmath/marketdata2/model/curves/DiscountCurveInterpolation.java
|
DiscountCurveInterpolation.createDiscountCurveFromDiscountFactors
|
public static DiscountCurveInterpolation createDiscountCurveFromDiscountFactors(
String name,
double[] times,
RandomVariable[] givenDiscountFactors,
InterpolationMethod interpolationMethod, ExtrapolationMethod extrapolationMethod, InterpolationEntity interpolationEntity) {
"""
Create a discount curve from given times and given discount factors using given interpolation and extrapolation methods.
@param name The name of this discount curve.
@param times Array of times as doubles.
@param givenDiscountFactors Array of corresponding discount factors.
@param interpolationMethod The interpolation method used for the curve.
@param extrapolationMethod The extrapolation method used for the curve.
@param interpolationEntity The entity interpolated/extrapolated.
@return A new discount factor object.
"""
boolean[] isParameter = new boolean[times.length];
for(int timeIndex=0; timeIndex<times.length;timeIndex++) {
isParameter[timeIndex] = times[timeIndex] > 0;
}
return createDiscountCurveFromDiscountFactors(name, times, givenDiscountFactors, isParameter, interpolationMethod, extrapolationMethod, interpolationEntity);
}
|
java
|
public static DiscountCurveInterpolation createDiscountCurveFromDiscountFactors(
String name,
double[] times,
RandomVariable[] givenDiscountFactors,
InterpolationMethod interpolationMethod, ExtrapolationMethod extrapolationMethod, InterpolationEntity interpolationEntity) {
boolean[] isParameter = new boolean[times.length];
for(int timeIndex=0; timeIndex<times.length;timeIndex++) {
isParameter[timeIndex] = times[timeIndex] > 0;
}
return createDiscountCurveFromDiscountFactors(name, times, givenDiscountFactors, isParameter, interpolationMethod, extrapolationMethod, interpolationEntity);
}
|
[
"public",
"static",
"DiscountCurveInterpolation",
"createDiscountCurveFromDiscountFactors",
"(",
"String",
"name",
",",
"double",
"[",
"]",
"times",
",",
"RandomVariable",
"[",
"]",
"givenDiscountFactors",
",",
"InterpolationMethod",
"interpolationMethod",
",",
"ExtrapolationMethod",
"extrapolationMethod",
",",
"InterpolationEntity",
"interpolationEntity",
")",
"{",
"boolean",
"[",
"]",
"isParameter",
"=",
"new",
"boolean",
"[",
"times",
".",
"length",
"]",
";",
"for",
"(",
"int",
"timeIndex",
"=",
"0",
";",
"timeIndex",
"<",
"times",
".",
"length",
";",
"timeIndex",
"++",
")",
"{",
"isParameter",
"[",
"timeIndex",
"]",
"=",
"times",
"[",
"timeIndex",
"]",
">",
"0",
";",
"}",
"return",
"createDiscountCurveFromDiscountFactors",
"(",
"name",
",",
"times",
",",
"givenDiscountFactors",
",",
"isParameter",
",",
"interpolationMethod",
",",
"extrapolationMethod",
",",
"interpolationEntity",
")",
";",
"}"
] |
Create a discount curve from given times and given discount factors using given interpolation and extrapolation methods.
@param name The name of this discount curve.
@param times Array of times as doubles.
@param givenDiscountFactors Array of corresponding discount factors.
@param interpolationMethod The interpolation method used for the curve.
@param extrapolationMethod The extrapolation method used for the curve.
@param interpolationEntity The entity interpolated/extrapolated.
@return A new discount factor object.
|
[
"Create",
"a",
"discount",
"curve",
"from",
"given",
"times",
"and",
"given",
"discount",
"factors",
"using",
"given",
"interpolation",
"and",
"extrapolation",
"methods",
"."
] |
train
|
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/marketdata2/model/curves/DiscountCurveInterpolation.java#L145-L156
|
landawn/AbacusUtil
|
src/com/landawn/abacus/util/SQLExecutor.java
|
SQLExecutor.queryForUniqueResult
|
@SuppressWarnings("unchecked")
@SafeVarargs
public final <V> Nullable<V> queryForUniqueResult(final Class<V> targetClass, final Connection conn, final String sql,
final StatementSetter statementSetter, final JdbcSettings jdbcSettings, final Object... parameters) throws DuplicatedResultException {
"""
Returns a {@code Nullable} describing the value in the first row/column if it exists, otherwise return an empty {@code Nullable}.
And throws {@code DuplicatedResultException} if more than one record found.
<br />
Special note for type conversion for {@code boolean} or {@code Boolean} type: {@code true} is returned if the
{@code String} value of the target column is {@code "true"}, case insensitive. or it's an integer with value > 0.
Otherwise, {@code false} is returned.
Remember to add {@code limit} condition if big result will be returned by the query.
@param targetClass
set result type to avoid the NullPointerException if result is null and T is primitive type
"int, long. short ... char, boolean..".
@param conn
@param sql
@param statementSetter
@param jdbcSettings
@param parameters
@throws DuplicatedResultException if more than one record found.
"""
return query(conn, sql, statementSetter, createUniqueResultExtractor(targetClass), jdbcSettings, parameters);
}
|
java
|
@SuppressWarnings("unchecked")
@SafeVarargs
public final <V> Nullable<V> queryForUniqueResult(final Class<V> targetClass, final Connection conn, final String sql,
final StatementSetter statementSetter, final JdbcSettings jdbcSettings, final Object... parameters) throws DuplicatedResultException {
return query(conn, sql, statementSetter, createUniqueResultExtractor(targetClass), jdbcSettings, parameters);
}
|
[
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"@",
"SafeVarargs",
"public",
"final",
"<",
"V",
">",
"Nullable",
"<",
"V",
">",
"queryForUniqueResult",
"(",
"final",
"Class",
"<",
"V",
">",
"targetClass",
",",
"final",
"Connection",
"conn",
",",
"final",
"String",
"sql",
",",
"final",
"StatementSetter",
"statementSetter",
",",
"final",
"JdbcSettings",
"jdbcSettings",
",",
"final",
"Object",
"...",
"parameters",
")",
"throws",
"DuplicatedResultException",
"{",
"return",
"query",
"(",
"conn",
",",
"sql",
",",
"statementSetter",
",",
"createUniqueResultExtractor",
"(",
"targetClass",
")",
",",
"jdbcSettings",
",",
"parameters",
")",
";",
"}"
] |
Returns a {@code Nullable} describing the value in the first row/column if it exists, otherwise return an empty {@code Nullable}.
And throws {@code DuplicatedResultException} if more than one record found.
<br />
Special note for type conversion for {@code boolean} or {@code Boolean} type: {@code true} is returned if the
{@code String} value of the target column is {@code "true"}, case insensitive. or it's an integer with value > 0.
Otherwise, {@code false} is returned.
Remember to add {@code limit} condition if big result will be returned by the query.
@param targetClass
set result type to avoid the NullPointerException if result is null and T is primitive type
"int, long. short ... char, boolean..".
@param conn
@param sql
@param statementSetter
@param jdbcSettings
@param parameters
@throws DuplicatedResultException if more than one record found.
|
[
"Returns",
"a",
"{",
"@code",
"Nullable",
"}",
"describing",
"the",
"value",
"in",
"the",
"first",
"row",
"/",
"column",
"if",
"it",
"exists",
"otherwise",
"return",
"an",
"empty",
"{",
"@code",
"Nullable",
"}",
".",
"And",
"throws",
"{",
"@code",
"DuplicatedResultException",
"}",
"if",
"more",
"than",
"one",
"record",
"found",
".",
"<br",
"/",
">"
] |
train
|
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/SQLExecutor.java#L2378-L2383
|
google/j2objc
|
jre_emul/android/platform/libcore/ojluni/src/main/java/java/time/temporal/ValueRange.java
|
ValueRange.of
|
public static ValueRange of(long minSmallest, long minLargest, long maxSmallest, long maxLargest) {
"""
Obtains a fully variable value range.
<p>
This factory obtains a range where both the minimum and maximum value may vary.
@param minSmallest the smallest minimum value
@param minLargest the largest minimum value
@param maxSmallest the smallest maximum value
@param maxLargest the largest maximum value
@return the ValueRange for smallest min, largest min, smallest max, largest max, not null
@throws IllegalArgumentException if
the smallest minimum is greater than the smallest maximum,
or the smallest maximum is greater than the largest maximum
or the largest minimum is greater than the largest maximum
"""
if (minSmallest > minLargest) {
throw new IllegalArgumentException("Smallest minimum value must be less than largest minimum value");
}
if (maxSmallest > maxLargest) {
throw new IllegalArgumentException("Smallest maximum value must be less than largest maximum value");
}
if (minLargest > maxLargest) {
throw new IllegalArgumentException("Minimum value must be less than maximum value");
}
return new ValueRange(minSmallest, minLargest, maxSmallest, maxLargest);
}
|
java
|
public static ValueRange of(long minSmallest, long minLargest, long maxSmallest, long maxLargest) {
if (minSmallest > minLargest) {
throw new IllegalArgumentException("Smallest minimum value must be less than largest minimum value");
}
if (maxSmallest > maxLargest) {
throw new IllegalArgumentException("Smallest maximum value must be less than largest maximum value");
}
if (minLargest > maxLargest) {
throw new IllegalArgumentException("Minimum value must be less than maximum value");
}
return new ValueRange(minSmallest, minLargest, maxSmallest, maxLargest);
}
|
[
"public",
"static",
"ValueRange",
"of",
"(",
"long",
"minSmallest",
",",
"long",
"minLargest",
",",
"long",
"maxSmallest",
",",
"long",
"maxLargest",
")",
"{",
"if",
"(",
"minSmallest",
">",
"minLargest",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Smallest minimum value must be less than largest minimum value\"",
")",
";",
"}",
"if",
"(",
"maxSmallest",
">",
"maxLargest",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Smallest maximum value must be less than largest maximum value\"",
")",
";",
"}",
"if",
"(",
"minLargest",
">",
"maxLargest",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Minimum value must be less than maximum value\"",
")",
";",
"}",
"return",
"new",
"ValueRange",
"(",
"minSmallest",
",",
"minLargest",
",",
"maxSmallest",
",",
"maxLargest",
")",
";",
"}"
] |
Obtains a fully variable value range.
<p>
This factory obtains a range where both the minimum and maximum value may vary.
@param minSmallest the smallest minimum value
@param minLargest the largest minimum value
@param maxSmallest the smallest maximum value
@param maxLargest the largest maximum value
@return the ValueRange for smallest min, largest min, smallest max, largest max, not null
@throws IllegalArgumentException if
the smallest minimum is greater than the smallest maximum,
or the smallest maximum is greater than the largest maximum
or the largest minimum is greater than the largest maximum
|
[
"Obtains",
"a",
"fully",
"variable",
"value",
"range",
".",
"<p",
">",
"This",
"factory",
"obtains",
"a",
"range",
"where",
"both",
"the",
"minimum",
"and",
"maximum",
"value",
"may",
"vary",
"."
] |
train
|
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/time/temporal/ValueRange.java#L165-L176
|
alkacon/opencms-core
|
src-gwt/org/opencms/ade/galleries/client/ui/CmsGalleryDialog.java
|
CmsGalleryDialog.selectTab
|
public void selectTab(GalleryTabId tabId, boolean fireEvent) {
"""
Selects a tab by the given id.<p>
@param tabId the tab id
@param fireEvent <code>true</code> to fire the tab event
"""
A_CmsTab tab = getTab(tabId);
if (tab != null) {
m_tabbedPanel.selectTab(tab, fireEvent);
}
}
|
java
|
public void selectTab(GalleryTabId tabId, boolean fireEvent) {
A_CmsTab tab = getTab(tabId);
if (tab != null) {
m_tabbedPanel.selectTab(tab, fireEvent);
}
}
|
[
"public",
"void",
"selectTab",
"(",
"GalleryTabId",
"tabId",
",",
"boolean",
"fireEvent",
")",
"{",
"A_CmsTab",
"tab",
"=",
"getTab",
"(",
"tabId",
")",
";",
"if",
"(",
"tab",
"!=",
"null",
")",
"{",
"m_tabbedPanel",
".",
"selectTab",
"(",
"tab",
",",
"fireEvent",
")",
";",
"}",
"}"
] |
Selects a tab by the given id.<p>
@param tabId the tab id
@param fireEvent <code>true</code> to fire the tab event
|
[
"Selects",
"a",
"tab",
"by",
"the",
"given",
"id",
".",
"<p",
">"
] |
train
|
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/galleries/client/ui/CmsGalleryDialog.java#L587-L593
|
JOML-CI/JOML
|
src/org/joml/Quaternionf.java
|
Quaternionf.rotationTo
|
public Quaternionf rotationTo(Vector3fc fromDir, Vector3fc toDir) {
"""
Set <code>this</code> quaternion to a rotation that rotates the <code>fromDir</code> vector to point along <code>toDir</code>.
<p>
Because there can be multiple possible rotations, this method chooses the one with the shortest arc.
@see #rotationTo(float, float, float, float, float, float)
@param fromDir
the starting direction
@param toDir
the destination direction
@return this
"""
return rotationTo(fromDir.x(), fromDir.y(), fromDir.z(), toDir.x(), toDir.y(), toDir.z());
}
|
java
|
public Quaternionf rotationTo(Vector3fc fromDir, Vector3fc toDir) {
return rotationTo(fromDir.x(), fromDir.y(), fromDir.z(), toDir.x(), toDir.y(), toDir.z());
}
|
[
"public",
"Quaternionf",
"rotationTo",
"(",
"Vector3fc",
"fromDir",
",",
"Vector3fc",
"toDir",
")",
"{",
"return",
"rotationTo",
"(",
"fromDir",
".",
"x",
"(",
")",
",",
"fromDir",
".",
"y",
"(",
")",
",",
"fromDir",
".",
"z",
"(",
")",
",",
"toDir",
".",
"x",
"(",
")",
",",
"toDir",
".",
"y",
"(",
")",
",",
"toDir",
".",
"z",
"(",
")",
")",
";",
"}"
] |
Set <code>this</code> quaternion to a rotation that rotates the <code>fromDir</code> vector to point along <code>toDir</code>.
<p>
Because there can be multiple possible rotations, this method chooses the one with the shortest arc.
@see #rotationTo(float, float, float, float, float, float)
@param fromDir
the starting direction
@param toDir
the destination direction
@return this
|
[
"Set",
"<code",
">",
"this<",
"/",
"code",
">",
"quaternion",
"to",
"a",
"rotation",
"that",
"rotates",
"the",
"<code",
">",
"fromDir<",
"/",
"code",
">",
"vector",
"to",
"point",
"along",
"<code",
">",
"toDir<",
"/",
"code",
">",
".",
"<p",
">",
"Because",
"there",
"can",
"be",
"multiple",
"possible",
"rotations",
"this",
"method",
"chooses",
"the",
"one",
"with",
"the",
"shortest",
"arc",
"."
] |
train
|
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Quaternionf.java#L2261-L2263
|
Waikato/moa
|
moa/src/main/java/com/yahoo/labs/samoa/instances/InstanceImpl.java
|
InstanceImpl.addSparseValues
|
@Override
public void addSparseValues(int[] indexValues, double[] attributeValues, int numberAttributes) {
"""
Adds the sparse values.
@param indexValues the index values
@param attributeValues the attribute values
@param numberAttributes the number attributes
"""
this.instanceData = new SparseInstanceData(attributeValues, indexValues, numberAttributes); //???
}
|
java
|
@Override
public void addSparseValues(int[] indexValues, double[] attributeValues, int numberAttributes) {
this.instanceData = new SparseInstanceData(attributeValues, indexValues, numberAttributes); //???
}
|
[
"@",
"Override",
"public",
"void",
"addSparseValues",
"(",
"int",
"[",
"]",
"indexValues",
",",
"double",
"[",
"]",
"attributeValues",
",",
"int",
"numberAttributes",
")",
"{",
"this",
".",
"instanceData",
"=",
"new",
"SparseInstanceData",
"(",
"attributeValues",
",",
"indexValues",
",",
"numberAttributes",
")",
";",
"//???",
"}"
] |
Adds the sparse values.
@param indexValues the index values
@param attributeValues the attribute values
@param numberAttributes the number attributes
|
[
"Adds",
"the",
"sparse",
"values",
"."
] |
train
|
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/com/yahoo/labs/samoa/instances/InstanceImpl.java#L381-L384
|
alkacon/opencms-core
|
src/org/opencms/workplace/CmsDialog.java
|
CmsDialog.dialogBlock
|
public String dialogBlock(int segment, String headline, boolean error) {
"""
Builds a block with 3D border and optional subheadline in the dialog content area.<p>
@param segment the HTML segment (START / END)
@param headline the headline String for the block
@param error if true, an error block will be created
@return 3D block start / end segment
"""
if (segment == HTML_START) {
StringBuffer result = new StringBuffer(512);
String errorStyle = "";
if (error) {
errorStyle = " dialogerror";
}
result.append("<!-- 3D block start -->\n");
result.append("<fieldset class=\"dialogblock\">\n");
if (CmsStringUtil.isNotEmpty(headline)) {
result.append("<legend>");
result.append("<span class=\"textbold");
result.append(errorStyle);
result.append("\" unselectable=\"on\">");
result.append(headline);
result.append("</span></legend>\n");
}
return result.toString();
} else {
return "</fieldset>\n<!-- 3D block end -->\n";
}
}
|
java
|
public String dialogBlock(int segment, String headline, boolean error) {
if (segment == HTML_START) {
StringBuffer result = new StringBuffer(512);
String errorStyle = "";
if (error) {
errorStyle = " dialogerror";
}
result.append("<!-- 3D block start -->\n");
result.append("<fieldset class=\"dialogblock\">\n");
if (CmsStringUtil.isNotEmpty(headline)) {
result.append("<legend>");
result.append("<span class=\"textbold");
result.append(errorStyle);
result.append("\" unselectable=\"on\">");
result.append(headline);
result.append("</span></legend>\n");
}
return result.toString();
} else {
return "</fieldset>\n<!-- 3D block end -->\n";
}
}
|
[
"public",
"String",
"dialogBlock",
"(",
"int",
"segment",
",",
"String",
"headline",
",",
"boolean",
"error",
")",
"{",
"if",
"(",
"segment",
"==",
"HTML_START",
")",
"{",
"StringBuffer",
"result",
"=",
"new",
"StringBuffer",
"(",
"512",
")",
";",
"String",
"errorStyle",
"=",
"\"\"",
";",
"if",
"(",
"error",
")",
"{",
"errorStyle",
"=",
"\" dialogerror\"",
";",
"}",
"result",
".",
"append",
"(",
"\"<!-- 3D block start -->\\n\"",
")",
";",
"result",
".",
"append",
"(",
"\"<fieldset class=\\\"dialogblock\\\">\\n\"",
")",
";",
"if",
"(",
"CmsStringUtil",
".",
"isNotEmpty",
"(",
"headline",
")",
")",
"{",
"result",
".",
"append",
"(",
"\"<legend>\"",
")",
";",
"result",
".",
"append",
"(",
"\"<span class=\\\"textbold\"",
")",
";",
"result",
".",
"append",
"(",
"errorStyle",
")",
";",
"result",
".",
"append",
"(",
"\"\\\" unselectable=\\\"on\\\">\"",
")",
";",
"result",
".",
"append",
"(",
"headline",
")",
";",
"result",
".",
"append",
"(",
"\"</span></legend>\\n\"",
")",
";",
"}",
"return",
"result",
".",
"toString",
"(",
")",
";",
"}",
"else",
"{",
"return",
"\"</fieldset>\\n<!-- 3D block end -->\\n\"",
";",
"}",
"}"
] |
Builds a block with 3D border and optional subheadline in the dialog content area.<p>
@param segment the HTML segment (START / END)
@param headline the headline String for the block
@param error if true, an error block will be created
@return 3D block start / end segment
|
[
"Builds",
"a",
"block",
"with",
"3D",
"border",
"and",
"optional",
"subheadline",
"in",
"the",
"dialog",
"content",
"area",
".",
"<p",
">"
] |
train
|
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/workplace/CmsDialog.java#L545-L567
|
baidubce/bce-sdk-java
|
src/main/java/com/baidubce/services/lss/LssClient.java
|
LssClient.getDomainSummaryStatistics
|
public GetDomainSummaryStatisticsResponse getDomainSummaryStatistics(String startTime, String endTime) {
"""
get all domains' summary statistics in the live stream service.
@param startTime start time
@param endTime start time
@return the response
"""
GetDomainSummaryStatisticsRequest request = new GetDomainSummaryStatisticsRequest();
request.withStartTime(startTime).withEndTime(endTime);
return getDomainSummaryStatistics(request);
}
|
java
|
public GetDomainSummaryStatisticsResponse getDomainSummaryStatistics(String startTime, String endTime) {
GetDomainSummaryStatisticsRequest request = new GetDomainSummaryStatisticsRequest();
request.withStartTime(startTime).withEndTime(endTime);
return getDomainSummaryStatistics(request);
}
|
[
"public",
"GetDomainSummaryStatisticsResponse",
"getDomainSummaryStatistics",
"(",
"String",
"startTime",
",",
"String",
"endTime",
")",
"{",
"GetDomainSummaryStatisticsRequest",
"request",
"=",
"new",
"GetDomainSummaryStatisticsRequest",
"(",
")",
";",
"request",
".",
"withStartTime",
"(",
"startTime",
")",
".",
"withEndTime",
"(",
"endTime",
")",
";",
"return",
"getDomainSummaryStatistics",
"(",
"request",
")",
";",
"}"
] |
get all domains' summary statistics in the live stream service.
@param startTime start time
@param endTime start time
@return the response
|
[
"get",
"all",
"domains",
"summary",
"statistics",
"in",
"the",
"live",
"stream",
"service",
"."
] |
train
|
https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/services/lss/LssClient.java#L1840-L1844
|
xwiki/xwiki-rendering
|
xwiki-rendering-wikimodel/src/main/java/org/xwiki/rendering/wikimodel/impl/WikiScannerUtil.java
|
WikiScannerUtil.removeSpaces
|
private static int removeSpaces(char[] array, int pos, StringBuffer buf) {
"""
Moves forward the current position in the array until the first not empty
character is found.
@param array the array of characters where the spaces are searched
@param pos the current position in the array; starting from this position
the spaces will be searched
@param buf to this buffer all not empty characters will be added
@return the new position int the array of characters
"""
buf.delete(0, buf.length());
for (; pos < array.length
&& (array[pos] == '=' || Character.isSpaceChar(array[pos])); pos++)
{
if (array[pos] == '=') {
buf.append(array[pos]);
}
}
return pos;
}
|
java
|
private static int removeSpaces(char[] array, int pos, StringBuffer buf)
{
buf.delete(0, buf.length());
for (; pos < array.length
&& (array[pos] == '=' || Character.isSpaceChar(array[pos])); pos++)
{
if (array[pos] == '=') {
buf.append(array[pos]);
}
}
return pos;
}
|
[
"private",
"static",
"int",
"removeSpaces",
"(",
"char",
"[",
"]",
"array",
",",
"int",
"pos",
",",
"StringBuffer",
"buf",
")",
"{",
"buf",
".",
"delete",
"(",
"0",
",",
"buf",
".",
"length",
"(",
")",
")",
";",
"for",
"(",
";",
"pos",
"<",
"array",
".",
"length",
"&&",
"(",
"array",
"[",
"pos",
"]",
"==",
"'",
"'",
"||",
"Character",
".",
"isSpaceChar",
"(",
"array",
"[",
"pos",
"]",
")",
")",
";",
"pos",
"++",
")",
"{",
"if",
"(",
"array",
"[",
"pos",
"]",
"==",
"'",
"'",
")",
"{",
"buf",
".",
"append",
"(",
"array",
"[",
"pos",
"]",
")",
";",
"}",
"}",
"return",
"pos",
";",
"}"
] |
Moves forward the current position in the array until the first not empty
character is found.
@param array the array of characters where the spaces are searched
@param pos the current position in the array; starting from this position
the spaces will be searched
@param buf to this buffer all not empty characters will be added
@return the new position int the array of characters
|
[
"Moves",
"forward",
"the",
"current",
"position",
"in",
"the",
"array",
"until",
"the",
"first",
"not",
"empty",
"character",
"is",
"found",
"."
] |
train
|
https://github.com/xwiki/xwiki-rendering/blob/a21cdfcb64ef5b76872e3eedf78c530f26d7beb0/xwiki-rendering-wikimodel/src/main/java/org/xwiki/rendering/wikimodel/impl/WikiScannerUtil.java#L278-L289
|
milaboratory/milib
|
src/main/java/com/milaboratory/core/sequence/SequenceQuality.java
|
SequenceQuality.getUniformQuality
|
public static SequenceQuality getUniformQuality(byte qualityValue, int length) {
"""
Creates a phred sequence quality containing only given values of quality.
@param qualityValue value to fill the quality values with
@param length size of quality string
"""
byte[] data = new byte[length];
Arrays.fill(data, qualityValue);
return new SequenceQuality(data, true);
}
|
java
|
public static SequenceQuality getUniformQuality(byte qualityValue, int length) {
byte[] data = new byte[length];
Arrays.fill(data, qualityValue);
return new SequenceQuality(data, true);
}
|
[
"public",
"static",
"SequenceQuality",
"getUniformQuality",
"(",
"byte",
"qualityValue",
",",
"int",
"length",
")",
"{",
"byte",
"[",
"]",
"data",
"=",
"new",
"byte",
"[",
"length",
"]",
";",
"Arrays",
".",
"fill",
"(",
"data",
",",
"qualityValue",
")",
";",
"return",
"new",
"SequenceQuality",
"(",
"data",
",",
"true",
")",
";",
"}"
] |
Creates a phred sequence quality containing only given values of quality.
@param qualityValue value to fill the quality values with
@param length size of quality string
|
[
"Creates",
"a",
"phred",
"sequence",
"quality",
"containing",
"only",
"given",
"values",
"of",
"quality",
"."
] |
train
|
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/sequence/SequenceQuality.java#L312-L316
|
cojen/Cojen
|
src/main/java/org/cojen/classfile/attribute/CodeAttr.java
|
CodeAttr.getLocalVariable
|
public LocalVariable getLocalVariable(int useLocation, int number) {
"""
Returns local variable info at the given location, for the given number.
@return null if unknown
"""
LocalVariableTableAttr table = mOldLocalVariableTable;
if (table == null) {
table = mLocalVariableTable;
}
if (table == null) {
return null;
} else {
return table.getLocalVariable(useLocation, number);
}
}
|
java
|
public LocalVariable getLocalVariable(int useLocation, int number) {
LocalVariableTableAttr table = mOldLocalVariableTable;
if (table == null) {
table = mLocalVariableTable;
}
if (table == null) {
return null;
} else {
return table.getLocalVariable(useLocation, number);
}
}
|
[
"public",
"LocalVariable",
"getLocalVariable",
"(",
"int",
"useLocation",
",",
"int",
"number",
")",
"{",
"LocalVariableTableAttr",
"table",
"=",
"mOldLocalVariableTable",
";",
"if",
"(",
"table",
"==",
"null",
")",
"{",
"table",
"=",
"mLocalVariableTable",
";",
"}",
"if",
"(",
"table",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"else",
"{",
"return",
"table",
".",
"getLocalVariable",
"(",
"useLocation",
",",
"number",
")",
";",
"}",
"}"
] |
Returns local variable info at the given location, for the given number.
@return null if unknown
|
[
"Returns",
"local",
"variable",
"info",
"at",
"the",
"given",
"location",
"for",
"the",
"given",
"number",
"."
] |
train
|
https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/classfile/attribute/CodeAttr.java#L170-L181
|
UrielCh/ovh-java-sdk
|
ovh-java-sdk-clusterhadoop/src/main/java/net/minidev/ovh/api/ApiOvhClusterhadoop.java
|
ApiOvhClusterhadoop.serviceName_node_hostname_role_GET
|
public ArrayList<OvhRoleTypeEnum> serviceName_node_hostname_role_GET(String serviceName, String hostname) throws IOException {
"""
Roles (ie set of Hadoop services) of the Node
REST: GET /cluster/hadoop/{serviceName}/node/{hostname}/role
@param serviceName [required] The internal name of your cluster
@param hostname [required] Hostname of the node
"""
String qPath = "/cluster/hadoop/{serviceName}/node/{hostname}/role";
StringBuilder sb = path(qPath, serviceName, hostname);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t2);
}
|
java
|
public ArrayList<OvhRoleTypeEnum> serviceName_node_hostname_role_GET(String serviceName, String hostname) throws IOException {
String qPath = "/cluster/hadoop/{serviceName}/node/{hostname}/role";
StringBuilder sb = path(qPath, serviceName, hostname);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t2);
}
|
[
"public",
"ArrayList",
"<",
"OvhRoleTypeEnum",
">",
"serviceName_node_hostname_role_GET",
"(",
"String",
"serviceName",
",",
"String",
"hostname",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/cluster/hadoop/{serviceName}/node/{hostname}/role\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
",",
"serviceName",
",",
"hostname",
")",
";",
"String",
"resp",
"=",
"exec",
"(",
"qPath",
",",
"\"GET\"",
",",
"sb",
".",
"toString",
"(",
")",
",",
"null",
")",
";",
"return",
"convertTo",
"(",
"resp",
",",
"t2",
")",
";",
"}"
] |
Roles (ie set of Hadoop services) of the Node
REST: GET /cluster/hadoop/{serviceName}/node/{hostname}/role
@param serviceName [required] The internal name of your cluster
@param hostname [required] Hostname of the node
|
[
"Roles",
"(",
"ie",
"set",
"of",
"Hadoop",
"services",
")",
"of",
"the",
"Node"
] |
train
|
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-clusterhadoop/src/main/java/net/minidev/ovh/api/ApiOvhClusterhadoop.java#L271-L276
|
Azure/azure-sdk-for-java
|
network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/ExpressRouteCircuitsInner.java
|
ExpressRouteCircuitsInner.beginCreateOrUpdateAsync
|
public Observable<ExpressRouteCircuitInner> beginCreateOrUpdateAsync(String resourceGroupName, String circuitName, ExpressRouteCircuitInner parameters) {
"""
Creates or updates an express route circuit.
@param resourceGroupName The name of the resource group.
@param circuitName The name of the circuit.
@param parameters Parameters supplied to the create or update express route circuit operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the ExpressRouteCircuitInner object
"""
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, circuitName, parameters).map(new Func1<ServiceResponse<ExpressRouteCircuitInner>, ExpressRouteCircuitInner>() {
@Override
public ExpressRouteCircuitInner call(ServiceResponse<ExpressRouteCircuitInner> response) {
return response.body();
}
});
}
|
java
|
public Observable<ExpressRouteCircuitInner> beginCreateOrUpdateAsync(String resourceGroupName, String circuitName, ExpressRouteCircuitInner parameters) {
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, circuitName, parameters).map(new Func1<ServiceResponse<ExpressRouteCircuitInner>, ExpressRouteCircuitInner>() {
@Override
public ExpressRouteCircuitInner call(ServiceResponse<ExpressRouteCircuitInner> response) {
return response.body();
}
});
}
|
[
"public",
"Observable",
"<",
"ExpressRouteCircuitInner",
">",
"beginCreateOrUpdateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"circuitName",
",",
"ExpressRouteCircuitInner",
"parameters",
")",
"{",
"return",
"beginCreateOrUpdateWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"circuitName",
",",
"parameters",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"ExpressRouteCircuitInner",
">",
",",
"ExpressRouteCircuitInner",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"ExpressRouteCircuitInner",
"call",
"(",
"ServiceResponse",
"<",
"ExpressRouteCircuitInner",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Creates or updates an express route circuit.
@param resourceGroupName The name of the resource group.
@param circuitName The name of the circuit.
@param parameters Parameters supplied to the create or update express route circuit operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the ExpressRouteCircuitInner object
|
[
"Creates",
"or",
"updates",
"an",
"express",
"route",
"circuit",
"."
] |
train
|
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/ExpressRouteCircuitsInner.java#L497-L504
|
alkacon/opencms-core
|
src/org/opencms/jlan/CmsByteBuffer.java
|
CmsByteBuffer.readBytes
|
public void readBytes(byte[] dest, int srcStart, int destStart, int len) {
"""
Transfers bytes from this buffer to a target byte array.<p>
@param dest the byte array to which the bytes should be transferred
@param srcStart the start index in this buffer
@param destStart the start index in the destination buffer
@param len the number of bytes to transfer
"""
System.arraycopy(m_buffer, srcStart, dest, destStart, len);
}
|
java
|
public void readBytes(byte[] dest, int srcStart, int destStart, int len) {
System.arraycopy(m_buffer, srcStart, dest, destStart, len);
}
|
[
"public",
"void",
"readBytes",
"(",
"byte",
"[",
"]",
"dest",
",",
"int",
"srcStart",
",",
"int",
"destStart",
",",
"int",
"len",
")",
"{",
"System",
".",
"arraycopy",
"(",
"m_buffer",
",",
"srcStart",
",",
"dest",
",",
"destStart",
",",
"len",
")",
";",
"}"
] |
Transfers bytes from this buffer to a target byte array.<p>
@param dest the byte array to which the bytes should be transferred
@param srcStart the start index in this buffer
@param destStart the start index in the destination buffer
@param len the number of bytes to transfer
|
[
"Transfers",
"bytes",
"from",
"this",
"buffer",
"to",
"a",
"target",
"byte",
"array",
".",
"<p",
">"
] |
train
|
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/jlan/CmsByteBuffer.java#L86-L90
|
arquillian/arquillian-algeron
|
common/git/src/main/java/org/arquillian/algeron/git/GitOperations.java
|
GitOperations.pullFromRepository
|
public PullResult pullFromRepository(Git git, String remote, String remoteBranch, String username, String password) {
"""
Pull repository from current branch and remote branch with same name as current
@param git
instance.
@param remote
to be used.
@param remoteBranch
to use.
@param username
to connect
@param password
to connect
"""
try {
return git.pull()
.setRemote(remote)
.setRemoteBranchName(remoteBranch)
.setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password))
.call();
} catch (GitAPIException e) {
throw new IllegalStateException(e);
}
}
|
java
|
public PullResult pullFromRepository(Git git, String remote, String remoteBranch, String username, String password) {
try {
return git.pull()
.setRemote(remote)
.setRemoteBranchName(remoteBranch)
.setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password))
.call();
} catch (GitAPIException e) {
throw new IllegalStateException(e);
}
}
|
[
"public",
"PullResult",
"pullFromRepository",
"(",
"Git",
"git",
",",
"String",
"remote",
",",
"String",
"remoteBranch",
",",
"String",
"username",
",",
"String",
"password",
")",
"{",
"try",
"{",
"return",
"git",
".",
"pull",
"(",
")",
".",
"setRemote",
"(",
"remote",
")",
".",
"setRemoteBranchName",
"(",
"remoteBranch",
")",
".",
"setCredentialsProvider",
"(",
"new",
"UsernamePasswordCredentialsProvider",
"(",
"username",
",",
"password",
")",
")",
".",
"call",
"(",
")",
";",
"}",
"catch",
"(",
"GitAPIException",
"e",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"e",
")",
";",
"}",
"}"
] |
Pull repository from current branch and remote branch with same name as current
@param git
instance.
@param remote
to be used.
@param remoteBranch
to use.
@param username
to connect
@param password
to connect
|
[
"Pull",
"repository",
"from",
"current",
"branch",
"and",
"remote",
"branch",
"with",
"same",
"name",
"as",
"current"
] |
train
|
https://github.com/arquillian/arquillian-algeron/blob/ec79372defdafe99ab2f7bb696f1c1eabdbbacb6/common/git/src/main/java/org/arquillian/algeron/git/GitOperations.java#L401-L411
|
netty/netty
|
handler/src/main/java/io/netty/handler/ssl/OpenSslX509KeyManagerFactory.java
|
OpenSslX509KeyManagerFactory.newEngineBased
|
public static OpenSslX509KeyManagerFactory newEngineBased(X509Certificate[] certificateChain, String password)
throws CertificateException, IOException,
KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
"""
Create a new initialized {@link OpenSslX509KeyManagerFactory} which loads its {@link PrivateKey} directly from
an {@code OpenSSL engine} via the
<a href="https://www.openssl.org/docs/man1.1.0/crypto/ENGINE_load_private_key.html">ENGINE_load_private_key</a>
function.
"""
KeyStore store = new OpenSslKeyStore(certificateChain.clone(), false);
store.load(null, null);
OpenSslX509KeyManagerFactory factory = new OpenSslX509KeyManagerFactory();
factory.init(store, password == null ? null : password.toCharArray());
return factory;
}
|
java
|
public static OpenSslX509KeyManagerFactory newEngineBased(X509Certificate[] certificateChain, String password)
throws CertificateException, IOException,
KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
KeyStore store = new OpenSslKeyStore(certificateChain.clone(), false);
store.load(null, null);
OpenSslX509KeyManagerFactory factory = new OpenSslX509KeyManagerFactory();
factory.init(store, password == null ? null : password.toCharArray());
return factory;
}
|
[
"public",
"static",
"OpenSslX509KeyManagerFactory",
"newEngineBased",
"(",
"X509Certificate",
"[",
"]",
"certificateChain",
",",
"String",
"password",
")",
"throws",
"CertificateException",
",",
"IOException",
",",
"KeyStoreException",
",",
"NoSuchAlgorithmException",
",",
"UnrecoverableKeyException",
"{",
"KeyStore",
"store",
"=",
"new",
"OpenSslKeyStore",
"(",
"certificateChain",
".",
"clone",
"(",
")",
",",
"false",
")",
";",
"store",
".",
"load",
"(",
"null",
",",
"null",
")",
";",
"OpenSslX509KeyManagerFactory",
"factory",
"=",
"new",
"OpenSslX509KeyManagerFactory",
"(",
")",
";",
"factory",
".",
"init",
"(",
"store",
",",
"password",
"==",
"null",
"?",
"null",
":",
"password",
".",
"toCharArray",
"(",
")",
")",
";",
"return",
"factory",
";",
"}"
] |
Create a new initialized {@link OpenSslX509KeyManagerFactory} which loads its {@link PrivateKey} directly from
an {@code OpenSSL engine} via the
<a href="https://www.openssl.org/docs/man1.1.0/crypto/ENGINE_load_private_key.html">ENGINE_load_private_key</a>
function.
|
[
"Create",
"a",
"new",
"initialized",
"{"
] |
train
|
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/handler/src/main/java/io/netty/handler/ssl/OpenSslX509KeyManagerFactory.java#L252-L260
|
openengsb/openengsb
|
components/ekb/transformation-wonderland/src/main/java/org/openengsb/core/ekb/transformation/wonderland/internal/performer/TransformationPerformer.java
|
TransformationPerformer.setObjectToTargetField
|
private void setObjectToTargetField(String fieldname, Object value) throws Exception {
"""
Sets the given value object to the field with the field name of the target object. Is also aware of temporary
fields.
"""
Object toWrite = null;
if (fieldname.contains(".")) {
String path = StringUtils.substringBeforeLast(fieldname, ".");
toWrite = getObjectValue(path, false);
}
if (toWrite == null && isTemporaryField(fieldname)) {
String mapKey = StringUtils.substringAfter(fieldname, "#");
mapKey = StringUtils.substringBefore(mapKey, ".");
temporaryFields.put(mapKey, value);
return;
}
String realFieldName = fieldname.contains(".") ? StringUtils.substringAfterLast(fieldname, ".") : fieldname;
writeObjectToField(realFieldName, value, toWrite, target);
}
|
java
|
private void setObjectToTargetField(String fieldname, Object value) throws Exception {
Object toWrite = null;
if (fieldname.contains(".")) {
String path = StringUtils.substringBeforeLast(fieldname, ".");
toWrite = getObjectValue(path, false);
}
if (toWrite == null && isTemporaryField(fieldname)) {
String mapKey = StringUtils.substringAfter(fieldname, "#");
mapKey = StringUtils.substringBefore(mapKey, ".");
temporaryFields.put(mapKey, value);
return;
}
String realFieldName = fieldname.contains(".") ? StringUtils.substringAfterLast(fieldname, ".") : fieldname;
writeObjectToField(realFieldName, value, toWrite, target);
}
|
[
"private",
"void",
"setObjectToTargetField",
"(",
"String",
"fieldname",
",",
"Object",
"value",
")",
"throws",
"Exception",
"{",
"Object",
"toWrite",
"=",
"null",
";",
"if",
"(",
"fieldname",
".",
"contains",
"(",
"\".\"",
")",
")",
"{",
"String",
"path",
"=",
"StringUtils",
".",
"substringBeforeLast",
"(",
"fieldname",
",",
"\".\"",
")",
";",
"toWrite",
"=",
"getObjectValue",
"(",
"path",
",",
"false",
")",
";",
"}",
"if",
"(",
"toWrite",
"==",
"null",
"&&",
"isTemporaryField",
"(",
"fieldname",
")",
")",
"{",
"String",
"mapKey",
"=",
"StringUtils",
".",
"substringAfter",
"(",
"fieldname",
",",
"\"#\"",
")",
";",
"mapKey",
"=",
"StringUtils",
".",
"substringBefore",
"(",
"mapKey",
",",
"\".\"",
")",
";",
"temporaryFields",
".",
"put",
"(",
"mapKey",
",",
"value",
")",
";",
"return",
";",
"}",
"String",
"realFieldName",
"=",
"fieldname",
".",
"contains",
"(",
"\".\"",
")",
"?",
"StringUtils",
".",
"substringAfterLast",
"(",
"fieldname",
",",
"\".\"",
")",
":",
"fieldname",
";",
"writeObjectToField",
"(",
"realFieldName",
",",
"value",
",",
"toWrite",
",",
"target",
")",
";",
"}"
] |
Sets the given value object to the field with the field name of the target object. Is also aware of temporary
fields.
|
[
"Sets",
"the",
"given",
"value",
"object",
"to",
"the",
"field",
"with",
"the",
"field",
"name",
"of",
"the",
"target",
"object",
".",
"Is",
"also",
"aware",
"of",
"temporary",
"fields",
"."
] |
train
|
https://github.com/openengsb/openengsb/blob/d39058000707f617cd405629f9bc7f17da7b414a/components/ekb/transformation-wonderland/src/main/java/org/openengsb/core/ekb/transformation/wonderland/internal/performer/TransformationPerformer.java#L146-L160
|
Mozu/mozu-java
|
mozu-javaasync-core/src/main/java/com/mozu/api/urls/platform/entitylists/EntityUrl.java
|
EntityUrl.getEntityUrl
|
public static MozuUrl getEntityUrl(String entityListFullName, String id, String responseFields) {
"""
Get Resource Url for GetEntity
@param entityListFullName The full name of the EntityList including namespace in name@nameSpace format
@param id Unique identifier of the customer segment to retrieve.
@param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
@return String Resource Url
"""
UrlFormatter formatter = new UrlFormatter("/api/platform/entitylists/{entityListFullName}/entities/{id}?responseFields={responseFields}");
formatter.formatUrl("entityListFullName", entityListFullName);
formatter.formatUrl("id", id);
formatter.formatUrl("responseFields", responseFields);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
}
|
java
|
public static MozuUrl getEntityUrl(String entityListFullName, String id, String responseFields)
{
UrlFormatter formatter = new UrlFormatter("/api/platform/entitylists/{entityListFullName}/entities/{id}?responseFields={responseFields}");
formatter.formatUrl("entityListFullName", entityListFullName);
formatter.formatUrl("id", id);
formatter.formatUrl("responseFields", responseFields);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
}
|
[
"public",
"static",
"MozuUrl",
"getEntityUrl",
"(",
"String",
"entityListFullName",
",",
"String",
"id",
",",
"String",
"responseFields",
")",
"{",
"UrlFormatter",
"formatter",
"=",
"new",
"UrlFormatter",
"(",
"\"/api/platform/entitylists/{entityListFullName}/entities/{id}?responseFields={responseFields}\"",
")",
";",
"formatter",
".",
"formatUrl",
"(",
"\"entityListFullName\"",
",",
"entityListFullName",
")",
";",
"formatter",
".",
"formatUrl",
"(",
"\"id\"",
",",
"id",
")",
";",
"formatter",
".",
"formatUrl",
"(",
"\"responseFields\"",
",",
"responseFields",
")",
";",
"return",
"new",
"MozuUrl",
"(",
"formatter",
".",
"getResourceUrl",
"(",
")",
",",
"MozuUrl",
".",
"UrlLocation",
".",
"TENANT_POD",
")",
";",
"}"
] |
Get Resource Url for GetEntity
@param entityListFullName The full name of the EntityList including namespace in name@nameSpace format
@param id Unique identifier of the customer segment to retrieve.
@param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
@return String Resource Url
|
[
"Get",
"Resource",
"Url",
"for",
"GetEntity"
] |
train
|
https://github.com/Mozu/mozu-java/blob/5beadde73601a859f845e3e2fc1077b39c8bea83/mozu-javaasync-core/src/main/java/com/mozu/api/urls/platform/entitylists/EntityUrl.java#L23-L30
|
UrielCh/ovh-java-sdk
|
ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java
|
ApiOvhTelephony.billingAccount_easyPabx_serviceName_hunting_PUT
|
public void billingAccount_easyPabx_serviceName_hunting_PUT(String billingAccount, String serviceName, OvhEasyPabxHunting body) throws IOException {
"""
Alter this object properties
REST: PUT /telephony/{billingAccount}/easyPabx/{serviceName}/hunting
@param body [required] New object properties
@param billingAccount [required] The name of your billingAccount
@param serviceName [required]
"""
String qPath = "/telephony/{billingAccount}/easyPabx/{serviceName}/hunting";
StringBuilder sb = path(qPath, billingAccount, serviceName);
exec(qPath, "PUT", sb.toString(), body);
}
|
java
|
public void billingAccount_easyPabx_serviceName_hunting_PUT(String billingAccount, String serviceName, OvhEasyPabxHunting body) throws IOException {
String qPath = "/telephony/{billingAccount}/easyPabx/{serviceName}/hunting";
StringBuilder sb = path(qPath, billingAccount, serviceName);
exec(qPath, "PUT", sb.toString(), body);
}
|
[
"public",
"void",
"billingAccount_easyPabx_serviceName_hunting_PUT",
"(",
"String",
"billingAccount",
",",
"String",
"serviceName",
",",
"OvhEasyPabxHunting",
"body",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/telephony/{billingAccount}/easyPabx/{serviceName}/hunting\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
",",
"billingAccount",
",",
"serviceName",
")",
";",
"exec",
"(",
"qPath",
",",
"\"PUT\"",
",",
"sb",
".",
"toString",
"(",
")",
",",
"body",
")",
";",
"}"
] |
Alter this object properties
REST: PUT /telephony/{billingAccount}/easyPabx/{serviceName}/hunting
@param body [required] New object properties
@param billingAccount [required] The name of your billingAccount
@param serviceName [required]
|
[
"Alter",
"this",
"object",
"properties"
] |
train
|
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java#L3491-L3495
|
orbisgis/h2gis
|
h2gis-functions/src/main/java/org/h2gis/functions/io/geojson/GJGeometryReader.java
|
GJGeometryReader.parseMultiLinestring
|
private MultiLineString parseMultiLinestring(JsonParser jp) throws IOException, SQLException {
"""
Parses an array of positions defined as:
{ "type": "MultiLineString", "coordinates": [ [ [100.0, 0.0], [101.0,
1.0] ], [ [102.0, 2.0], [103.0, 3.0] ] ] }
@param jsParser
@return MultiLineString
"""
jp.nextToken(); // FIELD_NAME coordinates
String coordinatesField = jp.getText();
if (coordinatesField.equalsIgnoreCase(GeoJsonField.COORDINATES)) {
ArrayList<LineString> lineStrings = new ArrayList<LineString>();
jp.nextToken();//START_ARRAY [ coordinates
jp.nextToken(); // START_ARRAY [ coordinates line
while (jp.getCurrentToken() != JsonToken.END_ARRAY) {
lineStrings.add(GF.createLineString(parseCoordinates(jp)));
jp.nextToken();
}
MultiLineString line = GF.createMultiLineString(lineStrings.toArray(new LineString[0]));
jp.nextToken();//END_OBJECT } geometry
return line;
} else {
throw new SQLException("Malformed GeoJSON file. Expected 'coordinates', found '" + coordinatesField + "'");
}
}
|
java
|
private MultiLineString parseMultiLinestring(JsonParser jp) throws IOException, SQLException {
jp.nextToken(); // FIELD_NAME coordinates
String coordinatesField = jp.getText();
if (coordinatesField.equalsIgnoreCase(GeoJsonField.COORDINATES)) {
ArrayList<LineString> lineStrings = new ArrayList<LineString>();
jp.nextToken();//START_ARRAY [ coordinates
jp.nextToken(); // START_ARRAY [ coordinates line
while (jp.getCurrentToken() != JsonToken.END_ARRAY) {
lineStrings.add(GF.createLineString(parseCoordinates(jp)));
jp.nextToken();
}
MultiLineString line = GF.createMultiLineString(lineStrings.toArray(new LineString[0]));
jp.nextToken();//END_OBJECT } geometry
return line;
} else {
throw new SQLException("Malformed GeoJSON file. Expected 'coordinates', found '" + coordinatesField + "'");
}
}
|
[
"private",
"MultiLineString",
"parseMultiLinestring",
"(",
"JsonParser",
"jp",
")",
"throws",
"IOException",
",",
"SQLException",
"{",
"jp",
".",
"nextToken",
"(",
")",
";",
"// FIELD_NAME coordinates ",
"String",
"coordinatesField",
"=",
"jp",
".",
"getText",
"(",
")",
";",
"if",
"(",
"coordinatesField",
".",
"equalsIgnoreCase",
"(",
"GeoJsonField",
".",
"COORDINATES",
")",
")",
"{",
"ArrayList",
"<",
"LineString",
">",
"lineStrings",
"=",
"new",
"ArrayList",
"<",
"LineString",
">",
"(",
")",
";",
"jp",
".",
"nextToken",
"(",
")",
";",
"//START_ARRAY [ coordinates",
"jp",
".",
"nextToken",
"(",
")",
";",
"// START_ARRAY [ coordinates line",
"while",
"(",
"jp",
".",
"getCurrentToken",
"(",
")",
"!=",
"JsonToken",
".",
"END_ARRAY",
")",
"{",
"lineStrings",
".",
"add",
"(",
"GF",
".",
"createLineString",
"(",
"parseCoordinates",
"(",
"jp",
")",
")",
")",
";",
"jp",
".",
"nextToken",
"(",
")",
";",
"}",
"MultiLineString",
"line",
"=",
"GF",
".",
"createMultiLineString",
"(",
"lineStrings",
".",
"toArray",
"(",
"new",
"LineString",
"[",
"0",
"]",
")",
")",
";",
"jp",
".",
"nextToken",
"(",
")",
";",
"//END_OBJECT } geometry",
"return",
"line",
";",
"}",
"else",
"{",
"throw",
"new",
"SQLException",
"(",
"\"Malformed GeoJSON file. Expected 'coordinates', found '\"",
"+",
"coordinatesField",
"+",
"\"'\"",
")",
";",
"}",
"}"
] |
Parses an array of positions defined as:
{ "type": "MultiLineString", "coordinates": [ [ [100.0, 0.0], [101.0,
1.0] ], [ [102.0, 2.0], [103.0, 3.0] ] ] }
@param jsParser
@return MultiLineString
|
[
"Parses",
"an",
"array",
"of",
"positions",
"defined",
"as",
":"
] |
train
|
https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/io/geojson/GJGeometryReader.java#L160-L178
|
Squarespace/cldr
|
compiler/src/main/java/com/squarespace/cldr/codegen/CodeGenerator.java
|
CodeGenerator.saveClass
|
public static void saveClass(Path rootDir, String packageName, String className, TypeSpec type)
throws IOException {
"""
Saves a Java class file to a path for the given package, rooted in rootDir.
"""
List<String> packagePath = Splitter.on('.').splitToList(packageName);
Path classPath = Paths.get(rootDir.toString(), packagePath.toArray(EMPTY));
Path outputFile = classPath.resolve(className + ".java");
JavaFile javaFile = JavaFile.builder(packageName, type)
.addFileComment("\n\nAUTO-GENERATED CLASS - DO NOT EDIT\n\n")
// TODO: build timestamp and version info
.build();
System.out.println("saving " + outputFile);
Files.createParentDirs(outputFile.toFile());
CharSink sink = Files.asCharSink(outputFile.toFile(), Charsets.UTF_8);
sink.write(javaFile.toString());
}
|
java
|
public static void saveClass(Path rootDir, String packageName, String className, TypeSpec type)
throws IOException {
List<String> packagePath = Splitter.on('.').splitToList(packageName);
Path classPath = Paths.get(rootDir.toString(), packagePath.toArray(EMPTY));
Path outputFile = classPath.resolve(className + ".java");
JavaFile javaFile = JavaFile.builder(packageName, type)
.addFileComment("\n\nAUTO-GENERATED CLASS - DO NOT EDIT\n\n")
// TODO: build timestamp and version info
.build();
System.out.println("saving " + outputFile);
Files.createParentDirs(outputFile.toFile());
CharSink sink = Files.asCharSink(outputFile.toFile(), Charsets.UTF_8);
sink.write(javaFile.toString());
}
|
[
"public",
"static",
"void",
"saveClass",
"(",
"Path",
"rootDir",
",",
"String",
"packageName",
",",
"String",
"className",
",",
"TypeSpec",
"type",
")",
"throws",
"IOException",
"{",
"List",
"<",
"String",
">",
"packagePath",
"=",
"Splitter",
".",
"on",
"(",
"'",
"'",
")",
".",
"splitToList",
"(",
"packageName",
")",
";",
"Path",
"classPath",
"=",
"Paths",
".",
"get",
"(",
"rootDir",
".",
"toString",
"(",
")",
",",
"packagePath",
".",
"toArray",
"(",
"EMPTY",
")",
")",
";",
"Path",
"outputFile",
"=",
"classPath",
".",
"resolve",
"(",
"className",
"+",
"\".java\"",
")",
";",
"JavaFile",
"javaFile",
"=",
"JavaFile",
".",
"builder",
"(",
"packageName",
",",
"type",
")",
".",
"addFileComment",
"(",
"\"\\n\\nAUTO-GENERATED CLASS - DO NOT EDIT\\n\\n\"",
")",
"// TODO: build timestamp and version info",
".",
"build",
"(",
")",
";",
"System",
".",
"out",
".",
"println",
"(",
"\"saving \"",
"+",
"outputFile",
")",
";",
"Files",
".",
"createParentDirs",
"(",
"outputFile",
".",
"toFile",
"(",
")",
")",
";",
"CharSink",
"sink",
"=",
"Files",
".",
"asCharSink",
"(",
"outputFile",
".",
"toFile",
"(",
")",
",",
"Charsets",
".",
"UTF_8",
")",
";",
"sink",
".",
"write",
"(",
"javaFile",
".",
"toString",
"(",
")",
")",
";",
"}"
] |
Saves a Java class file to a path for the given package, rooted in rootDir.
|
[
"Saves",
"a",
"Java",
"class",
"file",
"to",
"a",
"path",
"for",
"the",
"given",
"package",
"rooted",
"in",
"rootDir",
"."
] |
train
|
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/CodeGenerator.java#L128-L144
|
shrinkwrap/resolver
|
maven/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/MavenArtifactInfoImpl.java
|
MavenArtifactInfoImpl.fromDependencyNode
|
static MavenArtifactInfo fromDependencyNode(final DependencyNode dependencyNode) {
"""
Creates MavenArtifactInfo based on DependencyNode.
@param dependencyNode
dependencyNode
@return The new {@link MavenArtifactInfo> instance.
"""
final Artifact artifact = dependencyNode.getDependency().getArtifact();
final List<DependencyNode> children = dependencyNode.getChildren();
// SHRINKRES-143 lets ignore invalid scope
ScopeType scopeType = ScopeType.RUNTIME;
try {
scopeType = ScopeType.fromScopeType(dependencyNode.getDependency().getScope());
} catch (IllegalArgumentException e) {
// let scope be RUNTIME
log.log(Level.WARNING, "Invalid scope {0} of retrieved dependency {1} will be replaced by <scope>runtime</scope>",
new Object[] { dependencyNode.getDependency().getScope(), dependencyNode.getDependency().getArtifact() });
}
final boolean optional = dependencyNode.getDependency().isOptional();
return new MavenArtifactInfoImpl(artifact, scopeType, children, optional);
}
|
java
|
static MavenArtifactInfo fromDependencyNode(final DependencyNode dependencyNode) {
final Artifact artifact = dependencyNode.getDependency().getArtifact();
final List<DependencyNode> children = dependencyNode.getChildren();
// SHRINKRES-143 lets ignore invalid scope
ScopeType scopeType = ScopeType.RUNTIME;
try {
scopeType = ScopeType.fromScopeType(dependencyNode.getDependency().getScope());
} catch (IllegalArgumentException e) {
// let scope be RUNTIME
log.log(Level.WARNING, "Invalid scope {0} of retrieved dependency {1} will be replaced by <scope>runtime</scope>",
new Object[] { dependencyNode.getDependency().getScope(), dependencyNode.getDependency().getArtifact() });
}
final boolean optional = dependencyNode.getDependency().isOptional();
return new MavenArtifactInfoImpl(artifact, scopeType, children, optional);
}
|
[
"static",
"MavenArtifactInfo",
"fromDependencyNode",
"(",
"final",
"DependencyNode",
"dependencyNode",
")",
"{",
"final",
"Artifact",
"artifact",
"=",
"dependencyNode",
".",
"getDependency",
"(",
")",
".",
"getArtifact",
"(",
")",
";",
"final",
"List",
"<",
"DependencyNode",
">",
"children",
"=",
"dependencyNode",
".",
"getChildren",
"(",
")",
";",
"// SHRINKRES-143 lets ignore invalid scope",
"ScopeType",
"scopeType",
"=",
"ScopeType",
".",
"RUNTIME",
";",
"try",
"{",
"scopeType",
"=",
"ScopeType",
".",
"fromScopeType",
"(",
"dependencyNode",
".",
"getDependency",
"(",
")",
".",
"getScope",
"(",
")",
")",
";",
"}",
"catch",
"(",
"IllegalArgumentException",
"e",
")",
"{",
"// let scope be RUNTIME",
"log",
".",
"log",
"(",
"Level",
".",
"WARNING",
",",
"\"Invalid scope {0} of retrieved dependency {1} will be replaced by <scope>runtime</scope>\"",
",",
"new",
"Object",
"[",
"]",
"{",
"dependencyNode",
".",
"getDependency",
"(",
")",
".",
"getScope",
"(",
")",
",",
"dependencyNode",
".",
"getDependency",
"(",
")",
".",
"getArtifact",
"(",
")",
"}",
")",
";",
"}",
"final",
"boolean",
"optional",
"=",
"dependencyNode",
".",
"getDependency",
"(",
")",
".",
"isOptional",
"(",
")",
";",
"return",
"new",
"MavenArtifactInfoImpl",
"(",
"artifact",
",",
"scopeType",
",",
"children",
",",
"optional",
")",
";",
"}"
] |
Creates MavenArtifactInfo based on DependencyNode.
@param dependencyNode
dependencyNode
@return The new {@link MavenArtifactInfo> instance.
|
[
"Creates",
"MavenArtifactInfo",
"based",
"on",
"DependencyNode",
"."
] |
train
|
https://github.com/shrinkwrap/resolver/blob/e881a84b8cff5b0a014f2a5ebf612be3eb9db01f/maven/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/MavenArtifactInfoImpl.java#L69-L84
|
playn/playn
|
html/src/playn/html/HtmlInput.java
|
HtmlInput.getRelativeY
|
static float getRelativeY (NativeEvent e, Element target) {
"""
Gets the event's y-position relative to a given element.
@param e native event
@param target the element whose coordinate system is to be used
@return the relative y-position
"""
return (e.getClientY() - target.getAbsoluteTop() + target.getScrollTop() +
target.getOwnerDocument().getScrollTop()) / HtmlGraphics.experimentalScale;
}
|
java
|
static float getRelativeY (NativeEvent e, Element target) {
return (e.getClientY() - target.getAbsoluteTop() + target.getScrollTop() +
target.getOwnerDocument().getScrollTop()) / HtmlGraphics.experimentalScale;
}
|
[
"static",
"float",
"getRelativeY",
"(",
"NativeEvent",
"e",
",",
"Element",
"target",
")",
"{",
"return",
"(",
"e",
".",
"getClientY",
"(",
")",
"-",
"target",
".",
"getAbsoluteTop",
"(",
")",
"+",
"target",
".",
"getScrollTop",
"(",
")",
"+",
"target",
".",
"getOwnerDocument",
"(",
")",
".",
"getScrollTop",
"(",
")",
")",
"/",
"HtmlGraphics",
".",
"experimentalScale",
";",
"}"
] |
Gets the event's y-position relative to a given element.
@param e native event
@param target the element whose coordinate system is to be used
@return the relative y-position
|
[
"Gets",
"the",
"event",
"s",
"y",
"-",
"position",
"relative",
"to",
"a",
"given",
"element",
"."
] |
train
|
https://github.com/playn/playn/blob/7e7a9d048ba6afe550dc0cdeaca3e1d5b0d01c66/html/src/playn/html/HtmlInput.java#L323-L326
|
cdk/cdk
|
tool/hash/src/main/java/org/openscience/cdk/hash/stereo/GeometricCumulativeDoubleBondFactory.java
|
GeometricCumulativeDoubleBondFactory.axialEncoder
|
static StereoEncoder axialEncoder(IAtomContainer container, IAtom start, IAtom end) {
"""
Create an encoder for axial 2D stereochemistry for the given start and
end atoms.
@param container the molecule
@param start start of the cumulated system
@param end end of the cumulated system
@return an encoder or null if there are no coordinated
"""
List<IBond> startBonds = container.getConnectedBondsList(start);
List<IBond> endBonds = container.getConnectedBondsList(end);
if (startBonds.size() < 2 || endBonds.size() < 2) return null;
if (has2DCoordinates(startBonds) && has2DCoordinates(endBonds)) {
return axial2DEncoder(container, start, startBonds, end, endBonds);
} else if (has3DCoordinates(startBonds) && has3DCoordinates(endBonds)) {
return axial3DEncoder(container, start, startBonds, end, endBonds);
}
return null;
}
|
java
|
static StereoEncoder axialEncoder(IAtomContainer container, IAtom start, IAtom end) {
List<IBond> startBonds = container.getConnectedBondsList(start);
List<IBond> endBonds = container.getConnectedBondsList(end);
if (startBonds.size() < 2 || endBonds.size() < 2) return null;
if (has2DCoordinates(startBonds) && has2DCoordinates(endBonds)) {
return axial2DEncoder(container, start, startBonds, end, endBonds);
} else if (has3DCoordinates(startBonds) && has3DCoordinates(endBonds)) {
return axial3DEncoder(container, start, startBonds, end, endBonds);
}
return null;
}
|
[
"static",
"StereoEncoder",
"axialEncoder",
"(",
"IAtomContainer",
"container",
",",
"IAtom",
"start",
",",
"IAtom",
"end",
")",
"{",
"List",
"<",
"IBond",
">",
"startBonds",
"=",
"container",
".",
"getConnectedBondsList",
"(",
"start",
")",
";",
"List",
"<",
"IBond",
">",
"endBonds",
"=",
"container",
".",
"getConnectedBondsList",
"(",
"end",
")",
";",
"if",
"(",
"startBonds",
".",
"size",
"(",
")",
"<",
"2",
"||",
"endBonds",
".",
"size",
"(",
")",
"<",
"2",
")",
"return",
"null",
";",
"if",
"(",
"has2DCoordinates",
"(",
"startBonds",
")",
"&&",
"has2DCoordinates",
"(",
"endBonds",
")",
")",
"{",
"return",
"axial2DEncoder",
"(",
"container",
",",
"start",
",",
"startBonds",
",",
"end",
",",
"endBonds",
")",
";",
"}",
"else",
"if",
"(",
"has3DCoordinates",
"(",
"startBonds",
")",
"&&",
"has3DCoordinates",
"(",
"endBonds",
")",
")",
"{",
"return",
"axial3DEncoder",
"(",
"container",
",",
"start",
",",
"startBonds",
",",
"end",
",",
"endBonds",
")",
";",
"}",
"return",
"null",
";",
"}"
] |
Create an encoder for axial 2D stereochemistry for the given start and
end atoms.
@param container the molecule
@param start start of the cumulated system
@param end end of the cumulated system
@return an encoder or null if there are no coordinated
|
[
"Create",
"an",
"encoder",
"for",
"axial",
"2D",
"stereochemistry",
"for",
"the",
"given",
"start",
"and",
"end",
"atoms",
"."
] |
train
|
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/tool/hash/src/main/java/org/openscience/cdk/hash/stereo/GeometricCumulativeDoubleBondFactory.java#L144-L158
|
prestodb/presto
|
presto-benchmark/src/main/java/com/facebook/presto/benchmark/HashJoinBenchmark.java
|
HashJoinBenchmark.createDrivers
|
@Override
protected List<Driver> createDrivers(TaskContext taskContext) {
"""
/*
select orderkey, quantity, totalprice
from lineitem join orders using (orderkey)
"""
if (probeDriverFactory == null) {
List<Type> ordersTypes = getColumnTypes("orders", "orderkey", "totalprice");
OperatorFactory ordersTableScan = createTableScanOperator(0, new PlanNodeId("test"), "orders", "orderkey", "totalprice");
JoinBridgeManager<PartitionedLookupSourceFactory> lookupSourceFactoryManager = JoinBridgeManager.lookupAllAtOnce(new PartitionedLookupSourceFactory(
ordersTypes,
ImmutableList.of(0, 1).stream()
.map(ordersTypes::get)
.collect(toImmutableList()),
Ints.asList(0).stream()
.map(ordersTypes::get)
.collect(toImmutableList()),
1,
requireNonNull(ImmutableMap.of(), "layout is null"),
false));
HashBuilderOperatorFactory hashBuilder = new HashBuilderOperatorFactory(
1,
new PlanNodeId("test"),
lookupSourceFactoryManager,
ImmutableList.of(0, 1),
Ints.asList(0),
OptionalInt.empty(),
Optional.empty(),
Optional.empty(),
ImmutableList.of(),
1_500_000,
new PagesIndex.TestingFactory(false),
false,
SingleStreamSpillerFactory.unsupportedSingleStreamSpillerFactory());
DriverContext driverContext = taskContext.addPipelineContext(0, false, false, false).addDriverContext();
DriverFactory buildDriverFactory = new DriverFactory(0, false, false, ImmutableList.of(ordersTableScan, hashBuilder), OptionalInt.empty(), UNGROUPED_EXECUTION);
List<Type> lineItemTypes = getColumnTypes("lineitem", "orderkey", "quantity");
OperatorFactory lineItemTableScan = createTableScanOperator(0, new PlanNodeId("test"), "lineitem", "orderkey", "quantity");
OperatorFactory joinOperator = LOOKUP_JOIN_OPERATORS.innerJoin(1, new PlanNodeId("test"), lookupSourceFactoryManager, lineItemTypes, Ints.asList(0), OptionalInt.empty(), Optional.empty(), OptionalInt.empty(), unsupportedPartitioningSpillerFactory());
NullOutputOperatorFactory output = new NullOutputOperatorFactory(2, new PlanNodeId("test"));
this.probeDriverFactory = new DriverFactory(1, true, true, ImmutableList.of(lineItemTableScan, joinOperator, output), OptionalInt.empty(), UNGROUPED_EXECUTION);
Driver driver = buildDriverFactory.createDriver(driverContext);
Future<LookupSourceProvider> lookupSourceProvider = lookupSourceFactoryManager.getJoinBridge(Lifespan.taskWide()).createLookupSourceProvider();
while (!lookupSourceProvider.isDone()) {
driver.process();
}
getFutureValue(lookupSourceProvider).close();
}
DriverContext driverContext = taskContext.addPipelineContext(1, true, true, false).addDriverContext();
Driver driver = probeDriverFactory.createDriver(driverContext);
return ImmutableList.of(driver);
}
|
java
|
@Override
protected List<Driver> createDrivers(TaskContext taskContext)
{
if (probeDriverFactory == null) {
List<Type> ordersTypes = getColumnTypes("orders", "orderkey", "totalprice");
OperatorFactory ordersTableScan = createTableScanOperator(0, new PlanNodeId("test"), "orders", "orderkey", "totalprice");
JoinBridgeManager<PartitionedLookupSourceFactory> lookupSourceFactoryManager = JoinBridgeManager.lookupAllAtOnce(new PartitionedLookupSourceFactory(
ordersTypes,
ImmutableList.of(0, 1).stream()
.map(ordersTypes::get)
.collect(toImmutableList()),
Ints.asList(0).stream()
.map(ordersTypes::get)
.collect(toImmutableList()),
1,
requireNonNull(ImmutableMap.of(), "layout is null"),
false));
HashBuilderOperatorFactory hashBuilder = new HashBuilderOperatorFactory(
1,
new PlanNodeId("test"),
lookupSourceFactoryManager,
ImmutableList.of(0, 1),
Ints.asList(0),
OptionalInt.empty(),
Optional.empty(),
Optional.empty(),
ImmutableList.of(),
1_500_000,
new PagesIndex.TestingFactory(false),
false,
SingleStreamSpillerFactory.unsupportedSingleStreamSpillerFactory());
DriverContext driverContext = taskContext.addPipelineContext(0, false, false, false).addDriverContext();
DriverFactory buildDriverFactory = new DriverFactory(0, false, false, ImmutableList.of(ordersTableScan, hashBuilder), OptionalInt.empty(), UNGROUPED_EXECUTION);
List<Type> lineItemTypes = getColumnTypes("lineitem", "orderkey", "quantity");
OperatorFactory lineItemTableScan = createTableScanOperator(0, new PlanNodeId("test"), "lineitem", "orderkey", "quantity");
OperatorFactory joinOperator = LOOKUP_JOIN_OPERATORS.innerJoin(1, new PlanNodeId("test"), lookupSourceFactoryManager, lineItemTypes, Ints.asList(0), OptionalInt.empty(), Optional.empty(), OptionalInt.empty(), unsupportedPartitioningSpillerFactory());
NullOutputOperatorFactory output = new NullOutputOperatorFactory(2, new PlanNodeId("test"));
this.probeDriverFactory = new DriverFactory(1, true, true, ImmutableList.of(lineItemTableScan, joinOperator, output), OptionalInt.empty(), UNGROUPED_EXECUTION);
Driver driver = buildDriverFactory.createDriver(driverContext);
Future<LookupSourceProvider> lookupSourceProvider = lookupSourceFactoryManager.getJoinBridge(Lifespan.taskWide()).createLookupSourceProvider();
while (!lookupSourceProvider.isDone()) {
driver.process();
}
getFutureValue(lookupSourceProvider).close();
}
DriverContext driverContext = taskContext.addPipelineContext(1, true, true, false).addDriverContext();
Driver driver = probeDriverFactory.createDriver(driverContext);
return ImmutableList.of(driver);
}
|
[
"@",
"Override",
"protected",
"List",
"<",
"Driver",
">",
"createDrivers",
"(",
"TaskContext",
"taskContext",
")",
"{",
"if",
"(",
"probeDriverFactory",
"==",
"null",
")",
"{",
"List",
"<",
"Type",
">",
"ordersTypes",
"=",
"getColumnTypes",
"(",
"\"orders\"",
",",
"\"orderkey\"",
",",
"\"totalprice\"",
")",
";",
"OperatorFactory",
"ordersTableScan",
"=",
"createTableScanOperator",
"(",
"0",
",",
"new",
"PlanNodeId",
"(",
"\"test\"",
")",
",",
"\"orders\"",
",",
"\"orderkey\"",
",",
"\"totalprice\"",
")",
";",
"JoinBridgeManager",
"<",
"PartitionedLookupSourceFactory",
">",
"lookupSourceFactoryManager",
"=",
"JoinBridgeManager",
".",
"lookupAllAtOnce",
"(",
"new",
"PartitionedLookupSourceFactory",
"(",
"ordersTypes",
",",
"ImmutableList",
".",
"of",
"(",
"0",
",",
"1",
")",
".",
"stream",
"(",
")",
".",
"map",
"(",
"ordersTypes",
"::",
"get",
")",
".",
"collect",
"(",
"toImmutableList",
"(",
")",
")",
",",
"Ints",
".",
"asList",
"(",
"0",
")",
".",
"stream",
"(",
")",
".",
"map",
"(",
"ordersTypes",
"::",
"get",
")",
".",
"collect",
"(",
"toImmutableList",
"(",
")",
")",
",",
"1",
",",
"requireNonNull",
"(",
"ImmutableMap",
".",
"of",
"(",
")",
",",
"\"layout is null\"",
")",
",",
"false",
")",
")",
";",
"HashBuilderOperatorFactory",
"hashBuilder",
"=",
"new",
"HashBuilderOperatorFactory",
"(",
"1",
",",
"new",
"PlanNodeId",
"(",
"\"test\"",
")",
",",
"lookupSourceFactoryManager",
",",
"ImmutableList",
".",
"of",
"(",
"0",
",",
"1",
")",
",",
"Ints",
".",
"asList",
"(",
"0",
")",
",",
"OptionalInt",
".",
"empty",
"(",
")",
",",
"Optional",
".",
"empty",
"(",
")",
",",
"Optional",
".",
"empty",
"(",
")",
",",
"ImmutableList",
".",
"of",
"(",
")",
",",
"1_500_000",
",",
"new",
"PagesIndex",
".",
"TestingFactory",
"(",
"false",
")",
",",
"false",
",",
"SingleStreamSpillerFactory",
".",
"unsupportedSingleStreamSpillerFactory",
"(",
")",
")",
";",
"DriverContext",
"driverContext",
"=",
"taskContext",
".",
"addPipelineContext",
"(",
"0",
",",
"false",
",",
"false",
",",
"false",
")",
".",
"addDriverContext",
"(",
")",
";",
"DriverFactory",
"buildDriverFactory",
"=",
"new",
"DriverFactory",
"(",
"0",
",",
"false",
",",
"false",
",",
"ImmutableList",
".",
"of",
"(",
"ordersTableScan",
",",
"hashBuilder",
")",
",",
"OptionalInt",
".",
"empty",
"(",
")",
",",
"UNGROUPED_EXECUTION",
")",
";",
"List",
"<",
"Type",
">",
"lineItemTypes",
"=",
"getColumnTypes",
"(",
"\"lineitem\"",
",",
"\"orderkey\"",
",",
"\"quantity\"",
")",
";",
"OperatorFactory",
"lineItemTableScan",
"=",
"createTableScanOperator",
"(",
"0",
",",
"new",
"PlanNodeId",
"(",
"\"test\"",
")",
",",
"\"lineitem\"",
",",
"\"orderkey\"",
",",
"\"quantity\"",
")",
";",
"OperatorFactory",
"joinOperator",
"=",
"LOOKUP_JOIN_OPERATORS",
".",
"innerJoin",
"(",
"1",
",",
"new",
"PlanNodeId",
"(",
"\"test\"",
")",
",",
"lookupSourceFactoryManager",
",",
"lineItemTypes",
",",
"Ints",
".",
"asList",
"(",
"0",
")",
",",
"OptionalInt",
".",
"empty",
"(",
")",
",",
"Optional",
".",
"empty",
"(",
")",
",",
"OptionalInt",
".",
"empty",
"(",
")",
",",
"unsupportedPartitioningSpillerFactory",
"(",
")",
")",
";",
"NullOutputOperatorFactory",
"output",
"=",
"new",
"NullOutputOperatorFactory",
"(",
"2",
",",
"new",
"PlanNodeId",
"(",
"\"test\"",
")",
")",
";",
"this",
".",
"probeDriverFactory",
"=",
"new",
"DriverFactory",
"(",
"1",
",",
"true",
",",
"true",
",",
"ImmutableList",
".",
"of",
"(",
"lineItemTableScan",
",",
"joinOperator",
",",
"output",
")",
",",
"OptionalInt",
".",
"empty",
"(",
")",
",",
"UNGROUPED_EXECUTION",
")",
";",
"Driver",
"driver",
"=",
"buildDriverFactory",
".",
"createDriver",
"(",
"driverContext",
")",
";",
"Future",
"<",
"LookupSourceProvider",
">",
"lookupSourceProvider",
"=",
"lookupSourceFactoryManager",
".",
"getJoinBridge",
"(",
"Lifespan",
".",
"taskWide",
"(",
")",
")",
".",
"createLookupSourceProvider",
"(",
")",
";",
"while",
"(",
"!",
"lookupSourceProvider",
".",
"isDone",
"(",
")",
")",
"{",
"driver",
".",
"process",
"(",
")",
";",
"}",
"getFutureValue",
"(",
"lookupSourceProvider",
")",
".",
"close",
"(",
")",
";",
"}",
"DriverContext",
"driverContext",
"=",
"taskContext",
".",
"addPipelineContext",
"(",
"1",
",",
"true",
",",
"true",
",",
"false",
")",
".",
"addDriverContext",
"(",
")",
";",
"Driver",
"driver",
"=",
"probeDriverFactory",
".",
"createDriver",
"(",
"driverContext",
")",
";",
"return",
"ImmutableList",
".",
"of",
"(",
"driver",
")",
";",
"}"
] |
/*
select orderkey, quantity, totalprice
from lineitem join orders using (orderkey)
|
[
"/",
"*",
"select",
"orderkey",
"quantity",
"totalprice",
"from",
"lineitem",
"join",
"orders",
"using",
"(",
"orderkey",
")"
] |
train
|
https://github.com/prestodb/presto/blob/89de5e379d8f85e139d292b0add8c537a2a01a88/presto-benchmark/src/main/java/com/facebook/presto/benchmark/HashJoinBenchmark.java#L65-L117
|
alkacon/opencms-core
|
src/org/opencms/search/CmsSearchIndex.java
|
CmsSearchIndex.createDateRangeFilter
|
protected Query createDateRangeFilter(String fieldName, long startTime, long endTime) {
"""
Creates an optimized date range filter for the date of last modification or creation.<p>
If the start date is equal to {@link Long#MIN_VALUE} and the end date is equal to {@link Long#MAX_VALUE}
than <code>null</code> is returned.<p>
@param fieldName the name of the field to search
@param startTime start time of the range to search in
@param endTime end time of the range to search in
@return an optimized date range filter for the date of last modification or creation
"""
Query filter = null;
if ((startTime != Long.MIN_VALUE) || (endTime != Long.MAX_VALUE)) {
// a date range has been set for this document search
if (startTime == Long.MIN_VALUE) {
// default start will always be "yyyy1231" in order to reduce term size
Calendar cal = Calendar.getInstance(OpenCms.getLocaleManager().getTimeZone());
cal.setTimeInMillis(endTime);
cal.set(cal.get(Calendar.YEAR) - MAX_YEAR_RANGE, 11, 31, 0, 0, 0);
startTime = cal.getTimeInMillis();
} else if (endTime == Long.MAX_VALUE) {
// default end will always be "yyyy0101" in order to reduce term size
Calendar cal = Calendar.getInstance(OpenCms.getLocaleManager().getTimeZone());
cal.setTimeInMillis(startTime);
cal.set(cal.get(Calendar.YEAR) + MAX_YEAR_RANGE, 0, 1, 0, 0, 0);
endTime = cal.getTimeInMillis();
}
// get the list of all possible date range options
List<String> dateRange = getDateRangeSpan(startTime, endTime);
List<Term> terms = new ArrayList<Term>();
for (String range : dateRange) {
terms.add(new Term(fieldName, range));
}
// create the filter for the date
BooleanQuery.Builder build = new BooleanQuery.Builder();
terms.forEach(term -> build.add(new TermQuery(term), Occur.SHOULD));
filter = build.build();
}
return filter;
}
|
java
|
protected Query createDateRangeFilter(String fieldName, long startTime, long endTime) {
Query filter = null;
if ((startTime != Long.MIN_VALUE) || (endTime != Long.MAX_VALUE)) {
// a date range has been set for this document search
if (startTime == Long.MIN_VALUE) {
// default start will always be "yyyy1231" in order to reduce term size
Calendar cal = Calendar.getInstance(OpenCms.getLocaleManager().getTimeZone());
cal.setTimeInMillis(endTime);
cal.set(cal.get(Calendar.YEAR) - MAX_YEAR_RANGE, 11, 31, 0, 0, 0);
startTime = cal.getTimeInMillis();
} else if (endTime == Long.MAX_VALUE) {
// default end will always be "yyyy0101" in order to reduce term size
Calendar cal = Calendar.getInstance(OpenCms.getLocaleManager().getTimeZone());
cal.setTimeInMillis(startTime);
cal.set(cal.get(Calendar.YEAR) + MAX_YEAR_RANGE, 0, 1, 0, 0, 0);
endTime = cal.getTimeInMillis();
}
// get the list of all possible date range options
List<String> dateRange = getDateRangeSpan(startTime, endTime);
List<Term> terms = new ArrayList<Term>();
for (String range : dateRange) {
terms.add(new Term(fieldName, range));
}
// create the filter for the date
BooleanQuery.Builder build = new BooleanQuery.Builder();
terms.forEach(term -> build.add(new TermQuery(term), Occur.SHOULD));
filter = build.build();
}
return filter;
}
|
[
"protected",
"Query",
"createDateRangeFilter",
"(",
"String",
"fieldName",
",",
"long",
"startTime",
",",
"long",
"endTime",
")",
"{",
"Query",
"filter",
"=",
"null",
";",
"if",
"(",
"(",
"startTime",
"!=",
"Long",
".",
"MIN_VALUE",
")",
"||",
"(",
"endTime",
"!=",
"Long",
".",
"MAX_VALUE",
")",
")",
"{",
"// a date range has been set for this document search",
"if",
"(",
"startTime",
"==",
"Long",
".",
"MIN_VALUE",
")",
"{",
"// default start will always be \"yyyy1231\" in order to reduce term size",
"Calendar",
"cal",
"=",
"Calendar",
".",
"getInstance",
"(",
"OpenCms",
".",
"getLocaleManager",
"(",
")",
".",
"getTimeZone",
"(",
")",
")",
";",
"cal",
".",
"setTimeInMillis",
"(",
"endTime",
")",
";",
"cal",
".",
"set",
"(",
"cal",
".",
"get",
"(",
"Calendar",
".",
"YEAR",
")",
"-",
"MAX_YEAR_RANGE",
",",
"11",
",",
"31",
",",
"0",
",",
"0",
",",
"0",
")",
";",
"startTime",
"=",
"cal",
".",
"getTimeInMillis",
"(",
")",
";",
"}",
"else",
"if",
"(",
"endTime",
"==",
"Long",
".",
"MAX_VALUE",
")",
"{",
"// default end will always be \"yyyy0101\" in order to reduce term size",
"Calendar",
"cal",
"=",
"Calendar",
".",
"getInstance",
"(",
"OpenCms",
".",
"getLocaleManager",
"(",
")",
".",
"getTimeZone",
"(",
")",
")",
";",
"cal",
".",
"setTimeInMillis",
"(",
"startTime",
")",
";",
"cal",
".",
"set",
"(",
"cal",
".",
"get",
"(",
"Calendar",
".",
"YEAR",
")",
"+",
"MAX_YEAR_RANGE",
",",
"0",
",",
"1",
",",
"0",
",",
"0",
",",
"0",
")",
";",
"endTime",
"=",
"cal",
".",
"getTimeInMillis",
"(",
")",
";",
"}",
"// get the list of all possible date range options",
"List",
"<",
"String",
">",
"dateRange",
"=",
"getDateRangeSpan",
"(",
"startTime",
",",
"endTime",
")",
";",
"List",
"<",
"Term",
">",
"terms",
"=",
"new",
"ArrayList",
"<",
"Term",
">",
"(",
")",
";",
"for",
"(",
"String",
"range",
":",
"dateRange",
")",
"{",
"terms",
".",
"add",
"(",
"new",
"Term",
"(",
"fieldName",
",",
"range",
")",
")",
";",
"}",
"// create the filter for the date",
"BooleanQuery",
".",
"Builder",
"build",
"=",
"new",
"BooleanQuery",
".",
"Builder",
"(",
")",
";",
"terms",
".",
"forEach",
"(",
"term",
"->",
"build",
".",
"add",
"(",
"new",
"TermQuery",
"(",
"term",
")",
",",
"Occur",
".",
"SHOULD",
")",
")",
";",
"filter",
"=",
"build",
".",
"build",
"(",
")",
";",
"}",
"return",
"filter",
";",
"}"
] |
Creates an optimized date range filter for the date of last modification or creation.<p>
If the start date is equal to {@link Long#MIN_VALUE} and the end date is equal to {@link Long#MAX_VALUE}
than <code>null</code> is returned.<p>
@param fieldName the name of the field to search
@param startTime start time of the range to search in
@param endTime end time of the range to search in
@return an optimized date range filter for the date of last modification or creation
|
[
"Creates",
"an",
"optimized",
"date",
"range",
"filter",
"for",
"the",
"date",
"of",
"last",
"modification",
"or",
"creation",
".",
"<p",
">"
] |
train
|
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/search/CmsSearchIndex.java#L1432-L1463
|
deephacks/confit
|
api-admin/src/main/java/org/deephacks/confit/admin/query/BeanQueryBuilder.java
|
BeanQueryBuilder.lessThan
|
public static <A extends Comparable<A>> BeanRestriction lessThan(String property, A value) {
"""
Query which asserts that a property is less than (but not equal to) a value.
@param property field to query
@param value value to query for
@return restriction to be added to {@link BeanQuery}.
"""
return new LessThan(property, value);
}
|
java
|
public static <A extends Comparable<A>> BeanRestriction lessThan(String property, A value) {
return new LessThan(property, value);
}
|
[
"public",
"static",
"<",
"A",
"extends",
"Comparable",
"<",
"A",
">",
">",
"BeanRestriction",
"lessThan",
"(",
"String",
"property",
",",
"A",
"value",
")",
"{",
"return",
"new",
"LessThan",
"(",
"property",
",",
"value",
")",
";",
"}"
] |
Query which asserts that a property is less than (but not equal to) a value.
@param property field to query
@param value value to query for
@return restriction to be added to {@link BeanQuery}.
|
[
"Query",
"which",
"asserts",
"that",
"a",
"property",
"is",
"less",
"than",
"(",
"but",
"not",
"equal",
"to",
")",
"a",
"value",
"."
] |
train
|
https://github.com/deephacks/confit/blob/4e6d4ee5fed32cbc5104433e61de1bcf1b360832/api-admin/src/main/java/org/deephacks/confit/admin/query/BeanQueryBuilder.java#L69-L72
|
moparisthebest/beehive
|
beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/scoping/ScopedServletUtils.java
|
ScopedServletUtils.getRelativeURI
|
public static final String getRelativeURI( String contextPath, String uri ) {
"""
Get a URI relative to a given webapp root.
@param contextPath the webapp context path, e.g., "/myWebapp"
@param uri the URI which should be made relative.
"""
String requestUrl = uri;
int overlap = requestUrl.indexOf( contextPath + '/' );
assert overlap != -1 : "contextPath: " + contextPath + ", uri: " + uri;
return requestUrl.substring( overlap + contextPath.length() );
}
|
java
|
public static final String getRelativeURI( String contextPath, String uri )
{
String requestUrl = uri;
int overlap = requestUrl.indexOf( contextPath + '/' );
assert overlap != -1 : "contextPath: " + contextPath + ", uri: " + uri;
return requestUrl.substring( overlap + contextPath.length() );
}
|
[
"public",
"static",
"final",
"String",
"getRelativeURI",
"(",
"String",
"contextPath",
",",
"String",
"uri",
")",
"{",
"String",
"requestUrl",
"=",
"uri",
";",
"int",
"overlap",
"=",
"requestUrl",
".",
"indexOf",
"(",
"contextPath",
"+",
"'",
"'",
")",
";",
"assert",
"overlap",
"!=",
"-",
"1",
":",
"\"contextPath: \"",
"+",
"contextPath",
"+",
"\", uri: \"",
"+",
"uri",
";",
"return",
"requestUrl",
".",
"substring",
"(",
"overlap",
"+",
"contextPath",
".",
"length",
"(",
")",
")",
";",
"}"
] |
Get a URI relative to a given webapp root.
@param contextPath the webapp context path, e.g., "/myWebapp"
@param uri the URI which should be made relative.
|
[
"Get",
"a",
"URI",
"relative",
"to",
"a",
"given",
"webapp",
"root",
"."
] |
train
|
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/scoping/ScopedServletUtils.java#L395-L401
|
brianwhu/xillium
|
core/src/main/java/org/xillium/core/ServicePlatform.java
|
ServicePlatform.contextInitialized
|
@Override
public void contextInitialized(ServletContextEvent event) {
"""
Tries to load an XML web application contenxt upon servlet context initialization. If a PlatformControl is detected
in the web application contenxt, registers it with the platform MBean server and stop. Otherwise, continues to load all
module contexts in the application.
"""
super.contextInitialized(event);
_dict.addTypeSet(org.xillium.data.validation.StandardDataTypes.class);
_packaged = _context.getResourcePaths("/WEB-INF/lib/");
_extended = discover(System.getProperty("xillium.service.ExtensionsRoot"));
// servlet mappings must be registered before this method returns
Functor<Void, ServiceModule> functor = new Functor<Void, ServiceModule>() {
public Void invoke(ServiceModule module) {
_context.getServletRegistration("dispatcher").addMapping("/" + module.simple + "/*");
return null;
}
};
ServiceModule.scan(_context, _packaged, functor, _logger);
ServiceModule.scan(_context, _extended, functor, _logger);
try {
XmlWebApplicationContext wac = new XmlWebApplicationContext();
wac.setServletContext(_context);
wac.refresh();
wac.start();
try {
// let the life cycle control take over
PlatformControl controlling = wac.getBean(CONTROLLING, PlatformControl.class);
ManagementFactory.getPlatformMBeanServer().registerMBean(
controlling.bind(this, wac, Thread.currentThread().getContextClassLoader()),
new ObjectName(controlling.getClass().getPackage().getName(), "type", controlling.getClass().getSimpleName())
);
if (controlling.isAutomatic()) {
controlling.reload();
}
} catch (BeansException x) {
// go ahead with platform realization
realize(wac, null);
} catch (Exception x) {
_logger.warning(Throwables.getFirstMessage(x));
}
} catch (BeanDefinitionStoreException x) {
_logger.warning(Throwables.getFirstMessage(x));
}
}
|
java
|
@Override
public void contextInitialized(ServletContextEvent event) {
super.contextInitialized(event);
_dict.addTypeSet(org.xillium.data.validation.StandardDataTypes.class);
_packaged = _context.getResourcePaths("/WEB-INF/lib/");
_extended = discover(System.getProperty("xillium.service.ExtensionsRoot"));
// servlet mappings must be registered before this method returns
Functor<Void, ServiceModule> functor = new Functor<Void, ServiceModule>() {
public Void invoke(ServiceModule module) {
_context.getServletRegistration("dispatcher").addMapping("/" + module.simple + "/*");
return null;
}
};
ServiceModule.scan(_context, _packaged, functor, _logger);
ServiceModule.scan(_context, _extended, functor, _logger);
try {
XmlWebApplicationContext wac = new XmlWebApplicationContext();
wac.setServletContext(_context);
wac.refresh();
wac.start();
try {
// let the life cycle control take over
PlatformControl controlling = wac.getBean(CONTROLLING, PlatformControl.class);
ManagementFactory.getPlatformMBeanServer().registerMBean(
controlling.bind(this, wac, Thread.currentThread().getContextClassLoader()),
new ObjectName(controlling.getClass().getPackage().getName(), "type", controlling.getClass().getSimpleName())
);
if (controlling.isAutomatic()) {
controlling.reload();
}
} catch (BeansException x) {
// go ahead with platform realization
realize(wac, null);
} catch (Exception x) {
_logger.warning(Throwables.getFirstMessage(x));
}
} catch (BeanDefinitionStoreException x) {
_logger.warning(Throwables.getFirstMessage(x));
}
}
|
[
"@",
"Override",
"public",
"void",
"contextInitialized",
"(",
"ServletContextEvent",
"event",
")",
"{",
"super",
".",
"contextInitialized",
"(",
"event",
")",
";",
"_dict",
".",
"addTypeSet",
"(",
"org",
".",
"xillium",
".",
"data",
".",
"validation",
".",
"StandardDataTypes",
".",
"class",
")",
";",
"_packaged",
"=",
"_context",
".",
"getResourcePaths",
"(",
"\"/WEB-INF/lib/\"",
")",
";",
"_extended",
"=",
"discover",
"(",
"System",
".",
"getProperty",
"(",
"\"xillium.service.ExtensionsRoot\"",
")",
")",
";",
"// servlet mappings must be registered before this method returns",
"Functor",
"<",
"Void",
",",
"ServiceModule",
">",
"functor",
"=",
"new",
"Functor",
"<",
"Void",
",",
"ServiceModule",
">",
"(",
")",
"{",
"public",
"Void",
"invoke",
"(",
"ServiceModule",
"module",
")",
"{",
"_context",
".",
"getServletRegistration",
"(",
"\"dispatcher\"",
")",
".",
"addMapping",
"(",
"\"/\"",
"+",
"module",
".",
"simple",
"+",
"\"/*\"",
")",
";",
"return",
"null",
";",
"}",
"}",
";",
"ServiceModule",
".",
"scan",
"(",
"_context",
",",
"_packaged",
",",
"functor",
",",
"_logger",
")",
";",
"ServiceModule",
".",
"scan",
"(",
"_context",
",",
"_extended",
",",
"functor",
",",
"_logger",
")",
";",
"try",
"{",
"XmlWebApplicationContext",
"wac",
"=",
"new",
"XmlWebApplicationContext",
"(",
")",
";",
"wac",
".",
"setServletContext",
"(",
"_context",
")",
";",
"wac",
".",
"refresh",
"(",
")",
";",
"wac",
".",
"start",
"(",
")",
";",
"try",
"{",
"// let the life cycle control take over",
"PlatformControl",
"controlling",
"=",
"wac",
".",
"getBean",
"(",
"CONTROLLING",
",",
"PlatformControl",
".",
"class",
")",
";",
"ManagementFactory",
".",
"getPlatformMBeanServer",
"(",
")",
".",
"registerMBean",
"(",
"controlling",
".",
"bind",
"(",
"this",
",",
"wac",
",",
"Thread",
".",
"currentThread",
"(",
")",
".",
"getContextClassLoader",
"(",
")",
")",
",",
"new",
"ObjectName",
"(",
"controlling",
".",
"getClass",
"(",
")",
".",
"getPackage",
"(",
")",
".",
"getName",
"(",
")",
",",
"\"type\"",
",",
"controlling",
".",
"getClass",
"(",
")",
".",
"getSimpleName",
"(",
")",
")",
")",
";",
"if",
"(",
"controlling",
".",
"isAutomatic",
"(",
")",
")",
"{",
"controlling",
".",
"reload",
"(",
")",
";",
"}",
"}",
"catch",
"(",
"BeansException",
"x",
")",
"{",
"// go ahead with platform realization",
"realize",
"(",
"wac",
",",
"null",
")",
";",
"}",
"catch",
"(",
"Exception",
"x",
")",
"{",
"_logger",
".",
"warning",
"(",
"Throwables",
".",
"getFirstMessage",
"(",
"x",
")",
")",
";",
"}",
"}",
"catch",
"(",
"BeanDefinitionStoreException",
"x",
")",
"{",
"_logger",
".",
"warning",
"(",
"Throwables",
".",
"getFirstMessage",
"(",
"x",
")",
")",
";",
"}",
"}"
] |
Tries to load an XML web application contenxt upon servlet context initialization. If a PlatformControl is detected
in the web application contenxt, registers it with the platform MBean server and stop. Otherwise, continues to load all
module contexts in the application.
|
[
"Tries",
"to",
"load",
"an",
"XML",
"web",
"application",
"contenxt",
"upon",
"servlet",
"context",
"initialization",
".",
"If",
"a",
"PlatformControl",
"is",
"detected",
"in",
"the",
"web",
"application",
"contenxt",
"registers",
"it",
"with",
"the",
"platform",
"MBean",
"server",
"and",
"stop",
".",
"Otherwise",
"continues",
"to",
"load",
"all",
"module",
"contexts",
"in",
"the",
"application",
"."
] |
train
|
https://github.com/brianwhu/xillium/blob/e8dbf8cb6589fa1031a0bfcdcb58cb03d2ba7799/core/src/main/java/org/xillium/core/ServicePlatform.java#L89-L131
|
joniles/mpxj
|
src/main/java/net/sf/mpxj/merlin/MerlinReader.java
|
MerlinReader.readFile
|
private ProjectFile readFile(File file) throws MPXJException {
"""
By the time we reach this method, we should be looking at the SQLite
database file itself.
@param file SQLite database file
@return ProjectFile instance
"""
try
{
String url = "jdbc:sqlite:" + file.getAbsolutePath();
Properties props = new Properties();
m_connection = org.sqlite.JDBC.createConnection(url, props);
m_documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
m_dayTimeIntervals = xpath.compile("/array/dayTimeInterval");
m_entityMap = new HashMap<String, Integer>();
return read();
}
catch (Exception ex)
{
throw new MPXJException(MPXJException.INVALID_FORMAT, ex);
}
finally
{
if (m_connection != null)
{
try
{
m_connection.close();
}
catch (SQLException ex)
{
// silently ignore exceptions when closing connection
}
}
m_documentBuilder = null;
m_dayTimeIntervals = null;
m_entityMap = null;
}
}
|
java
|
private ProjectFile readFile(File file) throws MPXJException
{
try
{
String url = "jdbc:sqlite:" + file.getAbsolutePath();
Properties props = new Properties();
m_connection = org.sqlite.JDBC.createConnection(url, props);
m_documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
m_dayTimeIntervals = xpath.compile("/array/dayTimeInterval");
m_entityMap = new HashMap<String, Integer>();
return read();
}
catch (Exception ex)
{
throw new MPXJException(MPXJException.INVALID_FORMAT, ex);
}
finally
{
if (m_connection != null)
{
try
{
m_connection.close();
}
catch (SQLException ex)
{
// silently ignore exceptions when closing connection
}
}
m_documentBuilder = null;
m_dayTimeIntervals = null;
m_entityMap = null;
}
}
|
[
"private",
"ProjectFile",
"readFile",
"(",
"File",
"file",
")",
"throws",
"MPXJException",
"{",
"try",
"{",
"String",
"url",
"=",
"\"jdbc:sqlite:\"",
"+",
"file",
".",
"getAbsolutePath",
"(",
")",
";",
"Properties",
"props",
"=",
"new",
"Properties",
"(",
")",
";",
"m_connection",
"=",
"org",
".",
"sqlite",
".",
"JDBC",
".",
"createConnection",
"(",
"url",
",",
"props",
")",
";",
"m_documentBuilder",
"=",
"DocumentBuilderFactory",
".",
"newInstance",
"(",
")",
".",
"newDocumentBuilder",
"(",
")",
";",
"XPathFactory",
"xPathfactory",
"=",
"XPathFactory",
".",
"newInstance",
"(",
")",
";",
"XPath",
"xpath",
"=",
"xPathfactory",
".",
"newXPath",
"(",
")",
";",
"m_dayTimeIntervals",
"=",
"xpath",
".",
"compile",
"(",
"\"/array/dayTimeInterval\"",
")",
";",
"m_entityMap",
"=",
"new",
"HashMap",
"<",
"String",
",",
"Integer",
">",
"(",
")",
";",
"return",
"read",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"ex",
")",
"{",
"throw",
"new",
"MPXJException",
"(",
"MPXJException",
".",
"INVALID_FORMAT",
",",
"ex",
")",
";",
"}",
"finally",
"{",
"if",
"(",
"m_connection",
"!=",
"null",
")",
"{",
"try",
"{",
"m_connection",
".",
"close",
"(",
")",
";",
"}",
"catch",
"(",
"SQLException",
"ex",
")",
"{",
"// silently ignore exceptions when closing connection",
"}",
"}",
"m_documentBuilder",
"=",
"null",
";",
"m_dayTimeIntervals",
"=",
"null",
";",
"m_entityMap",
"=",
"null",
";",
"}",
"}"
] |
By the time we reach this method, we should be looking at the SQLite
database file itself.
@param file SQLite database file
@return ProjectFile instance
|
[
"By",
"the",
"time",
"we",
"reach",
"this",
"method",
"we",
"should",
"be",
"looking",
"at",
"the",
"SQLite",
"database",
"file",
"itself",
"."
] |
train
|
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/merlin/MerlinReader.java#L160-L201
|
mikepenz/MaterialDrawer
|
library/src/main/java/com/mikepenz/materialdrawer/DrawerUtils.java
|
DrawerUtils.fillStickyDrawerItemFooter
|
public static void fillStickyDrawerItemFooter(DrawerBuilder drawer, ViewGroup container, View.OnClickListener onClickListener) {
"""
helper method to fill the sticky footer with it's elements
@param drawer
@param container
@param onClickListener
"""
//add all drawer items
for (IDrawerItem drawerItem : drawer.mStickyDrawerItems) {
View view = drawerItem.generateView(container.getContext(), container);
view.setTag(drawerItem);
if (drawerItem.isEnabled()) {
//UIUtils.setBackground(view, UIUtils.getSelectableBackground(container.getContext(), selected_color, drawerItem.isSelectedBackgroundAnimated()));
view.setOnClickListener(onClickListener);
}
container.addView(view);
//for android API 17 --> Padding not applied via xml
DrawerUIUtils.setDrawerVerticalPadding(view);
}
//and really. don't ask about this. it won't set the padding if i don't set the padding for the container
container.setPadding(0, 0, 0, 0);
}
|
java
|
public static void fillStickyDrawerItemFooter(DrawerBuilder drawer, ViewGroup container, View.OnClickListener onClickListener) {
//add all drawer items
for (IDrawerItem drawerItem : drawer.mStickyDrawerItems) {
View view = drawerItem.generateView(container.getContext(), container);
view.setTag(drawerItem);
if (drawerItem.isEnabled()) {
//UIUtils.setBackground(view, UIUtils.getSelectableBackground(container.getContext(), selected_color, drawerItem.isSelectedBackgroundAnimated()));
view.setOnClickListener(onClickListener);
}
container.addView(view);
//for android API 17 --> Padding not applied via xml
DrawerUIUtils.setDrawerVerticalPadding(view);
}
//and really. don't ask about this. it won't set the padding if i don't set the padding for the container
container.setPadding(0, 0, 0, 0);
}
|
[
"public",
"static",
"void",
"fillStickyDrawerItemFooter",
"(",
"DrawerBuilder",
"drawer",
",",
"ViewGroup",
"container",
",",
"View",
".",
"OnClickListener",
"onClickListener",
")",
"{",
"//add all drawer items",
"for",
"(",
"IDrawerItem",
"drawerItem",
":",
"drawer",
".",
"mStickyDrawerItems",
")",
"{",
"View",
"view",
"=",
"drawerItem",
".",
"generateView",
"(",
"container",
".",
"getContext",
"(",
")",
",",
"container",
")",
";",
"view",
".",
"setTag",
"(",
"drawerItem",
")",
";",
"if",
"(",
"drawerItem",
".",
"isEnabled",
"(",
")",
")",
"{",
"//UIUtils.setBackground(view, UIUtils.getSelectableBackground(container.getContext(), selected_color, drawerItem.isSelectedBackgroundAnimated()));",
"view",
".",
"setOnClickListener",
"(",
"onClickListener",
")",
";",
"}",
"container",
".",
"addView",
"(",
"view",
")",
";",
"//for android API 17 --> Padding not applied via xml",
"DrawerUIUtils",
".",
"setDrawerVerticalPadding",
"(",
"view",
")",
";",
"}",
"//and really. don't ask about this. it won't set the padding if i don't set the padding for the container",
"container",
".",
"setPadding",
"(",
"0",
",",
"0",
",",
"0",
",",
"0",
")",
";",
"}"
] |
helper method to fill the sticky footer with it's elements
@param drawer
@param container
@param onClickListener
|
[
"helper",
"method",
"to",
"fill",
"the",
"sticky",
"footer",
"with",
"it",
"s",
"elements"
] |
train
|
https://github.com/mikepenz/MaterialDrawer/blob/f4fb31635767edead0a01cee7b7588942b89d8d9/library/src/main/java/com/mikepenz/materialdrawer/DrawerUtils.java#L397-L415
|
linkedin/dexmaker
|
dexmaker/src/main/java/com/android/dx/stock/ProxyBuilder.java
|
ProxyBuilder.dexCache
|
public ProxyBuilder<T> dexCache(File dexCacheParent) {
"""
Sets the directory where executable code is stored. See {@link
DexMaker#generateAndLoad DexMaker.generateAndLoad()} for guidance on
choosing a secure location for the dex cache.
"""
dexCache = new File(dexCacheParent, "v" + Integer.toString(VERSION));
dexCache.mkdir();
return this;
}
|
java
|
public ProxyBuilder<T> dexCache(File dexCacheParent) {
dexCache = new File(dexCacheParent, "v" + Integer.toString(VERSION));
dexCache.mkdir();
return this;
}
|
[
"public",
"ProxyBuilder",
"<",
"T",
">",
"dexCache",
"(",
"File",
"dexCacheParent",
")",
"{",
"dexCache",
"=",
"new",
"File",
"(",
"dexCacheParent",
",",
"\"v\"",
"+",
"Integer",
".",
"toString",
"(",
"VERSION",
")",
")",
";",
"dexCache",
".",
"mkdir",
"(",
")",
";",
"return",
"this",
";",
"}"
] |
Sets the directory where executable code is stored. See {@link
DexMaker#generateAndLoad DexMaker.generateAndLoad()} for guidance on
choosing a secure location for the dex cache.
|
[
"Sets",
"the",
"directory",
"where",
"executable",
"code",
"is",
"stored",
".",
"See",
"{"
] |
train
|
https://github.com/linkedin/dexmaker/blob/c58ffebcbb2564c7d1fa6fb58b48f351c330296d/dexmaker/src/main/java/com/android/dx/stock/ProxyBuilder.java#L177-L181
|
brettwooldridge/NuProcess
|
src/main/java/com/zaxxer/nuprocess/codec/NuAbstractCharsetHandler.java
|
NuAbstractCharsetHandler.onStderrChars
|
protected void onStderrChars(CharBuffer buffer, boolean closed, CoderResult coderResult) {
"""
Override this to receive decoded Unicode Java string data read from
stderr.
<p>
Make sure to set the {@link CharBuffer#position() position} of
{@code buffer} to indicate how much data you have read before returning.
@param buffer The {@link CharBuffer} receiving Unicode string data.
"""
// Consume the entire buffer by default.
buffer.position(buffer.limit());
}
|
java
|
protected void onStderrChars(CharBuffer buffer, boolean closed, CoderResult coderResult)
{
// Consume the entire buffer by default.
buffer.position(buffer.limit());
}
|
[
"protected",
"void",
"onStderrChars",
"(",
"CharBuffer",
"buffer",
",",
"boolean",
"closed",
",",
"CoderResult",
"coderResult",
")",
"{",
"// Consume the entire buffer by default.",
"buffer",
".",
"position",
"(",
"buffer",
".",
"limit",
"(",
")",
")",
";",
"}"
] |
Override this to receive decoded Unicode Java string data read from
stderr.
<p>
Make sure to set the {@link CharBuffer#position() position} of
{@code buffer} to indicate how much data you have read before returning.
@param buffer The {@link CharBuffer} receiving Unicode string data.
|
[
"Override",
"this",
"to",
"receive",
"decoded",
"Unicode",
"Java",
"string",
"data",
"read",
"from",
"stderr",
".",
"<p",
">",
"Make",
"sure",
"to",
"set",
"the",
"{",
"@link",
"CharBuffer#position",
"()",
"position",
"}",
"of",
"{",
"@code",
"buffer",
"}",
"to",
"indicate",
"how",
"much",
"data",
"you",
"have",
"read",
"before",
"returning",
"."
] |
train
|
https://github.com/brettwooldridge/NuProcess/blob/d4abdd195367fce7375a0b45cb2f5eeff1c74d03/src/main/java/com/zaxxer/nuprocess/codec/NuAbstractCharsetHandler.java#L164-L168
|
overturetool/overture
|
core/interpreter/src/main/java/org/overture/interpreter/runtime/Interpreter.java
|
Interpreter.setTracepoint
|
public Breakpoint setTracepoint(PStm stmt, String trace) throws Exception {
"""
Set a statement tracepoint. A tracepoint does not stop execution, but evaluates and displays an expression before
continuing.
@param stmt
The statement to trace.
@param trace
The expression to evaluate.
@return The Breakpoint object created.
@throws Exception
Expression is not valid.
"""
BreakpointManager.setBreakpoint(stmt, new Tracepoint(stmt.getLocation(), ++nextbreakpoint, trace));
breakpoints.put(nextbreakpoint, BreakpointManager.getBreakpoint(stmt));
return BreakpointManager.getBreakpoint(stmt);
}
|
java
|
public Breakpoint setTracepoint(PStm stmt, String trace) throws Exception
{
BreakpointManager.setBreakpoint(stmt, new Tracepoint(stmt.getLocation(), ++nextbreakpoint, trace));
breakpoints.put(nextbreakpoint, BreakpointManager.getBreakpoint(stmt));
return BreakpointManager.getBreakpoint(stmt);
}
|
[
"public",
"Breakpoint",
"setTracepoint",
"(",
"PStm",
"stmt",
",",
"String",
"trace",
")",
"throws",
"Exception",
"{",
"BreakpointManager",
".",
"setBreakpoint",
"(",
"stmt",
",",
"new",
"Tracepoint",
"(",
"stmt",
".",
"getLocation",
"(",
")",
",",
"++",
"nextbreakpoint",
",",
"trace",
")",
")",
";",
"breakpoints",
".",
"put",
"(",
"nextbreakpoint",
",",
"BreakpointManager",
".",
"getBreakpoint",
"(",
"stmt",
")",
")",
";",
"return",
"BreakpointManager",
".",
"getBreakpoint",
"(",
"stmt",
")",
";",
"}"
] |
Set a statement tracepoint. A tracepoint does not stop execution, but evaluates and displays an expression before
continuing.
@param stmt
The statement to trace.
@param trace
The expression to evaluate.
@return The Breakpoint object created.
@throws Exception
Expression is not valid.
|
[
"Set",
"a",
"statement",
"tracepoint",
".",
"A",
"tracepoint",
"does",
"not",
"stop",
"execution",
"but",
"evaluates",
"and",
"displays",
"an",
"expression",
"before",
"continuing",
"."
] |
train
|
https://github.com/overturetool/overture/blob/83175dc6c24fa171cde4fcf61ecb648eba3bdbc1/core/interpreter/src/main/java/org/overture/interpreter/runtime/Interpreter.java#L427-L432
|
googleads/googleads-java-lib
|
examples/admanager_axis/src/main/java/admanager/axis/v201902/inventoryservice/GetAdUnitHierarchy.java
|
GetAdUnitHierarchy.runExample
|
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session)
throws RemoteException {
"""
Runs the example.
@param adManagerServices the services factory.
@param session the session.
@throws ApiException if the API request failed with one or more service errors.
@throws RemoteException if the API request failed due to other errors.
"""
// Get the InventoryService.
InventoryServiceInterface inventoryService =
adManagerServices.get(session, InventoryServiceInterface.class);
// Get the NetworkService.
NetworkServiceInterface networkService =
adManagerServices.get(session, NetworkServiceInterface.class);
// Get the effective root ad unit.
String rootAdUnitId = networkService.getCurrentNetwork().getEffectiveRootAdUnitId();
// Create a statement to select only the root ad unit by ID.
StatementBuilder statementBuilder =
new StatementBuilder()
.where("id = :id")
.orderBy("id ASC")
.limit(1)
.withBindVariableValue("id", rootAdUnitId);
AdUnitPage page = inventoryService.getAdUnitsByStatement(statementBuilder.toStatement());
AdUnit effectiveRootAdUnit = Iterables.getOnlyElement(Arrays.asList(page.getResults()));
// Get all ad units.
List<AdUnit> adUnits = getAllAdUnits(adManagerServices, session);
buildAndDisplayAdUnitTree(effectiveRootAdUnit, adUnits);
}
|
java
|
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session)
throws RemoteException {
// Get the InventoryService.
InventoryServiceInterface inventoryService =
adManagerServices.get(session, InventoryServiceInterface.class);
// Get the NetworkService.
NetworkServiceInterface networkService =
adManagerServices.get(session, NetworkServiceInterface.class);
// Get the effective root ad unit.
String rootAdUnitId = networkService.getCurrentNetwork().getEffectiveRootAdUnitId();
// Create a statement to select only the root ad unit by ID.
StatementBuilder statementBuilder =
new StatementBuilder()
.where("id = :id")
.orderBy("id ASC")
.limit(1)
.withBindVariableValue("id", rootAdUnitId);
AdUnitPage page = inventoryService.getAdUnitsByStatement(statementBuilder.toStatement());
AdUnit effectiveRootAdUnit = Iterables.getOnlyElement(Arrays.asList(page.getResults()));
// Get all ad units.
List<AdUnit> adUnits = getAllAdUnits(adManagerServices, session);
buildAndDisplayAdUnitTree(effectiveRootAdUnit, adUnits);
}
|
[
"public",
"static",
"void",
"runExample",
"(",
"AdManagerServices",
"adManagerServices",
",",
"AdManagerSession",
"session",
")",
"throws",
"RemoteException",
"{",
"// Get the InventoryService.",
"InventoryServiceInterface",
"inventoryService",
"=",
"adManagerServices",
".",
"get",
"(",
"session",
",",
"InventoryServiceInterface",
".",
"class",
")",
";",
"// Get the NetworkService.",
"NetworkServiceInterface",
"networkService",
"=",
"adManagerServices",
".",
"get",
"(",
"session",
",",
"NetworkServiceInterface",
".",
"class",
")",
";",
"// Get the effective root ad unit.",
"String",
"rootAdUnitId",
"=",
"networkService",
".",
"getCurrentNetwork",
"(",
")",
".",
"getEffectiveRootAdUnitId",
"(",
")",
";",
"// Create a statement to select only the root ad unit by ID.",
"StatementBuilder",
"statementBuilder",
"=",
"new",
"StatementBuilder",
"(",
")",
".",
"where",
"(",
"\"id = :id\"",
")",
".",
"orderBy",
"(",
"\"id ASC\"",
")",
".",
"limit",
"(",
"1",
")",
".",
"withBindVariableValue",
"(",
"\"id\"",
",",
"rootAdUnitId",
")",
";",
"AdUnitPage",
"page",
"=",
"inventoryService",
".",
"getAdUnitsByStatement",
"(",
"statementBuilder",
".",
"toStatement",
"(",
")",
")",
";",
"AdUnit",
"effectiveRootAdUnit",
"=",
"Iterables",
".",
"getOnlyElement",
"(",
"Arrays",
".",
"asList",
"(",
"page",
".",
"getResults",
"(",
")",
")",
")",
";",
"// Get all ad units.",
"List",
"<",
"AdUnit",
">",
"adUnits",
"=",
"getAllAdUnits",
"(",
"adManagerServices",
",",
"session",
")",
";",
"buildAndDisplayAdUnitTree",
"(",
"effectiveRootAdUnit",
",",
"adUnits",
")",
";",
"}"
] |
Runs the example.
@param adManagerServices the services factory.
@param session the session.
@throws ApiException if the API request failed with one or more service errors.
@throws RemoteException if the API request failed due to other errors.
|
[
"Runs",
"the",
"example",
"."
] |
train
|
https://github.com/googleads/googleads-java-lib/blob/967957cc4f6076514e3a7926fe653e4f1f7cc9c9/examples/admanager_axis/src/main/java/admanager/axis/v201902/inventoryservice/GetAdUnitHierarchy.java#L60-L89
|
Waikato/moa
|
moa/src/main/java/moa/classifiers/meta/ADACC.java
|
ADACC.computeKappa
|
private double computeKappa(int[] y1,int[] y2) {
"""
Returns the kappa statistics,
a statistical measure of agreement in the predictions
of 2 classifiers. Used as a measure of diversity of predictive
models: the higher the kappa value, the smaller the diversity
@param y1 the predictions of classifier A
@param y2 the predictions of classifier B
@return the kappa measure
"""
int m=y1.length;
double theta1=0;
double counts[][]=new double[2][this.modelContext.numClasses()];
for (int i=0;i<m;i++){
if (y1[i]==y2[i])
theta1=theta1+1;
counts[0][y1[i]]=counts[0][y1[i]]+1;
counts[1][y2[i]]=counts[1][y2[i]]+1;
}
theta1=theta1/m;
double theta2=0;
for(int i=0;i<this.modelContext.numClasses();i++)
theta2+=counts[0][i]/m*counts[1][i]/m;
if (theta1==theta2 && theta2==1)
return 1;
return (theta1-theta2)/(1-theta2);
}
|
java
|
private double computeKappa(int[] y1,int[] y2){
int m=y1.length;
double theta1=0;
double counts[][]=new double[2][this.modelContext.numClasses()];
for (int i=0;i<m;i++){
if (y1[i]==y2[i])
theta1=theta1+1;
counts[0][y1[i]]=counts[0][y1[i]]+1;
counts[1][y2[i]]=counts[1][y2[i]]+1;
}
theta1=theta1/m;
double theta2=0;
for(int i=0;i<this.modelContext.numClasses();i++)
theta2+=counts[0][i]/m*counts[1][i]/m;
if (theta1==theta2 && theta2==1)
return 1;
return (theta1-theta2)/(1-theta2);
}
|
[
"private",
"double",
"computeKappa",
"(",
"int",
"[",
"]",
"y1",
",",
"int",
"[",
"]",
"y2",
")",
"{",
"int",
"m",
"=",
"y1",
".",
"length",
";",
"double",
"theta1",
"=",
"0",
";",
"double",
"counts",
"[",
"]",
"[",
"]",
"=",
"new",
"double",
"[",
"2",
"]",
"[",
"this",
".",
"modelContext",
".",
"numClasses",
"(",
")",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"m",
";",
"i",
"++",
")",
"{",
"if",
"(",
"y1",
"[",
"i",
"]",
"==",
"y2",
"[",
"i",
"]",
")",
"theta1",
"=",
"theta1",
"+",
"1",
";",
"counts",
"[",
"0",
"]",
"[",
"y1",
"[",
"i",
"]",
"]",
"=",
"counts",
"[",
"0",
"]",
"[",
"y1",
"[",
"i",
"]",
"]",
"+",
"1",
";",
"counts",
"[",
"1",
"]",
"[",
"y2",
"[",
"i",
"]",
"]",
"=",
"counts",
"[",
"1",
"]",
"[",
"y2",
"[",
"i",
"]",
"]",
"+",
"1",
";",
"}",
"theta1",
"=",
"theta1",
"/",
"m",
";",
"double",
"theta2",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"this",
".",
"modelContext",
".",
"numClasses",
"(",
")",
";",
"i",
"++",
")",
"theta2",
"+=",
"counts",
"[",
"0",
"]",
"[",
"i",
"]",
"/",
"m",
"*",
"counts",
"[",
"1",
"]",
"[",
"i",
"]",
"/",
"m",
";",
"if",
"(",
"theta1",
"==",
"theta2",
"&&",
"theta2",
"==",
"1",
")",
"return",
"1",
";",
"return",
"(",
"theta1",
"-",
"theta2",
")",
"/",
"(",
"1",
"-",
"theta2",
")",
";",
"}"
] |
Returns the kappa statistics,
a statistical measure of agreement in the predictions
of 2 classifiers. Used as a measure of diversity of predictive
models: the higher the kappa value, the smaller the diversity
@param y1 the predictions of classifier A
@param y2 the predictions of classifier B
@return the kappa measure
|
[
"Returns",
"the",
"kappa",
"statistics",
"a",
"statistical",
"measure",
"of",
"agreement",
"in",
"the",
"predictions",
"of",
"2",
"classifiers",
".",
"Used",
"as",
"a",
"measure",
"of",
"diversity",
"of",
"predictive",
"models",
":",
"the",
"higher",
"the",
"kappa",
"value",
"the",
"smaller",
"the",
"diversity"
] |
train
|
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/classifiers/meta/ADACC.java#L179-L207
|
OpenBEL/openbel-framework
|
org.openbel.framework.common/src/main/java/org/openbel/framework/common/BELUtilities.java
|
BELUtilities.asPath
|
public static String asPath(final String directory, final String filename) {
"""
Inserts the platform-specific filesystem path separator between
{@code directory} and {@code filename} and returns the resulting string.
@param directory Non-null string
@param filename Non-null string
@return String following the format
{@code directory<path_separator>filename}
"""
return directory.concat(separator).concat(filename);
}
|
java
|
public static String asPath(final String directory, final String filename) {
return directory.concat(separator).concat(filename);
}
|
[
"public",
"static",
"String",
"asPath",
"(",
"final",
"String",
"directory",
",",
"final",
"String",
"filename",
")",
"{",
"return",
"directory",
".",
"concat",
"(",
"separator",
")",
".",
"concat",
"(",
"filename",
")",
";",
"}"
] |
Inserts the platform-specific filesystem path separator between
{@code directory} and {@code filename} and returns the resulting string.
@param directory Non-null string
@param filename Non-null string
@return String following the format
{@code directory<path_separator>filename}
|
[
"Inserts",
"the",
"platform",
"-",
"specific",
"filesystem",
"path",
"separator",
"between",
"{",
"@code",
"directory",
"}",
"and",
"{",
"@code",
"filename",
"}",
"and",
"returns",
"the",
"resulting",
"string",
"."
] |
train
|
https://github.com/OpenBEL/openbel-framework/blob/149f80b1d6eabb15ab15815b6f745b0afa9fd2d3/org.openbel.framework.common/src/main/java/org/openbel/framework/common/BELUtilities.java#L155-L157
|
rvs-fluid-it/mvn-fluid-cd
|
mvn-ext-freeze/src/main/java/be/fluid_it/mvn/cd/x/freeze/replace/FreezeHandler.java
|
FreezeHandler.getName
|
private String getName(String s1, String s2) {
"""
If the first String parameter is nonempty, return it,
else return the second string parameter.
@param s1 The string to be tested.
@param s2 The alternate String.
@return s1 if it isn't empty, else s2.
"""
if (s1 == null || "".equals(s1)) return s2;
else return s1;
}
|
java
|
private String getName(String s1, String s2) {
if (s1 == null || "".equals(s1)) return s2;
else return s1;
}
|
[
"private",
"String",
"getName",
"(",
"String",
"s1",
",",
"String",
"s2",
")",
"{",
"if",
"(",
"s1",
"==",
"null",
"||",
"\"\"",
".",
"equals",
"(",
"s1",
")",
")",
"return",
"s2",
";",
"else",
"return",
"s1",
";",
"}"
] |
If the first String parameter is nonempty, return it,
else return the second string parameter.
@param s1 The string to be tested.
@param s2 The alternate String.
@return s1 if it isn't empty, else s2.
|
[
"If",
"the",
"first",
"String",
"parameter",
"is",
"nonempty",
"return",
"it",
"else",
"return",
"the",
"second",
"string",
"parameter",
"."
] |
train
|
https://github.com/rvs-fluid-it/mvn-fluid-cd/blob/2aad8ed1cb40f94bd24bad7e6a127956cc277077/mvn-ext-freeze/src/main/java/be/fluid_it/mvn/cd/x/freeze/replace/FreezeHandler.java#L261-L264
|
spotbugs/spotbugs
|
eclipsePlugin/src/de/tobject/findbugs/actions/LoadXmlAction.java
|
LoadXmlAction.work
|
private void work(final IProject project, final String fileName) {
"""
Run a FindBugs import on the given project, displaying a progress
monitor.
@param project
The resource to load XMl to.
"""
FindBugsJob runFindBugs = new FindBugsJob("Loading XML data from " + fileName + "...", project) {
@Override
protected void runWithProgress(IProgressMonitor monitor) throws CoreException {
FindBugsWorker worker = new FindBugsWorker(project, monitor);
worker.loadXml(fileName);
}
};
runFindBugs.setRule(project);
runFindBugs.scheduleInteractive();
}
|
java
|
private void work(final IProject project, final String fileName) {
FindBugsJob runFindBugs = new FindBugsJob("Loading XML data from " + fileName + "...", project) {
@Override
protected void runWithProgress(IProgressMonitor monitor) throws CoreException {
FindBugsWorker worker = new FindBugsWorker(project, monitor);
worker.loadXml(fileName);
}
};
runFindBugs.setRule(project);
runFindBugs.scheduleInteractive();
}
|
[
"private",
"void",
"work",
"(",
"final",
"IProject",
"project",
",",
"final",
"String",
"fileName",
")",
"{",
"FindBugsJob",
"runFindBugs",
"=",
"new",
"FindBugsJob",
"(",
"\"Loading XML data from \"",
"+",
"fileName",
"+",
"\"...\"",
",",
"project",
")",
"{",
"@",
"Override",
"protected",
"void",
"runWithProgress",
"(",
"IProgressMonitor",
"monitor",
")",
"throws",
"CoreException",
"{",
"FindBugsWorker",
"worker",
"=",
"new",
"FindBugsWorker",
"(",
"project",
",",
"monitor",
")",
";",
"worker",
".",
"loadXml",
"(",
"fileName",
")",
";",
"}",
"}",
";",
"runFindBugs",
".",
"setRule",
"(",
"project",
")",
";",
"runFindBugs",
".",
"scheduleInteractive",
"(",
")",
";",
"}"
] |
Run a FindBugs import on the given project, displaying a progress
monitor.
@param project
The resource to load XMl to.
|
[
"Run",
"a",
"FindBugs",
"import",
"on",
"the",
"given",
"project",
"displaying",
"a",
"progress",
"monitor",
"."
] |
train
|
https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/eclipsePlugin/src/de/tobject/findbugs/actions/LoadXmlAction.java#L115-L125
|
cdk/cdk
|
tool/formula/src/main/java/org/openscience/cdk/formula/IsotopePatternSimilarity.java
|
IsotopePatternSimilarity.getClosestDataDiff
|
private int getClosestDataDiff(IsotopeContainer isoContainer, IsotopePattern pattern) {
"""
Search and find the closest difference in an array in terms of mass and
intensity. Always return the position in this List.
@param diffValue The difference to look for
@param normMass A List of normalized masses
@return The position in the List
"""
double diff = 100;
int posi = -1;
for (int i = 0; i < pattern.getNumberOfIsotopes(); i++) {
double tempDiff = Math.abs((isoContainer.getMass()) - pattern.getIsotopes().get(i).getMass());
if (tempDiff <= (tolerance_ppm / isoContainer.getMass()) && tempDiff < diff) {
diff = tempDiff;
posi = i;
}
}
return posi;
}
|
java
|
private int getClosestDataDiff(IsotopeContainer isoContainer, IsotopePattern pattern) {
double diff = 100;
int posi = -1;
for (int i = 0; i < pattern.getNumberOfIsotopes(); i++) {
double tempDiff = Math.abs((isoContainer.getMass()) - pattern.getIsotopes().get(i).getMass());
if (tempDiff <= (tolerance_ppm / isoContainer.getMass()) && tempDiff < diff) {
diff = tempDiff;
posi = i;
}
}
return posi;
}
|
[
"private",
"int",
"getClosestDataDiff",
"(",
"IsotopeContainer",
"isoContainer",
",",
"IsotopePattern",
"pattern",
")",
"{",
"double",
"diff",
"=",
"100",
";",
"int",
"posi",
"=",
"-",
"1",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"pattern",
".",
"getNumberOfIsotopes",
"(",
")",
";",
"i",
"++",
")",
"{",
"double",
"tempDiff",
"=",
"Math",
".",
"abs",
"(",
"(",
"isoContainer",
".",
"getMass",
"(",
")",
")",
"-",
"pattern",
".",
"getIsotopes",
"(",
")",
".",
"get",
"(",
"i",
")",
".",
"getMass",
"(",
")",
")",
";",
"if",
"(",
"tempDiff",
"<=",
"(",
"tolerance_ppm",
"/",
"isoContainer",
".",
"getMass",
"(",
")",
")",
"&&",
"tempDiff",
"<",
"diff",
")",
"{",
"diff",
"=",
"tempDiff",
";",
"posi",
"=",
"i",
";",
"}",
"}",
"return",
"posi",
";",
"}"
] |
Search and find the closest difference in an array in terms of mass and
intensity. Always return the position in this List.
@param diffValue The difference to look for
@param normMass A List of normalized masses
@return The position in the List
|
[
"Search",
"and",
"find",
"the",
"closest",
"difference",
"in",
"an",
"array",
"in",
"terms",
"of",
"mass",
"and",
"intensity",
".",
"Always",
"return",
"the",
"position",
"in",
"this",
"List",
"."
] |
train
|
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/tool/formula/src/main/java/org/openscience/cdk/formula/IsotopePatternSimilarity.java#L111-L123
|
square/spoon
|
spoon-runner/src/main/java/com/squareup/spoon/html/HtmlUtils.java
|
HtmlUtils.createRelativeUri
|
static String createRelativeUri(File file, File output) {
"""
Get a relative URI for {@code file} from {@code output} folder.
"""
if (file == null) {
return null;
}
try {
file = file.getCanonicalFile();
output = output.getCanonicalFile();
if (file.equals(output)) {
throw new IllegalArgumentException("File path and output folder are the same.");
}
StringBuilder builder = new StringBuilder();
while (!file.equals(output)) {
if (builder.length() > 0) {
builder.insert(0, "/");
}
builder.insert(0, file.getName());
file = file.getParentFile().getCanonicalFile();
}
return builder.toString();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
|
java
|
static String createRelativeUri(File file, File output) {
if (file == null) {
return null;
}
try {
file = file.getCanonicalFile();
output = output.getCanonicalFile();
if (file.equals(output)) {
throw new IllegalArgumentException("File path and output folder are the same.");
}
StringBuilder builder = new StringBuilder();
while (!file.equals(output)) {
if (builder.length() > 0) {
builder.insert(0, "/");
}
builder.insert(0, file.getName());
file = file.getParentFile().getCanonicalFile();
}
return builder.toString();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
|
[
"static",
"String",
"createRelativeUri",
"(",
"File",
"file",
",",
"File",
"output",
")",
"{",
"if",
"(",
"file",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"try",
"{",
"file",
"=",
"file",
".",
"getCanonicalFile",
"(",
")",
";",
"output",
"=",
"output",
".",
"getCanonicalFile",
"(",
")",
";",
"if",
"(",
"file",
".",
"equals",
"(",
"output",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"File path and output folder are the same.\"",
")",
";",
"}",
"StringBuilder",
"builder",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"while",
"(",
"!",
"file",
".",
"equals",
"(",
"output",
")",
")",
"{",
"if",
"(",
"builder",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"builder",
".",
"insert",
"(",
"0",
",",
"\"/\"",
")",
";",
"}",
"builder",
".",
"insert",
"(",
"0",
",",
"file",
".",
"getName",
"(",
")",
")",
";",
"file",
"=",
"file",
".",
"getParentFile",
"(",
")",
".",
"getCanonicalFile",
"(",
")",
";",
"}",
"return",
"builder",
".",
"toString",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"}"
] |
Get a relative URI for {@code file} from {@code output} folder.
|
[
"Get",
"a",
"relative",
"URI",
"for",
"{"
] |
train
|
https://github.com/square/spoon/blob/ebd51fbc1498f6bdcb61aa1281bbac2af99117b3/spoon-runner/src/main/java/com/squareup/spoon/html/HtmlUtils.java#L99-L121
|
mojohaus/aspectj-maven-plugin
|
src/main/java/org/codehaus/mojo/aspectj/AjcHelper.java
|
AjcHelper.writeBuildConfigToFile
|
public static void writeBuildConfigToFile( List<String> arguments, String fileName, File outputDir )
throws IOException {
"""
Creates a file that can be used as input to the ajc compiler using the -argdfile flag.
Each line in these files should contain one option or filename.
Comments, as in Java, start with // and extend to the end of the line.
@param arguments All arguments passed to ajc in this run
@param fileName the filename of the argfile
@param outputDir the build output area.
@throws IOException
"""
FileUtils.forceMkdir( outputDir );
File argFile = new File( outputDir, fileName );
argFile.getParentFile().mkdirs();
argFile.createNewFile();
BufferedWriter writer = new BufferedWriter( new FileWriter( argFile ) );
for ( String argument : arguments )
{
writer.write( argument );
writer.newLine();
}
writer.flush();
writer.close();
}
|
java
|
public static void writeBuildConfigToFile( List<String> arguments, String fileName, File outputDir )
throws IOException
{
FileUtils.forceMkdir( outputDir );
File argFile = new File( outputDir, fileName );
argFile.getParentFile().mkdirs();
argFile.createNewFile();
BufferedWriter writer = new BufferedWriter( new FileWriter( argFile ) );
for ( String argument : arguments )
{
writer.write( argument );
writer.newLine();
}
writer.flush();
writer.close();
}
|
[
"public",
"static",
"void",
"writeBuildConfigToFile",
"(",
"List",
"<",
"String",
">",
"arguments",
",",
"String",
"fileName",
",",
"File",
"outputDir",
")",
"throws",
"IOException",
"{",
"FileUtils",
".",
"forceMkdir",
"(",
"outputDir",
")",
";",
"File",
"argFile",
"=",
"new",
"File",
"(",
"outputDir",
",",
"fileName",
")",
";",
"argFile",
".",
"getParentFile",
"(",
")",
".",
"mkdirs",
"(",
")",
";",
"argFile",
".",
"createNewFile",
"(",
")",
";",
"BufferedWriter",
"writer",
"=",
"new",
"BufferedWriter",
"(",
"new",
"FileWriter",
"(",
"argFile",
")",
")",
";",
"for",
"(",
"String",
"argument",
":",
"arguments",
")",
"{",
"writer",
".",
"write",
"(",
"argument",
")",
";",
"writer",
".",
"newLine",
"(",
")",
";",
"}",
"writer",
".",
"flush",
"(",
")",
";",
"writer",
".",
"close",
"(",
")",
";",
"}"
] |
Creates a file that can be used as input to the ajc compiler using the -argdfile flag.
Each line in these files should contain one option or filename.
Comments, as in Java, start with // and extend to the end of the line.
@param arguments All arguments passed to ajc in this run
@param fileName the filename of the argfile
@param outputDir the build output area.
@throws IOException
|
[
"Creates",
"a",
"file",
"that",
"can",
"be",
"used",
"as",
"input",
"to",
"the",
"ajc",
"compiler",
"using",
"the",
"-",
"argdfile",
"flag",
".",
"Each",
"line",
"in",
"these",
"files",
"should",
"contain",
"one",
"option",
"or",
"filename",
".",
"Comments",
"as",
"in",
"Java",
"start",
"with",
"//",
"and",
"extend",
"to",
"the",
"end",
"of",
"the",
"line",
"."
] |
train
|
https://github.com/mojohaus/aspectj-maven-plugin/blob/120ee1ce08b93873931035ed98cd70e3ccceeefb/src/main/java/org/codehaus/mojo/aspectj/AjcHelper.java#L239-L254
|
ixa-ehu/kaflib
|
src/main/java/ixa/kaflib/KAFDocument.java
|
KAFDocument.newChunk
|
public Chunk newChunk(String phrase, Span<Term> span) {
"""
Creates a new chunk. It assigns an appropriate ID to it. The Chunk is added to the document object.
@param head the chunk head.
@param phrase type of the phrase.
@param terms the list of the terms in the chunk.
@return a new chunk.
"""
String newId = idManager.getNextId(AnnotationType.CHUNK);
Chunk newChunk = new Chunk(newId, span);
newChunk.setPhrase(phrase);
annotationContainer.add(newChunk, Layer.CHUNKS, AnnotationType.CHUNK);
return newChunk;
}
|
java
|
public Chunk newChunk(String phrase, Span<Term> span) {
String newId = idManager.getNextId(AnnotationType.CHUNK);
Chunk newChunk = new Chunk(newId, span);
newChunk.setPhrase(phrase);
annotationContainer.add(newChunk, Layer.CHUNKS, AnnotationType.CHUNK);
return newChunk;
}
|
[
"public",
"Chunk",
"newChunk",
"(",
"String",
"phrase",
",",
"Span",
"<",
"Term",
">",
"span",
")",
"{",
"String",
"newId",
"=",
"idManager",
".",
"getNextId",
"(",
"AnnotationType",
".",
"CHUNK",
")",
";",
"Chunk",
"newChunk",
"=",
"new",
"Chunk",
"(",
"newId",
",",
"span",
")",
";",
"newChunk",
".",
"setPhrase",
"(",
"phrase",
")",
";",
"annotationContainer",
".",
"add",
"(",
"newChunk",
",",
"Layer",
".",
"CHUNKS",
",",
"AnnotationType",
".",
"CHUNK",
")",
";",
"return",
"newChunk",
";",
"}"
] |
Creates a new chunk. It assigns an appropriate ID to it. The Chunk is added to the document object.
@param head the chunk head.
@param phrase type of the phrase.
@param terms the list of the terms in the chunk.
@return a new chunk.
|
[
"Creates",
"a",
"new",
"chunk",
".",
"It",
"assigns",
"an",
"appropriate",
"ID",
"to",
"it",
".",
"The",
"Chunk",
"is",
"added",
"to",
"the",
"document",
"object",
"."
] |
train
|
https://github.com/ixa-ehu/kaflib/blob/3921f55d9ae4621736a329418f6334fb721834b8/src/main/java/ixa/kaflib/KAFDocument.java#L718-L724
|
matthewhorridge/owlapi-gwt
|
owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLAnnotationAssertionAxiomImpl_CustomFieldSerializer.java
|
OWLAnnotationAssertionAxiomImpl_CustomFieldSerializer.deserializeInstance
|
@Override
public void deserializeInstance(SerializationStreamReader streamReader, OWLAnnotationAssertionAxiomImpl instance) throws SerializationException {
"""
Deserializes the content of the object from the
{@link com.google.gwt.user.client.rpc.SerializationStreamReader}.
@param streamReader the {@link com.google.gwt.user.client.rpc.SerializationStreamReader} to read the
object's content from
@param instance the object instance to deserialize
@throws com.google.gwt.user.client.rpc.SerializationException
if the deserialization operation is not
successful
"""
deserialize(streamReader, instance);
}
|
java
|
@Override
public void deserializeInstance(SerializationStreamReader streamReader, OWLAnnotationAssertionAxiomImpl instance) throws SerializationException {
deserialize(streamReader, instance);
}
|
[
"@",
"Override",
"public",
"void",
"deserializeInstance",
"(",
"SerializationStreamReader",
"streamReader",
",",
"OWLAnnotationAssertionAxiomImpl",
"instance",
")",
"throws",
"SerializationException",
"{",
"deserialize",
"(",
"streamReader",
",",
"instance",
")",
";",
"}"
] |
Deserializes the content of the object from the
{@link com.google.gwt.user.client.rpc.SerializationStreamReader}.
@param streamReader the {@link com.google.gwt.user.client.rpc.SerializationStreamReader} to read the
object's content from
@param instance the object instance to deserialize
@throws com.google.gwt.user.client.rpc.SerializationException
if the deserialization operation is not
successful
|
[
"Deserializes",
"the",
"content",
"of",
"the",
"object",
"from",
"the",
"{",
"@link",
"com",
".",
"google",
".",
"gwt",
".",
"user",
".",
"client",
".",
"rpc",
".",
"SerializationStreamReader",
"}",
"."
] |
train
|
https://github.com/matthewhorridge/owlapi-gwt/blob/7ab975fb6cef3c8947099983551672a3b5d4e2fd/owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLAnnotationAssertionAxiomImpl_CustomFieldSerializer.java#L94-L97
|
jenkinsci/jenkins
|
core/src/main/java/hudson/util/ChunkedOutputStream.java
|
ChunkedOutputStream.flushCacheWithAppend
|
protected void flushCacheWithAppend(byte[] bufferToAppend, int off, int len) throws IOException {
"""
Writes the cache and bufferToAppend to the underlying stream
as one large chunk
@param bufferToAppend
@param off
@param len
@throws IOException
@since 3.0
"""
byte[] chunkHeader = (Integer.toHexString(cachePosition + len) + "\r\n").getBytes(StandardCharsets.US_ASCII);
stream.write(chunkHeader, 0, chunkHeader.length);
stream.write(cache, 0, cachePosition);
stream.write(bufferToAppend, off, len);
stream.write(ENDCHUNK, 0, ENDCHUNK.length);
cachePosition = 0;
}
|
java
|
protected void flushCacheWithAppend(byte[] bufferToAppend, int off, int len) throws IOException {
byte[] chunkHeader = (Integer.toHexString(cachePosition + len) + "\r\n").getBytes(StandardCharsets.US_ASCII);
stream.write(chunkHeader, 0, chunkHeader.length);
stream.write(cache, 0, cachePosition);
stream.write(bufferToAppend, off, len);
stream.write(ENDCHUNK, 0, ENDCHUNK.length);
cachePosition = 0;
}
|
[
"protected",
"void",
"flushCacheWithAppend",
"(",
"byte",
"[",
"]",
"bufferToAppend",
",",
"int",
"off",
",",
"int",
"len",
")",
"throws",
"IOException",
"{",
"byte",
"[",
"]",
"chunkHeader",
"=",
"(",
"Integer",
".",
"toHexString",
"(",
"cachePosition",
"+",
"len",
")",
"+",
"\"\\r\\n\"",
")",
".",
"getBytes",
"(",
"StandardCharsets",
".",
"US_ASCII",
")",
";",
"stream",
".",
"write",
"(",
"chunkHeader",
",",
"0",
",",
"chunkHeader",
".",
"length",
")",
";",
"stream",
".",
"write",
"(",
"cache",
",",
"0",
",",
"cachePosition",
")",
";",
"stream",
".",
"write",
"(",
"bufferToAppend",
",",
"off",
",",
"len",
")",
";",
"stream",
".",
"write",
"(",
"ENDCHUNK",
",",
"0",
",",
"ENDCHUNK",
".",
"length",
")",
";",
"cachePosition",
"=",
"0",
";",
"}"
] |
Writes the cache and bufferToAppend to the underlying stream
as one large chunk
@param bufferToAppend
@param off
@param len
@throws IOException
@since 3.0
|
[
"Writes",
"the",
"cache",
"and",
"bufferToAppend",
"to",
"the",
"underlying",
"stream",
"as",
"one",
"large",
"chunk",
"@param",
"bufferToAppend",
"@param",
"off",
"@param",
"len",
"@throws",
"IOException"
] |
train
|
https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/util/ChunkedOutputStream.java#L118-L125
|
google/error-prone-javac
|
src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/ConstructorBuilder.java
|
ConstructorBuilder.buildConstructorComments
|
public void buildConstructorComments(XMLNode node, Content constructorDocTree) {
"""
Build the comments for the constructor. Do nothing if
{@link Configuration#nocomment} is set to true.
@param node the XML element that specifies which components to document
@param constructorDocTree the content tree to which the documentation will be added
"""
if (!configuration.nocomment) {
writer.addComments(currentConstructor, constructorDocTree);
}
}
|
java
|
public void buildConstructorComments(XMLNode node, Content constructorDocTree) {
if (!configuration.nocomment) {
writer.addComments(currentConstructor, constructorDocTree);
}
}
|
[
"public",
"void",
"buildConstructorComments",
"(",
"XMLNode",
"node",
",",
"Content",
"constructorDocTree",
")",
"{",
"if",
"(",
"!",
"configuration",
".",
"nocomment",
")",
"{",
"writer",
".",
"addComments",
"(",
"currentConstructor",
",",
"constructorDocTree",
")",
";",
"}",
"}"
] |
Build the comments for the constructor. Do nothing if
{@link Configuration#nocomment} is set to true.
@param node the XML element that specifies which components to document
@param constructorDocTree the content tree to which the documentation will be added
|
[
"Build",
"the",
"comments",
"for",
"the",
"constructor",
".",
"Do",
"nothing",
"if",
"{",
"@link",
"Configuration#nocomment",
"}",
"is",
"set",
"to",
"true",
"."
] |
train
|
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/ConstructorBuilder.java#L200-L204
|
foundation-runtime/service-directory
|
2.0/sd-api/src/main/java/com/cisco/oss/foundation/directory/impl/DirectoryServiceClient.java
|
DirectoryServiceClient.getService
|
public ModelService getService(String serviceName, Watcher watcher) {
"""
Get the Service.
@param serviceName
the serviceName.
@param watcher
the Watcher.
@return
the ModelService.
"""
WatcherRegistration wcb = null;
if (watcher != null) {
wcb = new WatcherRegistration(serviceName, watcher);
}
ProtocolHeader header = new ProtocolHeader();
header.setType(ProtocolType.GetService);
GetServiceProtocol p = new GetServiceProtocol(serviceName);
p.setWatcher(watcher != null);
GetServiceResponse resp ;
resp = (GetServiceResponse) connection.submitRequest(header, p, wcb);
return resp.getService();
}
|
java
|
public ModelService getService(String serviceName, Watcher watcher){
WatcherRegistration wcb = null;
if (watcher != null) {
wcb = new WatcherRegistration(serviceName, watcher);
}
ProtocolHeader header = new ProtocolHeader();
header.setType(ProtocolType.GetService);
GetServiceProtocol p = new GetServiceProtocol(serviceName);
p.setWatcher(watcher != null);
GetServiceResponse resp ;
resp = (GetServiceResponse) connection.submitRequest(header, p, wcb);
return resp.getService();
}
|
[
"public",
"ModelService",
"getService",
"(",
"String",
"serviceName",
",",
"Watcher",
"watcher",
")",
"{",
"WatcherRegistration",
"wcb",
"=",
"null",
";",
"if",
"(",
"watcher",
"!=",
"null",
")",
"{",
"wcb",
"=",
"new",
"WatcherRegistration",
"(",
"serviceName",
",",
"watcher",
")",
";",
"}",
"ProtocolHeader",
"header",
"=",
"new",
"ProtocolHeader",
"(",
")",
";",
"header",
".",
"setType",
"(",
"ProtocolType",
".",
"GetService",
")",
";",
"GetServiceProtocol",
"p",
"=",
"new",
"GetServiceProtocol",
"(",
"serviceName",
")",
";",
"p",
".",
"setWatcher",
"(",
"watcher",
"!=",
"null",
")",
";",
"GetServiceResponse",
"resp",
";",
"resp",
"=",
"(",
"GetServiceResponse",
")",
"connection",
".",
"submitRequest",
"(",
"header",
",",
"p",
",",
"wcb",
")",
";",
"return",
"resp",
".",
"getService",
"(",
")",
";",
"}"
] |
Get the Service.
@param serviceName
the serviceName.
@param watcher
the Watcher.
@return
the ModelService.
|
[
"Get",
"the",
"Service",
"."
] |
train
|
https://github.com/foundation-runtime/service-directory/blob/a7bdefe173dc99e75eff4a24e07e6407e62f2ed4/2.0/sd-api/src/main/java/com/cisco/oss/foundation/directory/impl/DirectoryServiceClient.java#L686-L700
|
wellner/jcarafe
|
jcarafe-core/src/main/java/cern/colt/list/BooleanArrayList.java
|
BooleanArrayList.replaceFromToWithFrom
|
public void replaceFromToWithFrom(int from, int to, AbstractBooleanList other, int otherFrom) {
"""
Replaces a number of elements in the receiver with the same number of elements of another list.
Replaces elements in the receiver, between <code>from</code> (inclusive) and <code>to</code> (inclusive),
with elements of <code>other</code>, starting from <code>otherFrom</code> (inclusive).
@param from the position of the first element to be replaced in the receiver
@param to the position of the last element to be replaced in the receiver
@param other list holding elements to be copied into the receiver.
@param otherFrom position of first element within other list to be copied.
"""
// overridden for performance only.
if (! (other instanceof BooleanArrayList)) {
// slower
super.replaceFromToWithFrom(from,to,other,otherFrom);
return;
}
int length=to-from+1;
if (length>0) {
checkRangeFromTo(from, to, size());
checkRangeFromTo(otherFrom,otherFrom+length-1,other.size());
System.arraycopy(((BooleanArrayList) other).elements, otherFrom, elements, from, length);
}
}
|
java
|
public void replaceFromToWithFrom(int from, int to, AbstractBooleanList other, int otherFrom) {
// overridden for performance only.
if (! (other instanceof BooleanArrayList)) {
// slower
super.replaceFromToWithFrom(from,to,other,otherFrom);
return;
}
int length=to-from+1;
if (length>0) {
checkRangeFromTo(from, to, size());
checkRangeFromTo(otherFrom,otherFrom+length-1,other.size());
System.arraycopy(((BooleanArrayList) other).elements, otherFrom, elements, from, length);
}
}
|
[
"public",
"void",
"replaceFromToWithFrom",
"(",
"int",
"from",
",",
"int",
"to",
",",
"AbstractBooleanList",
"other",
",",
"int",
"otherFrom",
")",
"{",
"// overridden for performance only.\r",
"if",
"(",
"!",
"(",
"other",
"instanceof",
"BooleanArrayList",
")",
")",
"{",
"// slower\r",
"super",
".",
"replaceFromToWithFrom",
"(",
"from",
",",
"to",
",",
"other",
",",
"otherFrom",
")",
";",
"return",
";",
"}",
"int",
"length",
"=",
"to",
"-",
"from",
"+",
"1",
";",
"if",
"(",
"length",
">",
"0",
")",
"{",
"checkRangeFromTo",
"(",
"from",
",",
"to",
",",
"size",
"(",
")",
")",
";",
"checkRangeFromTo",
"(",
"otherFrom",
",",
"otherFrom",
"+",
"length",
"-",
"1",
",",
"other",
".",
"size",
"(",
")",
")",
";",
"System",
".",
"arraycopy",
"(",
"(",
"(",
"BooleanArrayList",
")",
"other",
")",
".",
"elements",
",",
"otherFrom",
",",
"elements",
",",
"from",
",",
"length",
")",
";",
"}",
"}"
] |
Replaces a number of elements in the receiver with the same number of elements of another list.
Replaces elements in the receiver, between <code>from</code> (inclusive) and <code>to</code> (inclusive),
with elements of <code>other</code>, starting from <code>otherFrom</code> (inclusive).
@param from the position of the first element to be replaced in the receiver
@param to the position of the last element to be replaced in the receiver
@param other list holding elements to be copied into the receiver.
@param otherFrom position of first element within other list to be copied.
|
[
"Replaces",
"a",
"number",
"of",
"elements",
"in",
"the",
"receiver",
"with",
"the",
"same",
"number",
"of",
"elements",
"of",
"another",
"list",
".",
"Replaces",
"elements",
"in",
"the",
"receiver",
"between",
"<code",
">",
"from<",
"/",
"code",
">",
"(",
"inclusive",
")",
"and",
"<code",
">",
"to<",
"/",
"code",
">",
"(",
"inclusive",
")",
"with",
"elements",
"of",
"<code",
">",
"other<",
"/",
"code",
">",
"starting",
"from",
"<code",
">",
"otherFrom<",
"/",
"code",
">",
"(",
"inclusive",
")",
"."
] |
train
|
https://github.com/wellner/jcarafe/blob/ab8b0a83dbf600fe80c27711815c90bd3055b217/jcarafe-core/src/main/java/cern/colt/list/BooleanArrayList.java#L365-L378
|
gocd/gocd
|
base/src/main/java/com/thoughtworks/go/util/DirectoryScanner.java
|
DirectoryScanner.isDeeper
|
private boolean isDeeper(String pattern, String name) {
"""
Verify that a pattern specifies files deeper
than the level of the specified file.
@param pattern the pattern to check.
@param name the name to check.
@return whether the pattern is deeper than the name.
@since Ant 1.6.3
"""
Vector p = SelectorUtils.tokenizePath(pattern);
Vector n = SelectorUtils.tokenizePath(name);
return p.contains("**") || p.size() > n.size();
}
|
java
|
private boolean isDeeper(String pattern, String name) {
Vector p = SelectorUtils.tokenizePath(pattern);
Vector n = SelectorUtils.tokenizePath(name);
return p.contains("**") || p.size() > n.size();
}
|
[
"private",
"boolean",
"isDeeper",
"(",
"String",
"pattern",
",",
"String",
"name",
")",
"{",
"Vector",
"p",
"=",
"SelectorUtils",
".",
"tokenizePath",
"(",
"pattern",
")",
";",
"Vector",
"n",
"=",
"SelectorUtils",
".",
"tokenizePath",
"(",
"name",
")",
";",
"return",
"p",
".",
"contains",
"(",
"\"**\"",
")",
"||",
"p",
".",
"size",
"(",
")",
">",
"n",
".",
"size",
"(",
")",
";",
"}"
] |
Verify that a pattern specifies files deeper
than the level of the specified file.
@param pattern the pattern to check.
@param name the name to check.
@return whether the pattern is deeper than the name.
@since Ant 1.6.3
|
[
"Verify",
"that",
"a",
"pattern",
"specifies",
"files",
"deeper",
"than",
"the",
"level",
"of",
"the",
"specified",
"file",
"."
] |
train
|
https://github.com/gocd/gocd/blob/59a8480e23d6c06de39127635108dff57603cb71/base/src/main/java/com/thoughtworks/go/util/DirectoryScanner.java#L1219-L1223
|
graphhopper/graphhopper
|
api/src/main/java/com/graphhopper/util/AngleCalc.java
|
AngleCalc.calcOrientation
|
public double calcOrientation(double lat1, double lon1, double lat2, double lon2, boolean exact) {
"""
Return orientation of line relative to east.
<p>
@param exact If false the atan gets calculated faster, but it might contain small errors
@return Orientation in interval -pi to +pi where 0 is east
"""
double shrinkFactor = cos(toRadians((lat1 + lat2) / 2));
if (exact)
return Math.atan2(lat2 - lat1, shrinkFactor * (lon2 - lon1));
else
return atan2(lat2 - lat1, shrinkFactor * (lon2 - lon1));
}
|
java
|
public double calcOrientation(double lat1, double lon1, double lat2, double lon2, boolean exact) {
double shrinkFactor = cos(toRadians((lat1 + lat2) / 2));
if (exact)
return Math.atan2(lat2 - lat1, shrinkFactor * (lon2 - lon1));
else
return atan2(lat2 - lat1, shrinkFactor * (lon2 - lon1));
}
|
[
"public",
"double",
"calcOrientation",
"(",
"double",
"lat1",
",",
"double",
"lon1",
",",
"double",
"lat2",
",",
"double",
"lon2",
",",
"boolean",
"exact",
")",
"{",
"double",
"shrinkFactor",
"=",
"cos",
"(",
"toRadians",
"(",
"(",
"lat1",
"+",
"lat2",
")",
"/",
"2",
")",
")",
";",
"if",
"(",
"exact",
")",
"return",
"Math",
".",
"atan2",
"(",
"lat2",
"-",
"lat1",
",",
"shrinkFactor",
"*",
"(",
"lon2",
"-",
"lon1",
")",
")",
";",
"else",
"return",
"atan2",
"(",
"lat2",
"-",
"lat1",
",",
"shrinkFactor",
"*",
"(",
"lon2",
"-",
"lon1",
")",
")",
";",
"}"
] |
Return orientation of line relative to east.
<p>
@param exact If false the atan gets calculated faster, but it might contain small errors
@return Orientation in interval -pi to +pi where 0 is east
|
[
"Return",
"orientation",
"of",
"line",
"relative",
"to",
"east",
".",
"<p",
">"
] |
train
|
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/api/src/main/java/com/graphhopper/util/AngleCalc.java#L66-L72
|
baasbox/Android-SDK
|
library/src/main/java/com/baasbox/android/json/JsonArray.java
|
JsonArray.getBoolean
|
public boolean getBoolean(int index, boolean otherwise) {
"""
Returns the <code>boolean</code> at index or otherwise if not found.
@param index
@return the value at index or null if not found
@throws java.lang.IndexOutOfBoundsException if the index is out of the array bounds
"""
Boolean b = getBoolean(index);
return b == null ? otherwise : b;
}
|
java
|
public boolean getBoolean(int index, boolean otherwise) {
Boolean b = getBoolean(index);
return b == null ? otherwise : b;
}
|
[
"public",
"boolean",
"getBoolean",
"(",
"int",
"index",
",",
"boolean",
"otherwise",
")",
"{",
"Boolean",
"b",
"=",
"getBoolean",
"(",
"index",
")",
";",
"return",
"b",
"==",
"null",
"?",
"otherwise",
":",
"b",
";",
"}"
] |
Returns the <code>boolean</code> at index or otherwise if not found.
@param index
@return the value at index or null if not found
@throws java.lang.IndexOutOfBoundsException if the index is out of the array bounds
|
[
"Returns",
"the",
"<code",
">",
"boolean<",
"/",
"code",
">",
"at",
"index",
"or",
"otherwise",
"if",
"not",
"found",
"."
] |
train
|
https://github.com/baasbox/Android-SDK/blob/6bb2203246b885b2ad63a7bfaf37c83caf15e0d8/library/src/main/java/com/baasbox/android/json/JsonArray.java#L480-L483
|
Azure/azure-sdk-for-java
|
appservice/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/appservice/v2018_02_01/implementation/DiagnosticsInner.java
|
DiagnosticsInner.getSiteDetectorAsync
|
public Observable<Page<DetectorDefinitionInner>> getSiteDetectorAsync(final String resourceGroupName, final String siteName, final String diagnosticCategory, final String detectorName) {
"""
Get Detector.
Get Detector.
@param resourceGroupName Name of the resource group to which the resource belongs.
@param siteName Site Name
@param diagnosticCategory Diagnostic Category
@param detectorName Detector Name
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<DetectorDefinitionInner> object
"""
return getSiteDetectorWithServiceResponseAsync(resourceGroupName, siteName, diagnosticCategory, detectorName)
.map(new Func1<ServiceResponse<Page<DetectorDefinitionInner>>, Page<DetectorDefinitionInner>>() {
@Override
public Page<DetectorDefinitionInner> call(ServiceResponse<Page<DetectorDefinitionInner>> response) {
return response.body();
}
});
}
|
java
|
public Observable<Page<DetectorDefinitionInner>> getSiteDetectorAsync(final String resourceGroupName, final String siteName, final String diagnosticCategory, final String detectorName) {
return getSiteDetectorWithServiceResponseAsync(resourceGroupName, siteName, diagnosticCategory, detectorName)
.map(new Func1<ServiceResponse<Page<DetectorDefinitionInner>>, Page<DetectorDefinitionInner>>() {
@Override
public Page<DetectorDefinitionInner> call(ServiceResponse<Page<DetectorDefinitionInner>> response) {
return response.body();
}
});
}
|
[
"public",
"Observable",
"<",
"Page",
"<",
"DetectorDefinitionInner",
">",
">",
"getSiteDetectorAsync",
"(",
"final",
"String",
"resourceGroupName",
",",
"final",
"String",
"siteName",
",",
"final",
"String",
"diagnosticCategory",
",",
"final",
"String",
"detectorName",
")",
"{",
"return",
"getSiteDetectorWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"siteName",
",",
"diagnosticCategory",
",",
"detectorName",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"DetectorDefinitionInner",
">",
">",
",",
"Page",
"<",
"DetectorDefinitionInner",
">",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"Page",
"<",
"DetectorDefinitionInner",
">",
"call",
"(",
"ServiceResponse",
"<",
"Page",
"<",
"DetectorDefinitionInner",
">",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Get Detector.
Get Detector.
@param resourceGroupName Name of the resource group to which the resource belongs.
@param siteName Site Name
@param diagnosticCategory Diagnostic Category
@param detectorName Detector Name
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<DetectorDefinitionInner> object
|
[
"Get",
"Detector",
".",
"Get",
"Detector",
"."
] |
train
|
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/appservice/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/appservice/v2018_02_01/implementation/DiagnosticsInner.java#L1035-L1043
|
gliga/ekstazi
|
org.ekstazi.core/src/main/java/org/ekstazi/agent/EkstaziAgent.java
|
EkstaziAgent.premain
|
public static void premain(String options, Instrumentation instrumentation) {
"""
Executed if agent is invoked before the application is started (usually
when specified as javaagent on command line). Note that this method has
two modes: 1) starts only class transformer (multiRun mode), and 2)
starts transformer and starts/ends coverage (singleRun mode). Option
2) is executed if javaagent is invoked with singleRun:runName
argument, where runName is the name of the file that will be used to save
coverage. If the argument is not correct or no argument is specified,
option 1) is used.
@param options
Command line options specified for javaagent.
@param instrumentation
Instrumentation instance.
"""
// Load options.
Config.loadConfig(options, false);
if (Config.X_ENABLED_V) {
// Initialize instrumentation instance according to the
// given mode.
initializeMode(instrumentation);
}
}
|
java
|
public static void premain(String options, Instrumentation instrumentation) {
// Load options.
Config.loadConfig(options, false);
if (Config.X_ENABLED_V) {
// Initialize instrumentation instance according to the
// given mode.
initializeMode(instrumentation);
}
}
|
[
"public",
"static",
"void",
"premain",
"(",
"String",
"options",
",",
"Instrumentation",
"instrumentation",
")",
"{",
"// Load options.",
"Config",
".",
"loadConfig",
"(",
"options",
",",
"false",
")",
";",
"if",
"(",
"Config",
".",
"X_ENABLED_V",
")",
"{",
"// Initialize instrumentation instance according to the",
"// given mode.",
"initializeMode",
"(",
"instrumentation",
")",
";",
"}",
"}"
] |
Executed if agent is invoked before the application is started (usually
when specified as javaagent on command line). Note that this method has
two modes: 1) starts only class transformer (multiRun mode), and 2)
starts transformer and starts/ends coverage (singleRun mode). Option
2) is executed if javaagent is invoked with singleRun:runName
argument, where runName is the name of the file that will be used to save
coverage. If the argument is not correct or no argument is specified,
option 1) is used.
@param options
Command line options specified for javaagent.
@param instrumentation
Instrumentation instance.
|
[
"Executed",
"if",
"agent",
"is",
"invoked",
"before",
"the",
"application",
"is",
"started",
"(",
"usually",
"when",
"specified",
"as",
"javaagent",
"on",
"command",
"line",
")",
".",
"Note",
"that",
"this",
"method",
"has",
"two",
"modes",
":",
"1",
")",
"starts",
"only",
"class",
"transformer",
"(",
"multiRun",
"mode",
")",
"and",
"2",
")",
"starts",
"transformer",
"and",
"starts",
"/",
"ends",
"coverage",
"(",
"singleRun",
"mode",
")",
".",
"Option",
"2",
")",
"is",
"executed",
"if",
"javaagent",
"is",
"invoked",
"with",
"singleRun",
":",
"runName",
"argument",
"where",
"runName",
"is",
"the",
"name",
"of",
"the",
"file",
"that",
"will",
"be",
"used",
"to",
"save",
"coverage",
".",
"If",
"the",
"argument",
"is",
"not",
"correct",
"or",
"no",
"argument",
"is",
"specified",
"option",
"1",
")",
"is",
"used",
"."
] |
train
|
https://github.com/gliga/ekstazi/blob/5bf4d39a13305afe62f8b8d2d7b4c573d37d42a1/org.ekstazi.core/src/main/java/org/ekstazi/agent/EkstaziAgent.java#L54-L63
|
cchabanois/transmorph
|
src/main/java/net/entropysoft/transmorph/type/TypeUtils.java
|
TypeUtils.matches
|
private static boolean matches(Type from, Type to, Map<String, Type> typeMap) {
"""
Checks if two types are the same or are equivalent under a variable
mapping given in the type map that was provided.
"""
if (to.equals(from))
return true;
if (from instanceof TypeVariable) {
return to.equals(typeMap.get(((TypeVariable<?>) from).getName()));
}
return false;
}
|
java
|
private static boolean matches(Type from, Type to, Map<String, Type> typeMap) {
if (to.equals(from))
return true;
if (from instanceof TypeVariable) {
return to.equals(typeMap.get(((TypeVariable<?>) from).getName()));
}
return false;
}
|
[
"private",
"static",
"boolean",
"matches",
"(",
"Type",
"from",
",",
"Type",
"to",
",",
"Map",
"<",
"String",
",",
"Type",
">",
"typeMap",
")",
"{",
"if",
"(",
"to",
".",
"equals",
"(",
"from",
")",
")",
"return",
"true",
";",
"if",
"(",
"from",
"instanceof",
"TypeVariable",
")",
"{",
"return",
"to",
".",
"equals",
"(",
"typeMap",
".",
"get",
"(",
"(",
"(",
"TypeVariable",
"<",
"?",
">",
")",
"from",
")",
".",
"getName",
"(",
")",
")",
")",
";",
"}",
"return",
"false",
";",
"}"
] |
Checks if two types are the same or are equivalent under a variable
mapping given in the type map that was provided.
|
[
"Checks",
"if",
"two",
"types",
"are",
"the",
"same",
"or",
"are",
"equivalent",
"under",
"a",
"variable",
"mapping",
"given",
"in",
"the",
"type",
"map",
"that",
"was",
"provided",
"."
] |
train
|
https://github.com/cchabanois/transmorph/blob/118550f30b9680a84eab7496bd8b04118740dcec/src/main/java/net/entropysoft/transmorph/type/TypeUtils.java#L170-L179
|
bitcoinj/bitcoinj
|
core/src/main/java/org/bitcoinj/core/PeerGroup.java
|
PeerGroup.connectTo
|
@Nullable @GuardedBy("lock")
protected Peer connectTo(PeerAddress address, boolean incrementMaxConnections, int connectTimeoutMillis) {
"""
Creates a version message to send, constructs a Peer object and attempts to connect it. Returns the peer on
success or null on failure.
@param address Remote network address
@param incrementMaxConnections Whether to consider this connection an attempt to fill our quota, or something
explicitly requested.
@return Peer or null.
"""
checkState(lock.isHeldByCurrentThread());
VersionMessage ver = getVersionMessage().duplicate();
ver.bestHeight = chain == null ? 0 : chain.getBestChainHeight();
ver.time = Utils.currentTimeSeconds();
ver.receivingAddr = address;
ver.receivingAddr.setParent(ver);
Peer peer = createPeer(address, ver);
peer.addConnectedEventListener(Threading.SAME_THREAD, startupListener);
peer.addDisconnectedEventListener(Threading.SAME_THREAD, startupListener);
peer.setMinProtocolVersion(vMinRequiredProtocolVersion);
pendingPeers.add(peer);
try {
log.info("Attempting connection to {} ({} connected, {} pending, {} max)", address,
peers.size(), pendingPeers.size(), maxConnections);
ListenableFuture<SocketAddress> future = channels.openConnection(address.toSocketAddress(), peer);
if (future.isDone())
Uninterruptibles.getUninterruptibly(future);
} catch (ExecutionException e) {
Throwable cause = Throwables.getRootCause(e);
log.warn("Failed to connect to " + address + ": " + cause.getMessage());
handlePeerDeath(peer, cause);
return null;
}
peer.setSocketTimeout(connectTimeoutMillis);
// When the channel has connected and version negotiated successfully, handleNewPeer will end up being called on
// a worker thread.
if (incrementMaxConnections) {
// We don't use setMaxConnections here as that would trigger a recursive attempt to establish a new
// outbound connection.
maxConnections++;
}
return peer;
}
|
java
|
@Nullable @GuardedBy("lock")
protected Peer connectTo(PeerAddress address, boolean incrementMaxConnections, int connectTimeoutMillis) {
checkState(lock.isHeldByCurrentThread());
VersionMessage ver = getVersionMessage().duplicate();
ver.bestHeight = chain == null ? 0 : chain.getBestChainHeight();
ver.time = Utils.currentTimeSeconds();
ver.receivingAddr = address;
ver.receivingAddr.setParent(ver);
Peer peer = createPeer(address, ver);
peer.addConnectedEventListener(Threading.SAME_THREAD, startupListener);
peer.addDisconnectedEventListener(Threading.SAME_THREAD, startupListener);
peer.setMinProtocolVersion(vMinRequiredProtocolVersion);
pendingPeers.add(peer);
try {
log.info("Attempting connection to {} ({} connected, {} pending, {} max)", address,
peers.size(), pendingPeers.size(), maxConnections);
ListenableFuture<SocketAddress> future = channels.openConnection(address.toSocketAddress(), peer);
if (future.isDone())
Uninterruptibles.getUninterruptibly(future);
} catch (ExecutionException e) {
Throwable cause = Throwables.getRootCause(e);
log.warn("Failed to connect to " + address + ": " + cause.getMessage());
handlePeerDeath(peer, cause);
return null;
}
peer.setSocketTimeout(connectTimeoutMillis);
// When the channel has connected and version negotiated successfully, handleNewPeer will end up being called on
// a worker thread.
if (incrementMaxConnections) {
// We don't use setMaxConnections here as that would trigger a recursive attempt to establish a new
// outbound connection.
maxConnections++;
}
return peer;
}
|
[
"@",
"Nullable",
"@",
"GuardedBy",
"(",
"\"lock\"",
")",
"protected",
"Peer",
"connectTo",
"(",
"PeerAddress",
"address",
",",
"boolean",
"incrementMaxConnections",
",",
"int",
"connectTimeoutMillis",
")",
"{",
"checkState",
"(",
"lock",
".",
"isHeldByCurrentThread",
"(",
")",
")",
";",
"VersionMessage",
"ver",
"=",
"getVersionMessage",
"(",
")",
".",
"duplicate",
"(",
")",
";",
"ver",
".",
"bestHeight",
"=",
"chain",
"==",
"null",
"?",
"0",
":",
"chain",
".",
"getBestChainHeight",
"(",
")",
";",
"ver",
".",
"time",
"=",
"Utils",
".",
"currentTimeSeconds",
"(",
")",
";",
"ver",
".",
"receivingAddr",
"=",
"address",
";",
"ver",
".",
"receivingAddr",
".",
"setParent",
"(",
"ver",
")",
";",
"Peer",
"peer",
"=",
"createPeer",
"(",
"address",
",",
"ver",
")",
";",
"peer",
".",
"addConnectedEventListener",
"(",
"Threading",
".",
"SAME_THREAD",
",",
"startupListener",
")",
";",
"peer",
".",
"addDisconnectedEventListener",
"(",
"Threading",
".",
"SAME_THREAD",
",",
"startupListener",
")",
";",
"peer",
".",
"setMinProtocolVersion",
"(",
"vMinRequiredProtocolVersion",
")",
";",
"pendingPeers",
".",
"add",
"(",
"peer",
")",
";",
"try",
"{",
"log",
".",
"info",
"(",
"\"Attempting connection to {} ({} connected, {} pending, {} max)\"",
",",
"address",
",",
"peers",
".",
"size",
"(",
")",
",",
"pendingPeers",
".",
"size",
"(",
")",
",",
"maxConnections",
")",
";",
"ListenableFuture",
"<",
"SocketAddress",
">",
"future",
"=",
"channels",
".",
"openConnection",
"(",
"address",
".",
"toSocketAddress",
"(",
")",
",",
"peer",
")",
";",
"if",
"(",
"future",
".",
"isDone",
"(",
")",
")",
"Uninterruptibles",
".",
"getUninterruptibly",
"(",
"future",
")",
";",
"}",
"catch",
"(",
"ExecutionException",
"e",
")",
"{",
"Throwable",
"cause",
"=",
"Throwables",
".",
"getRootCause",
"(",
"e",
")",
";",
"log",
".",
"warn",
"(",
"\"Failed to connect to \"",
"+",
"address",
"+",
"\": \"",
"+",
"cause",
".",
"getMessage",
"(",
")",
")",
";",
"handlePeerDeath",
"(",
"peer",
",",
"cause",
")",
";",
"return",
"null",
";",
"}",
"peer",
".",
"setSocketTimeout",
"(",
"connectTimeoutMillis",
")",
";",
"// When the channel has connected and version negotiated successfully, handleNewPeer will end up being called on",
"// a worker thread.",
"if",
"(",
"incrementMaxConnections",
")",
"{",
"// We don't use setMaxConnections here as that would trigger a recursive attempt to establish a new",
"// outbound connection.",
"maxConnections",
"++",
";",
"}",
"return",
"peer",
";",
"}"
] |
Creates a version message to send, constructs a Peer object and attempts to connect it. Returns the peer on
success or null on failure.
@param address Remote network address
@param incrementMaxConnections Whether to consider this connection an attempt to fill our quota, or something
explicitly requested.
@return Peer or null.
|
[
"Creates",
"a",
"version",
"message",
"to",
"send",
"constructs",
"a",
"Peer",
"object",
"and",
"attempts",
"to",
"connect",
"it",
".",
"Returns",
"the",
"peer",
"on",
"success",
"or",
"null",
"on",
"failure",
"."
] |
train
|
https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/PeerGroup.java#L1342-L1378
|
CODAIT/stocator
|
src/main/java/com/ibm/stocator/fs/cos/COSUtils.java
|
COSUtils.ensureOutputParameterInRange
|
public static int ensureOutputParameterInRange(String name, long size) {
"""
Ensure that the long value is in the range of an integer.
@param name property name for error messages
@param size original size
@return the size, guaranteed to be less than or equal to the max value of
an integer
"""
if (size > Integer.MAX_VALUE) {
LOG.warn("cos: {} capped to ~2.14GB"
+ " (maximum allowed size with current output mechanism)", name);
return Integer.MAX_VALUE;
} else {
return (int) size;
}
}
|
java
|
public static int ensureOutputParameterInRange(String name, long size) {
if (size > Integer.MAX_VALUE) {
LOG.warn("cos: {} capped to ~2.14GB"
+ " (maximum allowed size with current output mechanism)", name);
return Integer.MAX_VALUE;
} else {
return (int) size;
}
}
|
[
"public",
"static",
"int",
"ensureOutputParameterInRange",
"(",
"String",
"name",
",",
"long",
"size",
")",
"{",
"if",
"(",
"size",
">",
"Integer",
".",
"MAX_VALUE",
")",
"{",
"LOG",
".",
"warn",
"(",
"\"cos: {} capped to ~2.14GB\"",
"+",
"\" (maximum allowed size with current output mechanism)\"",
",",
"name",
")",
";",
"return",
"Integer",
".",
"MAX_VALUE",
";",
"}",
"else",
"{",
"return",
"(",
"int",
")",
"size",
";",
"}",
"}"
] |
Ensure that the long value is in the range of an integer.
@param name property name for error messages
@param size original size
@return the size, guaranteed to be less than or equal to the max value of
an integer
|
[
"Ensure",
"that",
"the",
"long",
"value",
"is",
"in",
"the",
"range",
"of",
"an",
"integer",
"."
] |
train
|
https://github.com/CODAIT/stocator/blob/35969cadd2e8faa6fdac45e8bec1799fdd3d8299/src/main/java/com/ibm/stocator/fs/cos/COSUtils.java#L224-L232
|
prestodb/presto
|
presto-main/src/main/java/com/facebook/presto/execution/executor/MultilevelSplitQueue.java
|
MultilevelSplitQueue.updatePriority
|
public Priority updatePriority(Priority oldPriority, long quantaNanos, long scheduledNanos) {
"""
Presto 'charges' the quanta run time to the task <i>and</i> the level it belongs to in
an effort to maintain the target thread utilization ratios between levels and to
maintain fairness within a level.
<p>
Consider an example split where a read hung for several minutes. This is either a bug
or a failing dependency. In either case we do not want to charge the task too much,
and we especially do not want to charge the level too much - i.e. cause other queries
in this level to starve.
@return the new priority for the task
"""
int oldLevel = oldPriority.getLevel();
int newLevel = computeLevel(scheduledNanos);
long levelContribution = Math.min(quantaNanos, LEVEL_CONTRIBUTION_CAP);
if (oldLevel == newLevel) {
addLevelTime(oldLevel, levelContribution);
return new Priority(oldLevel, oldPriority.getLevelPriority() + quantaNanos);
}
long remainingLevelContribution = levelContribution;
long remainingTaskTime = quantaNanos;
// a task normally slowly accrues scheduled time in a level and then moves to the next, but
// if the split had a particularly long quanta, accrue time to each level as if it had run
// in that level up to the level limit.
for (int currentLevel = oldLevel; currentLevel < newLevel; currentLevel++) {
long timeAccruedToLevel = Math.min(SECONDS.toNanos(LEVEL_THRESHOLD_SECONDS[currentLevel + 1] - LEVEL_THRESHOLD_SECONDS[currentLevel]), remainingLevelContribution);
addLevelTime(currentLevel, timeAccruedToLevel);
remainingLevelContribution -= timeAccruedToLevel;
remainingTaskTime -= timeAccruedToLevel;
}
addLevelTime(newLevel, remainingLevelContribution);
long newLevelMinPriority = getLevelMinPriority(newLevel, scheduledNanos);
return new Priority(newLevel, newLevelMinPriority + remainingTaskTime);
}
|
java
|
public Priority updatePriority(Priority oldPriority, long quantaNanos, long scheduledNanos)
{
int oldLevel = oldPriority.getLevel();
int newLevel = computeLevel(scheduledNanos);
long levelContribution = Math.min(quantaNanos, LEVEL_CONTRIBUTION_CAP);
if (oldLevel == newLevel) {
addLevelTime(oldLevel, levelContribution);
return new Priority(oldLevel, oldPriority.getLevelPriority() + quantaNanos);
}
long remainingLevelContribution = levelContribution;
long remainingTaskTime = quantaNanos;
// a task normally slowly accrues scheduled time in a level and then moves to the next, but
// if the split had a particularly long quanta, accrue time to each level as if it had run
// in that level up to the level limit.
for (int currentLevel = oldLevel; currentLevel < newLevel; currentLevel++) {
long timeAccruedToLevel = Math.min(SECONDS.toNanos(LEVEL_THRESHOLD_SECONDS[currentLevel + 1] - LEVEL_THRESHOLD_SECONDS[currentLevel]), remainingLevelContribution);
addLevelTime(currentLevel, timeAccruedToLevel);
remainingLevelContribution -= timeAccruedToLevel;
remainingTaskTime -= timeAccruedToLevel;
}
addLevelTime(newLevel, remainingLevelContribution);
long newLevelMinPriority = getLevelMinPriority(newLevel, scheduledNanos);
return new Priority(newLevel, newLevelMinPriority + remainingTaskTime);
}
|
[
"public",
"Priority",
"updatePriority",
"(",
"Priority",
"oldPriority",
",",
"long",
"quantaNanos",
",",
"long",
"scheduledNanos",
")",
"{",
"int",
"oldLevel",
"=",
"oldPriority",
".",
"getLevel",
"(",
")",
";",
"int",
"newLevel",
"=",
"computeLevel",
"(",
"scheduledNanos",
")",
";",
"long",
"levelContribution",
"=",
"Math",
".",
"min",
"(",
"quantaNanos",
",",
"LEVEL_CONTRIBUTION_CAP",
")",
";",
"if",
"(",
"oldLevel",
"==",
"newLevel",
")",
"{",
"addLevelTime",
"(",
"oldLevel",
",",
"levelContribution",
")",
";",
"return",
"new",
"Priority",
"(",
"oldLevel",
",",
"oldPriority",
".",
"getLevelPriority",
"(",
")",
"+",
"quantaNanos",
")",
";",
"}",
"long",
"remainingLevelContribution",
"=",
"levelContribution",
";",
"long",
"remainingTaskTime",
"=",
"quantaNanos",
";",
"// a task normally slowly accrues scheduled time in a level and then moves to the next, but",
"// if the split had a particularly long quanta, accrue time to each level as if it had run",
"// in that level up to the level limit.",
"for",
"(",
"int",
"currentLevel",
"=",
"oldLevel",
";",
"currentLevel",
"<",
"newLevel",
";",
"currentLevel",
"++",
")",
"{",
"long",
"timeAccruedToLevel",
"=",
"Math",
".",
"min",
"(",
"SECONDS",
".",
"toNanos",
"(",
"LEVEL_THRESHOLD_SECONDS",
"[",
"currentLevel",
"+",
"1",
"]",
"-",
"LEVEL_THRESHOLD_SECONDS",
"[",
"currentLevel",
"]",
")",
",",
"remainingLevelContribution",
")",
";",
"addLevelTime",
"(",
"currentLevel",
",",
"timeAccruedToLevel",
")",
";",
"remainingLevelContribution",
"-=",
"timeAccruedToLevel",
";",
"remainingTaskTime",
"-=",
"timeAccruedToLevel",
";",
"}",
"addLevelTime",
"(",
"newLevel",
",",
"remainingLevelContribution",
")",
";",
"long",
"newLevelMinPriority",
"=",
"getLevelMinPriority",
"(",
"newLevel",
",",
"scheduledNanos",
")",
";",
"return",
"new",
"Priority",
"(",
"newLevel",
",",
"newLevelMinPriority",
"+",
"remainingTaskTime",
")",
";",
"}"
] |
Presto 'charges' the quanta run time to the task <i>and</i> the level it belongs to in
an effort to maintain the target thread utilization ratios between levels and to
maintain fairness within a level.
<p>
Consider an example split where a read hung for several minutes. This is either a bug
or a failing dependency. In either case we do not want to charge the task too much,
and we especially do not want to charge the level too much - i.e. cause other queries
in this level to starve.
@return the new priority for the task
|
[
"Presto",
"charges",
"the",
"quanta",
"run",
"time",
"to",
"the",
"task",
"<i",
">",
"and<",
"/",
"i",
">",
"the",
"level",
"it",
"belongs",
"to",
"in",
"an",
"effort",
"to",
"maintain",
"the",
"target",
"thread",
"utilization",
"ratios",
"between",
"levels",
"and",
"to",
"maintain",
"fairness",
"within",
"a",
"level",
".",
"<p",
">",
"Consider",
"an",
"example",
"split",
"where",
"a",
"read",
"hung",
"for",
"several",
"minutes",
".",
"This",
"is",
"either",
"a",
"bug",
"or",
"a",
"failing",
"dependency",
".",
"In",
"either",
"case",
"we",
"do",
"not",
"want",
"to",
"charge",
"the",
"task",
"too",
"much",
"and",
"we",
"especially",
"do",
"not",
"want",
"to",
"charge",
"the",
"level",
"too",
"much",
"-",
"i",
".",
"e",
".",
"cause",
"other",
"queries",
"in",
"this",
"level",
"to",
"starve",
"."
] |
train
|
https://github.com/prestodb/presto/blob/89de5e379d8f85e139d292b0add8c537a2a01a88/presto-main/src/main/java/com/facebook/presto/execution/executor/MultilevelSplitQueue.java#L217-L245
|
alkacon/opencms-core
|
src/org/opencms/jlan/CmsByteBuffer.java
|
CmsByteBuffer.writeBytes
|
public void writeBytes(byte[] src, int srcStart, int destStart, int len) {
"""
Writes some bytes to this buffer, expanding the buffer if necessary.<p>
@param src the source from which to write the bytes
@param srcStart the start index in the source array
@param destStart the start index in this buffer
@param len the number of bytes to write
"""
int newEnd = destStart + len;
ensureCapacity(newEnd);
if (newEnd > m_size) {
m_size = newEnd;
}
System.arraycopy(src, srcStart, m_buffer, destStart, len);
}
|
java
|
public void writeBytes(byte[] src, int srcStart, int destStart, int len) {
int newEnd = destStart + len;
ensureCapacity(newEnd);
if (newEnd > m_size) {
m_size = newEnd;
}
System.arraycopy(src, srcStart, m_buffer, destStart, len);
}
|
[
"public",
"void",
"writeBytes",
"(",
"byte",
"[",
"]",
"src",
",",
"int",
"srcStart",
",",
"int",
"destStart",
",",
"int",
"len",
")",
"{",
"int",
"newEnd",
"=",
"destStart",
"+",
"len",
";",
"ensureCapacity",
"(",
"newEnd",
")",
";",
"if",
"(",
"newEnd",
">",
"m_size",
")",
"{",
"m_size",
"=",
"newEnd",
";",
"}",
"System",
".",
"arraycopy",
"(",
"src",
",",
"srcStart",
",",
"m_buffer",
",",
"destStart",
",",
"len",
")",
";",
"}"
] |
Writes some bytes to this buffer, expanding the buffer if necessary.<p>
@param src the source from which to write the bytes
@param srcStart the start index in the source array
@param destStart the start index in this buffer
@param len the number of bytes to write
|
[
"Writes",
"some",
"bytes",
"to",
"this",
"buffer",
"expanding",
"the",
"buffer",
"if",
"necessary",
".",
"<p",
">"
] |
train
|
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/jlan/CmsByteBuffer.java#L149-L157
|
UrielCh/ovh-java-sdk
|
ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java
|
ApiOvhCloud.project_serviceName_stack_GET
|
public ArrayList<OvhStack> project_serviceName_stack_GET(String serviceName) throws IOException {
"""
Get stacks
REST: GET /cloud/project/{serviceName}/stack
@param serviceName [required] Project id
API beta
"""
String qPath = "/cloud/project/{serviceName}/stack";
StringBuilder sb = path(qPath, serviceName);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t15);
}
|
java
|
public ArrayList<OvhStack> project_serviceName_stack_GET(String serviceName) throws IOException {
String qPath = "/cloud/project/{serviceName}/stack";
StringBuilder sb = path(qPath, serviceName);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t15);
}
|
[
"public",
"ArrayList",
"<",
"OvhStack",
">",
"project_serviceName_stack_GET",
"(",
"String",
"serviceName",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/cloud/project/{serviceName}/stack\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
",",
"serviceName",
")",
";",
"String",
"resp",
"=",
"exec",
"(",
"qPath",
",",
"\"GET\"",
",",
"sb",
".",
"toString",
"(",
")",
",",
"null",
")",
";",
"return",
"convertTo",
"(",
"resp",
",",
"t15",
")",
";",
"}"
] |
Get stacks
REST: GET /cloud/project/{serviceName}/stack
@param serviceName [required] Project id
API beta
|
[
"Get",
"stacks"
] |
train
|
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java#L1384-L1389
|
geomajas/geomajas-project-server
|
api/src/main/java/org/geomajas/layer/feature/attribute/ManyToOneAttribute.java
|
ManyToOneAttribute.setShortAttribute
|
public void setShortAttribute(String name, Short value) {
"""
Sets the specified short attribute to the specified value.
@param name name of the attribute
@param value value of the attribute
@since 1.9.0
"""
ensureValue();
Attribute attribute = new ShortAttribute(value);
attribute.setEditable(isEditable(name));
getValue().getAllAttributes().put(name, attribute);
}
|
java
|
public void setShortAttribute(String name, Short value) {
ensureValue();
Attribute attribute = new ShortAttribute(value);
attribute.setEditable(isEditable(name));
getValue().getAllAttributes().put(name, attribute);
}
|
[
"public",
"void",
"setShortAttribute",
"(",
"String",
"name",
",",
"Short",
"value",
")",
"{",
"ensureValue",
"(",
")",
";",
"Attribute",
"attribute",
"=",
"new",
"ShortAttribute",
"(",
"value",
")",
";",
"attribute",
".",
"setEditable",
"(",
"isEditable",
"(",
"name",
")",
")",
";",
"getValue",
"(",
")",
".",
"getAllAttributes",
"(",
")",
".",
"put",
"(",
"name",
",",
"attribute",
")",
";",
"}"
] |
Sets the specified short attribute to the specified value.
@param name name of the attribute
@param value value of the attribute
@since 1.9.0
|
[
"Sets",
"the",
"specified",
"short",
"attribute",
"to",
"the",
"specified",
"value",
"."
] |
train
|
https://github.com/geomajas/geomajas-project-server/blob/904b7d7deed1350d28955589098dd1e0a786d76e/api/src/main/java/org/geomajas/layer/feature/attribute/ManyToOneAttribute.java#L230-L235
|
threerings/narya
|
core/src/main/java/com/threerings/crowd/chat/client/ChatDirector.java
|
ChatDirector.displayFeedback
|
public void displayFeedback (String bundle, String message) {
"""
Display a system FEEDBACK message as if it had come from the server. The localtype of the
message will be PLACE_CHAT_TYPE.
Feedback messages are sent in direct response to a user action, usually to indicate success
or failure of the user's action.
"""
displaySystem(bundle, message, SystemMessage.FEEDBACK, PLACE_CHAT_TYPE);
}
|
java
|
public void displayFeedback (String bundle, String message)
{
displaySystem(bundle, message, SystemMessage.FEEDBACK, PLACE_CHAT_TYPE);
}
|
[
"public",
"void",
"displayFeedback",
"(",
"String",
"bundle",
",",
"String",
"message",
")",
"{",
"displaySystem",
"(",
"bundle",
",",
"message",
",",
"SystemMessage",
".",
"FEEDBACK",
",",
"PLACE_CHAT_TYPE",
")",
";",
"}"
] |
Display a system FEEDBACK message as if it had come from the server. The localtype of the
message will be PLACE_CHAT_TYPE.
Feedback messages are sent in direct response to a user action, usually to indicate success
or failure of the user's action.
|
[
"Display",
"a",
"system",
"FEEDBACK",
"message",
"as",
"if",
"it",
"had",
"come",
"from",
"the",
"server",
".",
"The",
"localtype",
"of",
"the",
"message",
"will",
"be",
"PLACE_CHAT_TYPE",
"."
] |
train
|
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/crowd/chat/client/ChatDirector.java#L344-L347
|
alkacon/opencms-core
|
src/org/opencms/db/generic/CmsUserDriver.java
|
CmsUserDriver.internalCreateAce
|
protected CmsAccessControlEntry internalCreateAce(ResultSet res) throws SQLException {
"""
Internal helper method to create an access control entry from a database record.<p>
@param res resultset of the current query
@return a new {@link CmsAccessControlEntry} initialized with the values from the current database record
@throws SQLException if something goes wrong
"""
return internalCreateAce(res, new CmsUUID(res.getString(m_sqlManager.readQuery("C_ACCESS_RESOURCE_ID_0"))));
}
|
java
|
protected CmsAccessControlEntry internalCreateAce(ResultSet res) throws SQLException {
return internalCreateAce(res, new CmsUUID(res.getString(m_sqlManager.readQuery("C_ACCESS_RESOURCE_ID_0"))));
}
|
[
"protected",
"CmsAccessControlEntry",
"internalCreateAce",
"(",
"ResultSet",
"res",
")",
"throws",
"SQLException",
"{",
"return",
"internalCreateAce",
"(",
"res",
",",
"new",
"CmsUUID",
"(",
"res",
".",
"getString",
"(",
"m_sqlManager",
".",
"readQuery",
"(",
"\"C_ACCESS_RESOURCE_ID_0\"",
")",
")",
")",
")",
";",
"}"
] |
Internal helper method to create an access control entry from a database record.<p>
@param res resultset of the current query
@return a new {@link CmsAccessControlEntry} initialized with the values from the current database record
@throws SQLException if something goes wrong
|
[
"Internal",
"helper",
"method",
"to",
"create",
"an",
"access",
"control",
"entry",
"from",
"a",
"database",
"record",
".",
"<p",
">"
] |
train
|
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/generic/CmsUserDriver.java#L2164-L2167
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.