hexsha
stringlengths 40
40
| repo
stringlengths 5
114
| path
stringlengths 4
295
| license
listlengths 1
10
| language
stringclasses 5
values | identifier
stringlengths 1
116
| original_docstring
stringlengths 133
7.85k
| docstring
stringlengths 7
2.1k
| docstring_tokens
listlengths 3
399
| code
stringlengths 350
22.6k
| code_tokens
listlengths 20
3.22k
| short_docstring
stringlengths 0
1.32k
| short_docstring_tokens
listlengths 0
359
| comment
listlengths 0
1.22k
| parameters
listlengths 0
13
| docstring_params
dict | has_error
bool 1
class | ast_depth
int64 13
29
| code_length
int64 151
3k
| original_docstring_length
int64 76
449
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
023d87e0babd7092df56b024a2e07d7b2fcc012e
|
buidler-labs/hedera-sdk-js
|
src/topic/TopicUpdateTransaction.js
|
[
"Apache-2.0"
] |
JavaScript
|
TopicUpdateTransaction
|
/**
* Update a topic.
*
* If there is no adminKey, the only authorized update (available to anyone) is to extend the expirationTime.
* Otherwise transaction must be signed by the adminKey.
*
* If an adminKey is updated, the transaction must be signed by the pre-update adminKey and post-update adminKey.
*
* If a new autoRenewAccount is specified (not just being removed), that account must also sign the transaction.
*/
|
Update a topic.
If there is no adminKey, the only authorized update (available to anyone) is to extend the expirationTime.
Otherwise transaction must be signed by the adminKey.
If an adminKey is updated, the transaction must be signed by the pre-update adminKey and post-update adminKey.
If a new autoRenewAccount is specified (not just being removed), that account must also sign the transaction.
|
[
"Update",
"a",
"topic",
".",
"If",
"there",
"is",
"no",
"adminKey",
"the",
"only",
"authorized",
"update",
"(",
"available",
"to",
"anyone",
")",
"is",
"to",
"extend",
"the",
"expirationTime",
".",
"Otherwise",
"transaction",
"must",
"be",
"signed",
"by",
"the",
"adminKey",
".",
"If",
"an",
"adminKey",
"is",
"updated",
"the",
"transaction",
"must",
"be",
"signed",
"by",
"the",
"pre",
"-",
"update",
"adminKey",
"and",
"post",
"-",
"update",
"adminKey",
".",
"If",
"a",
"new",
"autoRenewAccount",
"is",
"specified",
"(",
"not",
"just",
"being",
"removed",
")",
"that",
"account",
"must",
"also",
"sign",
"the",
"transaction",
"."
] |
class TopicUpdateTransaction extends Transaction {
/**
* @param {object} props
* @param {TopicId | string} [props.topicId]
* @param {Key} [props.adminKey]
* @param {Key} [props.submitKey]
* @param {Duration | Long | number} [props.autoRenewPeriod]
* @param {AccountId | string} [props.autoRenewAccountId]
* @param {string} [props.topicMemo]
*/
constructor(props = {}) {
super();
/**
* @private
* @type {?TopicId}
*/
this._topicId = null;
if (props.topicId != null) {
this.setTopicId(props.topicId);
}
/**
* @private
* @type {?string}
*/
this._topicMemo = null;
if (props.topicMemo != null) {
this.setTopicMemo(props.topicMemo);
}
/**
* @private
* @type {?Key}
*/
this._submitKey = null;
if (props.submitKey != null) {
this.setSubmitKey(props.submitKey);
}
/**
* @private
* @type {?Key}
*/
this._adminKey = null;
if (props.adminKey != null) {
this.setAdminKey(props.adminKey);
}
/**
* @private
* @type {?AccountId}
*/
this._autoRenewAccountId = null;
if (props.autoRenewAccountId != null) {
this.setAutoRenewAccountId(props.autoRenewAccountId);
}
/**
* @private
* @type {?Duration}
*/
this._autoRenewPeriod = null;
if (props.autoRenewPeriod != null) {
this.setAutoRenewPeriod(props.autoRenewPeriod);
}
}
/**
* @internal
* @param {HashgraphProto.proto.ITransaction[]} transactions
* @param {HashgraphProto.proto.ISignedTransaction[]} signedTransactions
* @param {TransactionId[]} transactionIds
* @param {AccountId[]} nodeIds
* @param {HashgraphProto.proto.ITransactionBody[]} bodies
* @returns {TopicUpdateTransaction}
*/
static _fromProtobuf(
transactions,
signedTransactions,
transactionIds,
nodeIds,
bodies
) {
const body = bodies[0];
const update =
/** @type {HashgraphProto.proto.IConsensusUpdateTopicTransactionBody} */ (
body.consensusUpdateTopic
);
return Transaction._fromProtobufTransactions(
new TopicUpdateTransaction({
topicId:
update.topicID != null
? TopicId._fromProtobuf(update.topicID)
: undefined,
adminKey:
update.adminKey != null
? Key._fromProtobufKey(update.adminKey)
: undefined,
submitKey:
update.submitKey != null
? Key._fromProtobufKey(update.submitKey)
: undefined,
autoRenewAccountId:
update.autoRenewAccount != null
? AccountId._fromProtobuf(update.autoRenewAccount)
: undefined,
autoRenewPeriod:
update.autoRenewPeriod != null
? update.autoRenewPeriod.seconds != null
? update.autoRenewPeriod.seconds
: undefined
: undefined,
topicMemo:
update.memo != null
? update.memo.value != null
? update.memo.value
: undefined
: undefined,
}),
transactions,
signedTransactions,
transactionIds,
nodeIds,
bodies
);
}
/**
* @returns {?TopicId}
*/
get topicId() {
return this._topicId;
}
/**
* @param {TopicId | string} topicId
* @returns {TopicUpdateTransaction}
*/
setTopicId(topicId) {
this._requireNotFrozen();
this._topicId =
typeof topicId === "string"
? TopicId.fromString(topicId)
: topicId.clone();
return this;
}
/**
* @returns {TopicUpdateTransaction}
*/
clearTopicId() {
this._requireNotFrozen();
this._topicId = null;
return this;
}
/**
* @returns {?string}
*/
get topicMemo() {
return this._topicMemo;
}
/**
* @param {string} topicMemo
* @returns {TopicUpdateTransaction}
*/
setTopicMemo(topicMemo) {
this._requireNotFrozen();
this._topicMemo = topicMemo;
return this;
}
/**
* @returns {TopicUpdateTransaction}
*/
clearTopicMemo() {
this._requireNotFrozen();
this._topicMemo = null;
return this;
}
/**
* @returns {?Key}
*/
get adminKey() {
return this._adminKey;
}
/**
* @param {Key} adminKey
* @returns {TopicUpdateTransaction}
*/
setAdminKey(adminKey) {
this._requireNotFrozen();
this._adminKey = adminKey;
return this;
}
/**
* @returns {TopicUpdateTransaction}
*/
clearAdminKey() {
this._requireNotFrozen();
this._adminKey = null;
return this;
}
/**
* @returns {?Key}
*/
get submitKey() {
return this._submitKey;
}
/**
* @param {Key} submitKey
* @returns {TopicUpdateTransaction}
*/
setSubmitKey(submitKey) {
this._requireNotFrozen();
this._submitKey = submitKey;
return this;
}
/**
* @returns {TopicUpdateTransaction}
*/
clearSubmitKey() {
this._requireNotFrozen();
this._submitKey = null;
return this;
}
/**
* @returns {?AccountId}
*/
get autoRenewAccountId() {
return this._autoRenewAccountId;
}
/**
* @param {AccountId | string} autoRenewAccountId
* @returns {TopicUpdateTransaction}
*/
setAutoRenewAccountId(autoRenewAccountId) {
this._requireNotFrozen();
this._autoRenewAccountId =
autoRenewAccountId instanceof AccountId
? autoRenewAccountId
: AccountId.fromString(autoRenewAccountId);
return this;
}
/**
* @returns {TopicUpdateTransaction}
*/
clearAutoRenewAccountId() {
this._requireNotFrozen();
this._autoRenewAccountId = null;
return this;
}
/**
* @returns {?Duration}
*/
get autoRenewPeriod() {
return this._autoRenewPeriod;
}
/**
* Set the auto renew period for this account.
*
* @param {Duration | Long | number} autoRenewPeriod
* @returns {TopicUpdateTransaction}
*/
setAutoRenewPeriod(autoRenewPeriod) {
this._requireNotFrozen();
this._autoRenewPeriod =
autoRenewPeriod instanceof Duration
? autoRenewPeriod
: new Duration(autoRenewPeriod);
return this;
}
/**
* @param {Client} client
*/
_validateChecksums(client) {
if (this._topicId != null) {
this._topicId.validateChecksum(client);
}
if (this._autoRenewAccountId != null) {
this._autoRenewAccountId.validateChecksum(client);
}
}
/**
* @override
* @internal
* @param {Channel} channel
* @param {HashgraphProto.proto.ITransaction} request
* @returns {Promise<HashgraphProto.proto.ITransactionResponse>}
*/
_execute(channel, request) {
return channel.consensus.updateTopic(request);
}
/**
* @override
* @protected
* @returns {NonNullable<HashgraphProto.proto.TransactionBody["data"]>}
*/
_getTransactionDataCase() {
return "consensusUpdateTopic";
}
/**
* @override
* @protected
* @returns {HashgraphProto.proto.IConsensusUpdateTopicTransactionBody}
*/
_makeTransactionData() {
return {
topicID: this._topicId != null ? this._topicId._toProtobuf() : null,
adminKey:
this._adminKey != null ? this._adminKey._toProtobufKey() : null,
submitKey:
this._submitKey != null
? this._submitKey._toProtobufKey()
: null,
memo:
this._topicMemo != null
? {
value: this._topicMemo,
}
: null,
autoRenewAccount:
this._autoRenewAccountId != null
? this._autoRenewAccountId._toProtobuf()
: null,
autoRenewPeriod:
this._autoRenewPeriod != null
? this._autoRenewPeriod._toProtobuf()
: null,
};
}
/**
* @returns {string}
*/
_getLogId() {
const timestamp = /** @type {import("../Timestamp.js").default} */ (
this._transactionIds.current.validStart
);
return `TopicUpdateTransaction:${timestamp.toString()}`;
}
}
|
[
"class",
"TopicUpdateTransaction",
"extends",
"Transaction",
"{",
"constructor",
"(",
"props",
"=",
"{",
"}",
")",
"{",
"super",
"(",
")",
";",
"this",
".",
"_topicId",
"=",
"null",
";",
"if",
"(",
"props",
".",
"topicId",
"!=",
"null",
")",
"{",
"this",
".",
"setTopicId",
"(",
"props",
".",
"topicId",
")",
";",
"}",
"this",
".",
"_topicMemo",
"=",
"null",
";",
"if",
"(",
"props",
".",
"topicMemo",
"!=",
"null",
")",
"{",
"this",
".",
"setTopicMemo",
"(",
"props",
".",
"topicMemo",
")",
";",
"}",
"this",
".",
"_submitKey",
"=",
"null",
";",
"if",
"(",
"props",
".",
"submitKey",
"!=",
"null",
")",
"{",
"this",
".",
"setSubmitKey",
"(",
"props",
".",
"submitKey",
")",
";",
"}",
"this",
".",
"_adminKey",
"=",
"null",
";",
"if",
"(",
"props",
".",
"adminKey",
"!=",
"null",
")",
"{",
"this",
".",
"setAdminKey",
"(",
"props",
".",
"adminKey",
")",
";",
"}",
"this",
".",
"_autoRenewAccountId",
"=",
"null",
";",
"if",
"(",
"props",
".",
"autoRenewAccountId",
"!=",
"null",
")",
"{",
"this",
".",
"setAutoRenewAccountId",
"(",
"props",
".",
"autoRenewAccountId",
")",
";",
"}",
"this",
".",
"_autoRenewPeriod",
"=",
"null",
";",
"if",
"(",
"props",
".",
"autoRenewPeriod",
"!=",
"null",
")",
"{",
"this",
".",
"setAutoRenewPeriod",
"(",
"props",
".",
"autoRenewPeriod",
")",
";",
"}",
"}",
"static",
"_fromProtobuf",
"(",
"transactions",
",",
"signedTransactions",
",",
"transactionIds",
",",
"nodeIds",
",",
"bodies",
")",
"{",
"const",
"body",
"=",
"bodies",
"[",
"0",
"]",
";",
"const",
"update",
"=",
"(",
"body",
".",
"consensusUpdateTopic",
")",
";",
"return",
"Transaction",
".",
"_fromProtobufTransactions",
"(",
"new",
"TopicUpdateTransaction",
"(",
"{",
"topicId",
":",
"update",
".",
"topicID",
"!=",
"null",
"?",
"TopicId",
".",
"_fromProtobuf",
"(",
"update",
".",
"topicID",
")",
":",
"undefined",
",",
"adminKey",
":",
"update",
".",
"adminKey",
"!=",
"null",
"?",
"Key",
".",
"_fromProtobufKey",
"(",
"update",
".",
"adminKey",
")",
":",
"undefined",
",",
"submitKey",
":",
"update",
".",
"submitKey",
"!=",
"null",
"?",
"Key",
".",
"_fromProtobufKey",
"(",
"update",
".",
"submitKey",
")",
":",
"undefined",
",",
"autoRenewAccountId",
":",
"update",
".",
"autoRenewAccount",
"!=",
"null",
"?",
"AccountId",
".",
"_fromProtobuf",
"(",
"update",
".",
"autoRenewAccount",
")",
":",
"undefined",
",",
"autoRenewPeriod",
":",
"update",
".",
"autoRenewPeriod",
"!=",
"null",
"?",
"update",
".",
"autoRenewPeriod",
".",
"seconds",
"!=",
"null",
"?",
"update",
".",
"autoRenewPeriod",
".",
"seconds",
":",
"undefined",
":",
"undefined",
",",
"topicMemo",
":",
"update",
".",
"memo",
"!=",
"null",
"?",
"update",
".",
"memo",
".",
"value",
"!=",
"null",
"?",
"update",
".",
"memo",
".",
"value",
":",
"undefined",
":",
"undefined",
",",
"}",
")",
",",
"transactions",
",",
"signedTransactions",
",",
"transactionIds",
",",
"nodeIds",
",",
"bodies",
")",
";",
"}",
"get",
"topicId",
"(",
")",
"{",
"return",
"this",
".",
"_topicId",
";",
"}",
"setTopicId",
"(",
"topicId",
")",
"{",
"this",
".",
"_requireNotFrozen",
"(",
")",
";",
"this",
".",
"_topicId",
"=",
"typeof",
"topicId",
"===",
"\"string\"",
"?",
"TopicId",
".",
"fromString",
"(",
"topicId",
")",
":",
"topicId",
".",
"clone",
"(",
")",
";",
"return",
"this",
";",
"}",
"clearTopicId",
"(",
")",
"{",
"this",
".",
"_requireNotFrozen",
"(",
")",
";",
"this",
".",
"_topicId",
"=",
"null",
";",
"return",
"this",
";",
"}",
"get",
"topicMemo",
"(",
")",
"{",
"return",
"this",
".",
"_topicMemo",
";",
"}",
"setTopicMemo",
"(",
"topicMemo",
")",
"{",
"this",
".",
"_requireNotFrozen",
"(",
")",
";",
"this",
".",
"_topicMemo",
"=",
"topicMemo",
";",
"return",
"this",
";",
"}",
"clearTopicMemo",
"(",
")",
"{",
"this",
".",
"_requireNotFrozen",
"(",
")",
";",
"this",
".",
"_topicMemo",
"=",
"null",
";",
"return",
"this",
";",
"}",
"get",
"adminKey",
"(",
")",
"{",
"return",
"this",
".",
"_adminKey",
";",
"}",
"setAdminKey",
"(",
"adminKey",
")",
"{",
"this",
".",
"_requireNotFrozen",
"(",
")",
";",
"this",
".",
"_adminKey",
"=",
"adminKey",
";",
"return",
"this",
";",
"}",
"clearAdminKey",
"(",
")",
"{",
"this",
".",
"_requireNotFrozen",
"(",
")",
";",
"this",
".",
"_adminKey",
"=",
"null",
";",
"return",
"this",
";",
"}",
"get",
"submitKey",
"(",
")",
"{",
"return",
"this",
".",
"_submitKey",
";",
"}",
"setSubmitKey",
"(",
"submitKey",
")",
"{",
"this",
".",
"_requireNotFrozen",
"(",
")",
";",
"this",
".",
"_submitKey",
"=",
"submitKey",
";",
"return",
"this",
";",
"}",
"clearSubmitKey",
"(",
")",
"{",
"this",
".",
"_requireNotFrozen",
"(",
")",
";",
"this",
".",
"_submitKey",
"=",
"null",
";",
"return",
"this",
";",
"}",
"get",
"autoRenewAccountId",
"(",
")",
"{",
"return",
"this",
".",
"_autoRenewAccountId",
";",
"}",
"setAutoRenewAccountId",
"(",
"autoRenewAccountId",
")",
"{",
"this",
".",
"_requireNotFrozen",
"(",
")",
";",
"this",
".",
"_autoRenewAccountId",
"=",
"autoRenewAccountId",
"instanceof",
"AccountId",
"?",
"autoRenewAccountId",
":",
"AccountId",
".",
"fromString",
"(",
"autoRenewAccountId",
")",
";",
"return",
"this",
";",
"}",
"clearAutoRenewAccountId",
"(",
")",
"{",
"this",
".",
"_requireNotFrozen",
"(",
")",
";",
"this",
".",
"_autoRenewAccountId",
"=",
"null",
";",
"return",
"this",
";",
"}",
"get",
"autoRenewPeriod",
"(",
")",
"{",
"return",
"this",
".",
"_autoRenewPeriod",
";",
"}",
"setAutoRenewPeriod",
"(",
"autoRenewPeriod",
")",
"{",
"this",
".",
"_requireNotFrozen",
"(",
")",
";",
"this",
".",
"_autoRenewPeriod",
"=",
"autoRenewPeriod",
"instanceof",
"Duration",
"?",
"autoRenewPeriod",
":",
"new",
"Duration",
"(",
"autoRenewPeriod",
")",
";",
"return",
"this",
";",
"}",
"_validateChecksums",
"(",
"client",
")",
"{",
"if",
"(",
"this",
".",
"_topicId",
"!=",
"null",
")",
"{",
"this",
".",
"_topicId",
".",
"validateChecksum",
"(",
"client",
")",
";",
"}",
"if",
"(",
"this",
".",
"_autoRenewAccountId",
"!=",
"null",
")",
"{",
"this",
".",
"_autoRenewAccountId",
".",
"validateChecksum",
"(",
"client",
")",
";",
"}",
"}",
"_execute",
"(",
"channel",
",",
"request",
")",
"{",
"return",
"channel",
".",
"consensus",
".",
"updateTopic",
"(",
"request",
")",
";",
"}",
"_getTransactionDataCase",
"(",
")",
"{",
"return",
"\"consensusUpdateTopic\"",
";",
"}",
"_makeTransactionData",
"(",
")",
"{",
"return",
"{",
"topicID",
":",
"this",
".",
"_topicId",
"!=",
"null",
"?",
"this",
".",
"_topicId",
".",
"_toProtobuf",
"(",
")",
":",
"null",
",",
"adminKey",
":",
"this",
".",
"_adminKey",
"!=",
"null",
"?",
"this",
".",
"_adminKey",
".",
"_toProtobufKey",
"(",
")",
":",
"null",
",",
"submitKey",
":",
"this",
".",
"_submitKey",
"!=",
"null",
"?",
"this",
".",
"_submitKey",
".",
"_toProtobufKey",
"(",
")",
":",
"null",
",",
"memo",
":",
"this",
".",
"_topicMemo",
"!=",
"null",
"?",
"{",
"value",
":",
"this",
".",
"_topicMemo",
",",
"}",
":",
"null",
",",
"autoRenewAccount",
":",
"this",
".",
"_autoRenewAccountId",
"!=",
"null",
"?",
"this",
".",
"_autoRenewAccountId",
".",
"_toProtobuf",
"(",
")",
":",
"null",
",",
"autoRenewPeriod",
":",
"this",
".",
"_autoRenewPeriod",
"!=",
"null",
"?",
"this",
".",
"_autoRenewPeriod",
".",
"_toProtobuf",
"(",
")",
":",
"null",
",",
"}",
";",
"}",
"_getLogId",
"(",
")",
"{",
"const",
"timestamp",
"=",
"(",
"this",
".",
"_transactionIds",
".",
"current",
".",
"validStart",
")",
";",
"return",
"`",
"${",
"timestamp",
".",
"toString",
"(",
")",
"}",
"`",
";",
"}",
"}"
] |
Update a topic.
|
[
"Update",
"a",
"topic",
"."
] |
[
"/**\n * @param {object} props\n * @param {TopicId | string} [props.topicId]\n * @param {Key} [props.adminKey]\n * @param {Key} [props.submitKey]\n * @param {Duration | Long | number} [props.autoRenewPeriod]\n * @param {AccountId | string} [props.autoRenewAccountId]\n * @param {string} [props.topicMemo]\n */",
"/**\n * @private\n * @type {?TopicId}\n */",
"/**\n * @private\n * @type {?string}\n */",
"/**\n * @private\n * @type {?Key}\n */",
"/**\n * @private\n * @type {?Key}\n */",
"/**\n * @private\n * @type {?AccountId}\n */",
"/**\n * @private\n * @type {?Duration}\n */",
"/**\n * @internal\n * @param {HashgraphProto.proto.ITransaction[]} transactions\n * @param {HashgraphProto.proto.ISignedTransaction[]} signedTransactions\n * @param {TransactionId[]} transactionIds\n * @param {AccountId[]} nodeIds\n * @param {HashgraphProto.proto.ITransactionBody[]} bodies\n * @returns {TopicUpdateTransaction}\n */",
"/** @type {HashgraphProto.proto.IConsensusUpdateTopicTransactionBody} */",
"/**\n * @returns {?TopicId}\n */",
"/**\n * @param {TopicId | string} topicId\n * @returns {TopicUpdateTransaction}\n */",
"/**\n * @returns {TopicUpdateTransaction}\n */",
"/**\n * @returns {?string}\n */",
"/**\n * @param {string} topicMemo\n * @returns {TopicUpdateTransaction}\n */",
"/**\n * @returns {TopicUpdateTransaction}\n */",
"/**\n * @returns {?Key}\n */",
"/**\n * @param {Key} adminKey\n * @returns {TopicUpdateTransaction}\n */",
"/**\n * @returns {TopicUpdateTransaction}\n */",
"/**\n * @returns {?Key}\n */",
"/**\n * @param {Key} submitKey\n * @returns {TopicUpdateTransaction}\n */",
"/**\n * @returns {TopicUpdateTransaction}\n */",
"/**\n * @returns {?AccountId}\n */",
"/**\n * @param {AccountId | string} autoRenewAccountId\n * @returns {TopicUpdateTransaction}\n */",
"/**\n * @returns {TopicUpdateTransaction}\n */",
"/**\n * @returns {?Duration}\n */",
"/**\n * Set the auto renew period for this account.\n *\n * @param {Duration | Long | number} autoRenewPeriod\n * @returns {TopicUpdateTransaction}\n */",
"/**\n * @param {Client} client\n */",
"/**\n * @override\n * @internal\n * @param {Channel} channel\n * @param {HashgraphProto.proto.ITransaction} request\n * @returns {Promise<HashgraphProto.proto.ITransactionResponse>}\n */",
"/**\n * @override\n * @protected\n * @returns {NonNullable<HashgraphProto.proto.TransactionBody[\"data\"]>}\n */",
"/**\n * @override\n * @protected\n * @returns {HashgraphProto.proto.IConsensusUpdateTopicTransactionBody}\n */",
"/**\n * @returns {string}\n */",
"/** @type {import(\"../Timestamp.js\").default} */"
] |
[
{
"param": "Transaction",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "Transaction",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 17
| 2,041
| 94
|
e7faa58d81d4541aae744425a45d9aba23ed0bc2
|
japplis/xins
|
src/tests/org/xins/tests/common/servlet/container/XINSServletRequestTests.java
|
[
"BSD-3-Clause"
] |
Java
|
XINSServletRequestTests
|
/**
* Tests for class <code>XINSServletRequest</code>.
*
* @version $Revision: 1.10 $ $Date: 2010/11/18 20:35:05 $
* @author <a href="mailto:[email protected]">Ernst de Haan</a>
*/
|
Tests for class XINSServletRequest.
|
[
"Tests",
"for",
"class",
"XINSServletRequest",
"."
] |
public class XINSServletRequestTests extends TestCase {
/**
* Constructs a new <code>XINSServletRequestTests</code> test
* suite with the specified name. The name will be passed to the
* superconstructor.
*
*
* @param name
* the name for this test suite.
*/
public XINSServletRequestTests(String name) {
super(name);
}
/**
* Returns a test suite with all test cases defined by this class.
*
* @return
* the test suite, never <code>null</code>.
*/
public static Test suite() {
return new TestSuite(XINSServletRequestTests.class);
}
public void testEmptyValues() {
XINSServletRequest request = new XINSServletRequest(AllTests.url() + "?test1=bla&test2=&test3=");
Enumeration enuParams = request.getParameterNames();
boolean test1Done = false;
boolean test2Done = false;
boolean test3Done = false;
while (enuParams.hasMoreElements()) {
String nextParam = (String) enuParams.nextElement();
if (nextParam.equals("test1") && !test1Done) {
test1Done = true;
} else if (nextParam.equals("test2") && !test2Done) {
test2Done = true;
} else if (nextParam.equals("test3") && !test3Done) {
test3Done = true;
} else {
fail("Incorrect parameter or parameter already read: " + nextParam);
}
}
if (!(test1Done && test2Done && test3Done)) {
fail("At least one of the parameter was not read correctly.");
}
}
public void testMultipleValues() {
XINSServletRequest request = new XINSServletRequest(AllTests.url() + "?test1=bla&test1=&test1=bla2");
String[] test1Values = request.getParameterValues("test1");
List test1ValuesList = Arrays.asList(test1Values);
assertEquals("Not all values found.", test1Values.length, 3);
assertTrue("Specific value not found.", test1ValuesList.contains("bla"));
assertTrue("Specific value not found.", test1ValuesList.contains(""));
assertTrue("Specific value not found.", test1ValuesList.contains("bla2"));
String[] test2Values = request.getParameterValues("test2");
assertNull("Values found for an unset parameter.", test2Values);
}
}
|
[
"public",
"class",
"XINSServletRequestTests",
"extends",
"TestCase",
"{",
"/**\r\n * Constructs a new <code>XINSServletRequestTests</code> test\r\n * suite with the specified name. The name will be passed to the\r\n * superconstructor.\r\n *\r\n *\r\n * @param name\r\n * the name for this test suite.\r\n */",
"public",
"XINSServletRequestTests",
"(",
"String",
"name",
")",
"{",
"super",
"(",
"name",
")",
";",
"}",
"/**\r\n * Returns a test suite with all test cases defined by this class.\r\n *\r\n * @return\r\n * the test suite, never <code>null</code>.\r\n */",
"public",
"static",
"Test",
"suite",
"(",
")",
"{",
"return",
"new",
"TestSuite",
"(",
"XINSServletRequestTests",
".",
"class",
")",
";",
"}",
"public",
"void",
"testEmptyValues",
"(",
")",
"{",
"XINSServletRequest",
"request",
"=",
"new",
"XINSServletRequest",
"(",
"AllTests",
".",
"url",
"(",
")",
"+",
"\"",
"?test1=bla&test2=&test3=",
"\"",
")",
";",
"Enumeration",
"enuParams",
"=",
"request",
".",
"getParameterNames",
"(",
")",
";",
"boolean",
"test1Done",
"=",
"false",
";",
"boolean",
"test2Done",
"=",
"false",
";",
"boolean",
"test3Done",
"=",
"false",
";",
"while",
"(",
"enuParams",
".",
"hasMoreElements",
"(",
")",
")",
"{",
"String",
"nextParam",
"=",
"(",
"String",
")",
"enuParams",
".",
"nextElement",
"(",
")",
";",
"if",
"(",
"nextParam",
".",
"equals",
"(",
"\"",
"test1",
"\"",
")",
"&&",
"!",
"test1Done",
")",
"{",
"test1Done",
"=",
"true",
";",
"}",
"else",
"if",
"(",
"nextParam",
".",
"equals",
"(",
"\"",
"test2",
"\"",
")",
"&&",
"!",
"test2Done",
")",
"{",
"test2Done",
"=",
"true",
";",
"}",
"else",
"if",
"(",
"nextParam",
".",
"equals",
"(",
"\"",
"test3",
"\"",
")",
"&&",
"!",
"test3Done",
")",
"{",
"test3Done",
"=",
"true",
";",
"}",
"else",
"{",
"fail",
"(",
"\"",
"Incorrect parameter or parameter already read: ",
"\"",
"+",
"nextParam",
")",
";",
"}",
"}",
"if",
"(",
"!",
"(",
"test1Done",
"&&",
"test2Done",
"&&",
"test3Done",
")",
")",
"{",
"fail",
"(",
"\"",
"At least one of the parameter was not read correctly.",
"\"",
")",
";",
"}",
"}",
"public",
"void",
"testMultipleValues",
"(",
")",
"{",
"XINSServletRequest",
"request",
"=",
"new",
"XINSServletRequest",
"(",
"AllTests",
".",
"url",
"(",
")",
"+",
"\"",
"?test1=bla&test1=&test1=bla2",
"\"",
")",
";",
"String",
"[",
"]",
"test1Values",
"=",
"request",
".",
"getParameterValues",
"(",
"\"",
"test1",
"\"",
")",
";",
"List",
"test1ValuesList",
"=",
"Arrays",
".",
"asList",
"(",
"test1Values",
")",
";",
"assertEquals",
"(",
"\"",
"Not all values found.",
"\"",
",",
"test1Values",
".",
"length",
",",
"3",
")",
";",
"assertTrue",
"(",
"\"",
"Specific value not found.",
"\"",
",",
"test1ValuesList",
".",
"contains",
"(",
"\"",
"bla",
"\"",
")",
")",
";",
"assertTrue",
"(",
"\"",
"Specific value not found.",
"\"",
",",
"test1ValuesList",
".",
"contains",
"(",
"\"",
"\"",
")",
")",
";",
"assertTrue",
"(",
"\"",
"Specific value not found.",
"\"",
",",
"test1ValuesList",
".",
"contains",
"(",
"\"",
"bla2",
"\"",
")",
")",
";",
"String",
"[",
"]",
"test2Values",
"=",
"request",
".",
"getParameterValues",
"(",
"\"",
"test2",
"\"",
")",
";",
"assertNull",
"(",
"\"",
"Values found for an unset parameter.",
"\"",
",",
"test2Values",
")",
";",
"}",
"}"
] |
Tests for class <code>XINSServletRequest</code>.
|
[
"Tests",
"for",
"class",
"<code",
">",
"XINSServletRequest<",
"/",
"code",
">",
"."
] |
[] |
[
{
"param": "TestCase",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "TestCase",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 16
| 550
| 81
|
637ecb505d1f1e244781619b42a4e960bea7f097
|
badaboda/capistrano
|
lib/capistrano/scm/perforce.rb
|
[
"MIT"
] |
Ruby
|
Perforce
|
# An SCM module for using perforce as your source control tool.
# This module can explicitly selected by placing the following line
# in your configuration:
#
# set :scm, :perforce
#
# Also, this module accepts a <tt>:p4</tt> configuration variable,
# which (if specified) will be used as the full path to the p4
# executable on the remote machine:
#
# set :p4, "/usr/local/bin/p4"
#
# This module accepts another <tt>:p4sync_flags</tt> configuration
# variable, which (if specified) can add extra options. This setting
# defaults to the value "-f" which forces resynchronization.
#
# set :p4sync_flags, "-f"
#
# This module accepts another <tt>:p4client_root</tt> configuration
# variable to handle mapping adjustments. Perforce doesn't have the
# ability to sync to a specific directory (e.g. the release_path); the
# location being synced to is defined by the client-spec. As such, we
# sync the client-spec (defined by <tt>p4client</tt> and then copy from
# the determined root of the client-spec mappings to the release_path.
# In the unlikely event that your client-spec mappings introduces
# directory structure above the rails structure, you can override the
# may need to specify the directory
#
# set :p4client_root, "/user/rmcmahon/project1/code"
#
# Finally, the module accepts a <tt>p4diff2_options</tt> configuration
# variable. This can be used to manipulate the output when running a
# diff between what is deployed, and another revision. This option
# defaults to "-u". Run 'p4 help diff2' for other options.
#
|
An SCM module for using perforce as your source control tool.
This module can explicitly selected by placing the following line
in your configuration.
set :scm, :perforce
Also, this module accepts a :p4 configuration variable,
which (if specified) will be used as the full path to the p4
executable on the remote machine.
This module accepts another :p4sync_flags configuration
variable, which (if specified) can add extra options. This setting
defaults to the value "-f" which forces resynchronization.
This module accepts another :p4client_root configuration
variable to handle mapping adjustments. Perforce doesn't have the
ability to sync to a specific directory ; the
location being synced to is defined by the client-spec. As such, we
sync the client-spec (defined by p4client and then copy from
the determined root of the client-spec mappings to the release_path.
In the unlikely event that your client-spec mappings introduces
directory structure above the rails structure, you can override the
may need to specify the directory
Finally, the module accepts a p4diff2_options configuration
variable. This can be used to manipulate the output when running a
diff between what is deployed, and another revision. This option
defaults to "-u". Run 'p4 help diff2' for other options.
|
[
"An",
"SCM",
"module",
"for",
"using",
"perforce",
"as",
"your",
"source",
"control",
"tool",
".",
"This",
"module",
"can",
"explicitly",
"selected",
"by",
"placing",
"the",
"following",
"line",
"in",
"your",
"configuration",
".",
"set",
":",
"scm",
":",
"perforce",
"Also",
"this",
"module",
"accepts",
"a",
":",
"p4",
"configuration",
"variable",
"which",
"(",
"if",
"specified",
")",
"will",
"be",
"used",
"as",
"the",
"full",
"path",
"to",
"the",
"p4",
"executable",
"on",
"the",
"remote",
"machine",
".",
"This",
"module",
"accepts",
"another",
":",
"p4sync_flags",
"configuration",
"variable",
"which",
"(",
"if",
"specified",
")",
"can",
"add",
"extra",
"options",
".",
"This",
"setting",
"defaults",
"to",
"the",
"value",
"\"",
"-",
"f",
"\"",
"which",
"forces",
"resynchronization",
".",
"This",
"module",
"accepts",
"another",
":",
"p4client_root",
"configuration",
"variable",
"to",
"handle",
"mapping",
"adjustments",
".",
"Perforce",
"doesn",
"'",
"t",
"have",
"the",
"ability",
"to",
"sync",
"to",
"a",
"specific",
"directory",
";",
"the",
"location",
"being",
"synced",
"to",
"is",
"defined",
"by",
"the",
"client",
"-",
"spec",
".",
"As",
"such",
"we",
"sync",
"the",
"client",
"-",
"spec",
"(",
"defined",
"by",
"p4client",
"and",
"then",
"copy",
"from",
"the",
"determined",
"root",
"of",
"the",
"client",
"-",
"spec",
"mappings",
"to",
"the",
"release_path",
".",
"In",
"the",
"unlikely",
"event",
"that",
"your",
"client",
"-",
"spec",
"mappings",
"introduces",
"directory",
"structure",
"above",
"the",
"rails",
"structure",
"you",
"can",
"override",
"the",
"may",
"need",
"to",
"specify",
"the",
"directory",
"Finally",
"the",
"module",
"accepts",
"a",
"p4diff2_options",
"configuration",
"variable",
".",
"This",
"can",
"be",
"used",
"to",
"manipulate",
"the",
"output",
"when",
"running",
"a",
"diff",
"between",
"what",
"is",
"deployed",
"and",
"another",
"revision",
".",
"This",
"option",
"defaults",
"to",
"\"",
"-",
"u",
"\"",
".",
"Run",
"'",
"p4",
"help",
"diff2",
"'",
"for",
"other",
"options",
"."
] |
class Perforce < Base
def latest_revision
configuration.logger.debug "querying latest revision..." unless @latest_revision
@latest_revision = `#{local_p4} counter change`.strip
@latest_revision
end
# Return the number of the revision currently deployed.
def current_revision(actor)
latest = actor.releases.last
grep = %(grep " #{latest}$" #{configuration.deploy_to}/revisions.log)
result = ""
actor.run(grep, :once => true) do |ch, str, out|
result << out if str == :out
raise "could not determine current revision" if str == :err
end
date, time, user, rev, dir = result.split
raise "current revision not found in revisions.log" unless dir == latest
rev.to_i
end
# Return a string containing the diff between the two revisions. +from+
# and +to+ may be in any format that p4 recognizes as a valid revision
# identifiers. If +from+ is +nil+, it defaults to the last deployed
# revision. If +to+ is +nil+, it defaults to #head.
def diff(actor, from=nil, to=nil)
from ||= "@#{current_revision(actor)}"
to ||= "#head"
p4client = configuration[:p4client]
p4diff2_options = configuration[:p4diff2_options]||"-u -db"
`#{local_p4} diff2 #{p4diff2_options} //#{p4client}/...#{from} //#{p4client}/...#{to}`
end
# Syncronizes (on all servers associated with the current task) the head
# revision of the code. Uses the given actor instance to execute the command.
#
def checkout(actor)
p4sync_flags = configuration[:p4sync_flags] || "-f"
p4client_root = configuration[:p4client_root] || "`#{remote_p4} client -o | grep ^Root | cut -f2`"
command = "#{remote_p4} sync #{p4sync_flags} && cp -rf #{p4client_root} #{actor.release_path};"
run_checkout(actor, command, &p4_stream_handler(actor))
end
def update(actor)
raise "#{self.class} doesn't support update(actor)"
end
private
def local_p4
add_standard_p4_options('p4')
end
def remote_p4
p4_cmd = configuration[:p4] || 'p4'
add_standard_p4_options(p4_cmd)
end
def add_standard_p4_options(p4_location)
check_settings
p4_cmd = p4_location
p4_cmd = "#{p4_cmd} -p #{configuration[:p4port]}" if configuration[:p4port]
p4_cmd = "#{p4_cmd} -u #{configuration[:p4user]}" if configuration[:p4user]
p4_cmd = "#{p4_cmd} -P #{configuration[:p4passwd]}" if configuration[:p4passwd]
p4_cmd = "#{p4_cmd} -c #{configuration[:p4client]}" if configuration[:p4client]
p4_cmd
end
def check_settings
check_setting(:p4port, "Add set :p4port, <your perforce server details e.g. my.p4.server:1666> to deploy.rb")
check_setting(:p4user, "Add set :p4user, <your production build username> to deploy.rb")
check_setting(:p4passwd, "Add set :p4passwd, <your build user password> to deploy.rb")
check_setting(:p4client, "Add set :p4client, <your client-spec name> to deploy.rb")
end
def check_setting(p4setting, message)
raise "#{p4setting} is not configured. #{message}" unless configuration[p4setting]
end
def p4_stream_handler(actor)
Proc.new do |ch, stream, out|
prefix = "#{stream} :: #{ch[:host]}"
actor.logger.info out, prefix
if out =~ /\(P4PASSWD\) invalid or unset\./i
raise "p4passwd is incorrect or unset"
elsif out =~ /Can.t create a new user.*/i
raise "p4user is incorrect or unset"
elsif out =~ /Perforce client error\:/i
raise "p4port is incorrect or unset"
elsif out =~ /Client \'[\w\-\_\.]+\' unknown.*/i
raise "p4client is incorrect or unset"
end
end
end
end
|
[
"class",
"Perforce",
"<",
"Base",
"def",
"latest_revision",
"configuration",
".",
"logger",
".",
"debug",
"\"querying latest revision...\"",
"unless",
"@latest_revision",
"@latest_revision",
"=",
"`",
"#{",
"local_p4",
"}",
" counter change",
"`",
".",
"strip",
"@latest_revision",
"end",
"def",
"current_revision",
"(",
"actor",
")",
"latest",
"=",
"actor",
".",
"releases",
".",
"last",
"grep",
"=",
"%(grep \" #{latest}$\" #{configuration.deploy_to}/revisions.log)",
"result",
"=",
"\"\"",
"actor",
".",
"run",
"(",
"grep",
",",
":once",
"=>",
"true",
")",
"do",
"|",
"ch",
",",
"str",
",",
"out",
"|",
"result",
"<<",
"out",
"if",
"str",
"==",
":out",
"raise",
"\"could not determine current revision\"",
"if",
"str",
"==",
":err",
"end",
"date",
",",
"time",
",",
"user",
",",
"rev",
",",
"dir",
"=",
"result",
".",
"split",
"raise",
"\"current revision not found in revisions.log\"",
"unless",
"dir",
"==",
"latest",
"rev",
".",
"to_i",
"end",
"def",
"diff",
"(",
"actor",
",",
"from",
"=",
"nil",
",",
"to",
"=",
"nil",
")",
"from",
"||=",
"\"@#{current_revision(actor)}\"",
"to",
"||=",
"\"#head\"",
"p4client",
"=",
"configuration",
"[",
":p4client",
"]",
"p4diff2_options",
"=",
"configuration",
"[",
":p4diff2_options",
"]",
"||",
"\"-u -db\"",
"`",
"#{",
"local_p4",
"}",
" diff2 ",
"#{",
"p4diff2_options",
"}",
" //",
"#{",
"p4client",
"}",
"/...",
"#{",
"from",
"}",
" //",
"#{",
"p4client",
"}",
"/...",
"#{",
"to",
"}",
"`",
"end",
"def",
"checkout",
"(",
"actor",
")",
"p4sync_flags",
"=",
"configuration",
"[",
":p4sync_flags",
"]",
"||",
"\"-f\"",
"p4client_root",
"=",
"configuration",
"[",
":p4client_root",
"]",
"||",
"\"`#{remote_p4} client -o | grep ^Root | cut -f2`\"",
"command",
"=",
"\"#{remote_p4} sync #{p4sync_flags} && cp -rf #{p4client_root} #{actor.release_path};\"",
"run_checkout",
"(",
"actor",
",",
"command",
",",
"&",
"p4_stream_handler",
"(",
"actor",
")",
")",
"end",
"def",
"update",
"(",
"actor",
")",
"raise",
"\"#{self.class} doesn't support update(actor)\"",
"end",
"private",
"def",
"local_p4",
"add_standard_p4_options",
"(",
"'p4'",
")",
"end",
"def",
"remote_p4",
"p4_cmd",
"=",
"configuration",
"[",
":p4",
"]",
"||",
"'p4'",
"add_standard_p4_options",
"(",
"p4_cmd",
")",
"end",
"def",
"add_standard_p4_options",
"(",
"p4_location",
")",
"check_settings",
"p4_cmd",
"=",
"p4_location",
"p4_cmd",
"=",
"\"#{p4_cmd} -p #{configuration[:p4port]}\"",
"if",
"configuration",
"[",
":p4port",
"]",
"p4_cmd",
"=",
"\"#{p4_cmd} -u #{configuration[:p4user]}\"",
"if",
"configuration",
"[",
":p4user",
"]",
"p4_cmd",
"=",
"\"#{p4_cmd} -P #{configuration[:p4passwd]}\"",
"if",
"configuration",
"[",
":p4passwd",
"]",
"p4_cmd",
"=",
"\"#{p4_cmd} -c #{configuration[:p4client]}\"",
"if",
"configuration",
"[",
":p4client",
"]",
"p4_cmd",
"end",
"def",
"check_settings",
"check_setting",
"(",
":p4port",
",",
"\"Add set :p4port, <your perforce server details e.g. my.p4.server:1666> to deploy.rb\"",
")",
"check_setting",
"(",
":p4user",
",",
"\"Add set :p4user, <your production build username> to deploy.rb\"",
")",
"check_setting",
"(",
":p4passwd",
",",
"\"Add set :p4passwd, <your build user password> to deploy.rb\"",
")",
"check_setting",
"(",
":p4client",
",",
"\"Add set :p4client, <your client-spec name> to deploy.rb\"",
")",
"end",
"def",
"check_setting",
"(",
"p4setting",
",",
"message",
")",
"raise",
"\"#{p4setting} is not configured. #{message}\"",
"unless",
"configuration",
"[",
"p4setting",
"]",
"end",
"def",
"p4_stream_handler",
"(",
"actor",
")",
"Proc",
".",
"new",
"do",
"|",
"ch",
",",
"stream",
",",
"out",
"|",
"prefix",
"=",
"\"#{stream} :: #{ch[:host]}\"",
"actor",
".",
"logger",
".",
"info",
"out",
",",
"prefix",
"if",
"out",
"=~",
"/",
"\\(",
"P4PASSWD",
"\\)",
" invalid or unset",
"\\.",
"/i",
"raise",
"\"p4passwd is incorrect or unset\"",
"elsif",
"out",
"=~",
"/",
"Can.t create a new user.*",
"/i",
"raise",
"\"p4user is incorrect or unset\"",
"elsif",
"out",
"=~",
"/",
"Perforce client error",
"\\:",
"/i",
"raise",
"\"p4port is incorrect or unset\"",
"elsif",
"out",
"=~",
"/",
"Client ",
"\\'",
"[",
"\\w",
"\\-",
"\\_",
"\\.",
"]+",
"\\'",
" unknown.*",
"/i",
"raise",
"\"p4client is incorrect or unset\"",
"end",
"end",
"end",
"end"
] |
An SCM module for using perforce as your source control tool.
|
[
"An",
"SCM",
"module",
"for",
"using",
"perforce",
"as",
"your",
"source",
"control",
"tool",
"."
] |
[
"# Return the number of the revision currently deployed.",
"# Return a string containing the diff between the two revisions. +from+",
"# and +to+ may be in any format that p4 recognizes as a valid revision",
"# identifiers. If +from+ is +nil+, it defaults to the last deployed",
"# revision. If +to+ is +nil+, it defaults to #head.",
"# Syncronizes (on all servers associated with the current task) the head",
"# revision of the code. Uses the given actor instance to execute the command. ",
"#"
] |
[
{
"param": "Base",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "Base",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 16
| 1,027
| 390
|
f79384d775c85f3267a6e0e7c0f44189c1370df4
|
gstearmit/data-structure-algorithm
|
src/main/java/ir/sk/adt/datastructure/graph/adjacencylist/OrientedAdjacencyListGraph.java
|
[
"MIT"
] |
Java
|
OrientedAdjacencyListGraph
|
/**
* simple oriented graph as part of an exercise in both Object Oriented Programming
* and Data Structures.
* <p>
* The object oriented incidence list structure suggested by Goodrich and Tamassia has special classes of vertex objects and edge objects.
* Each vertex object has an instance variable pointing to a collection object that lists the neighboring edge objects.
* In turn, each edge object points to the two vertex objects at its endpoints.
* This version of the adjacency list uses more memory than the version in which adjacent vertices are listed directly,
* but the existence of explicit edge objects allows it extra flexibility in storing additional information about edges.
* <p>
* It represents Directed Wighted graph
*
* @author <a href="[email protected]">Saeed Kayvanfar</a> on 7/11/2020.
*/
|
simple oriented graph as part of an exercise in both Object Oriented Programming
and Data Structures.
The object oriented incidence list structure suggested by Goodrich and Tamassia has special classes of vertex objects and edge objects.
Each vertex object has an instance variable pointing to a collection object that lists the neighboring edge objects.
In turn, each edge object points to the two vertex objects at its endpoints.
This version of the adjacency list uses more memory than the version in which adjacent vertices are listed directly,
but the existence of explicit edge objects allows it extra flexibility in storing additional information about edges.
It represents Directed Wighted graph
@author Saeed Kayvanfar on 7/11/2020.
|
[
"simple",
"oriented",
"graph",
"as",
"part",
"of",
"an",
"exercise",
"in",
"both",
"Object",
"Oriented",
"Programming",
"and",
"Data",
"Structures",
".",
"The",
"object",
"oriented",
"incidence",
"list",
"structure",
"suggested",
"by",
"Goodrich",
"and",
"Tamassia",
"has",
"special",
"classes",
"of",
"vertex",
"objects",
"and",
"edge",
"objects",
".",
"Each",
"vertex",
"object",
"has",
"an",
"instance",
"variable",
"pointing",
"to",
"a",
"collection",
"object",
"that",
"lists",
"the",
"neighboring",
"edge",
"objects",
".",
"In",
"turn",
"each",
"edge",
"object",
"points",
"to",
"the",
"two",
"vertex",
"objects",
"at",
"its",
"endpoints",
".",
"This",
"version",
"of",
"the",
"adjacency",
"list",
"uses",
"more",
"memory",
"than",
"the",
"version",
"in",
"which",
"adjacent",
"vertices",
"are",
"listed",
"directly",
"but",
"the",
"existence",
"of",
"explicit",
"edge",
"objects",
"allows",
"it",
"extra",
"flexibility",
"in",
"storing",
"additional",
"information",
"about",
"edges",
".",
"It",
"represents",
"Directed",
"Wighted",
"graph",
"@author",
"Saeed",
"Kayvanfar",
"on",
"7",
"/",
"11",
"/",
"2020",
"."
] |
public class OrientedAdjacencyListGraph<T> implements Graph<T> {
/**
* Could be replaced by array
*/
// private OrientedVertex<T>[] graph;
// private Set<OrientedVertex<T>> graph;
@Point("Instead of using Set, we use map so we can map between value and vertex easily")
private Map<T, OrientedVertex<T>> graph;
public OrientedAdjacencyListGraph() {
graph = new HashMap<>();
}
public boolean contains(T vertex) {
return graph.containsKey(vertex);
}
public boolean areAdjacent(T src, T dest) throws NoSuchVertexException {
OrientedVertex<T> srcVertex = graph.get(src);
OrientedVertex<T> destVertex = graph.get(dest);
if (srcVertex == null || destVertex == null)
throw new NoSuchVertexException();
return srcVertex.hasNeighbor(destVertex);
}
public void addVertex(T info) {
OrientedVertex<T> vertexNode = new OrientedVertex<>(info);
graph.put(info, vertexNode);
}
public void removeVertex(T info) throws NoSuchVertexException {
OrientedVertex<T> vertexNode = graph.get(info);
if (vertexNode == null)
throw new NoSuchVertexException();
Iterator<OrientedVertex<T>> iterator = graph.values().iterator();
while (iterator.hasNext()) {
OrientedVertex<T> possibleLink = iterator.next();
possibleLink.removeEdgeTo(vertexNode);
}
graph.remove(info);
}
public void addEdge(T from, T to, int weight) throws NoSuchVertexException {
OrientedVertex<T> fromVertex = graph.get(from);
OrientedVertex<T> toVertex = graph.get(to);
if (fromVertex == null || toVertex == null)
throw new NoSuchVertexException();
Edge<T> edge = new Edge<>(fromVertex, toVertex, weight);
fromVertex.addEdge(edge);
}
public void removeEdge(T from, T to) throws NoSuchVertexException {
OrientedVertex<T> fromVertex = graph.get(from);
OrientedVertex<T> toVertex = graph.get(to);
if (fromVertex == null || toVertex == null)
throw new NoSuchVertexException();
if (fromVertex.hasNeighbor(toVertex)) {
fromVertex.removeEdgeTo(toVertex);
}
}
public List<T> getNeighborsFor(T vertex) throws NoSuchVertexException {
if (graph.get(vertex) == null)
throw new NoSuchVertexException();
return graph.get(vertex).getNeighbors();
}
/**
* @param start
* @throws NoSuchVertexException
*/
@Override
@BFS
public Collection<T> breathFirstSearch(T start) throws NoSuchVertexException {
if (graph.get(start) == null)
throw new NoSuchVertexException();
Collection<T> visited = new HashSet<>();
visited.add(start);
Queue<T> queue = new ArrayDeque<>();
queue.add(start);
System.out.println(start);
while (!queue.isEmpty()) {
T current = queue.remove();
T neighbor = null;
Iterator<T> iterator = getNeighborsFor(current).iterator();
while (iterator.hasNext()) {
neighbor = iterator.next();
if (!visited.contains(neighbor)) {
visited.add(neighbor);
System.out.println(neighbor);
queue.add(neighbor);
}
}
}
return visited;
}
/**
* @param start
* @throws NoSuchVertexException
*/
@Override
public Collection<T> depthFirstSearch(T start) throws NoSuchVertexException {
if (graph.get(start) == null)
throw new NoSuchVertexException();
Collection<T> visited = new HashSet<>();
visited.add(start);
Stack<T> stack = new Stack<>();
stack.push(start);
System.out.println(start);
while (!stack.empty()) {
T current = stack.peek();
T neighbor = null;
Iterator<T> iterator = getNeighborsFor(current).iterator();
while (iterator.hasNext()) {
neighbor = iterator.next();
if (!visited.contains(neighbor))
break;
}
if (neighbor != null && !visited.contains(neighbor)) {
visited.add(neighbor);
System.out.println(neighbor);
stack.push(neighbor);
} else {
stack.pop();
}
}
return visited;
}
}
|
[
"public",
"class",
"OrientedAdjacencyListGraph",
"<",
"T",
">",
"implements",
"Graph",
"<",
"T",
">",
"{",
"/**\n * Could be replaced by array\n */",
"@",
"Point",
"(",
"\"",
"Instead of using Set, we use map so we can map between value and vertex easily",
"\"",
")",
"private",
"Map",
"<",
"T",
",",
"OrientedVertex",
"<",
"T",
">",
">",
"graph",
";",
"public",
"OrientedAdjacencyListGraph",
"(",
")",
"{",
"graph",
"=",
"new",
"HashMap",
"<",
">",
"(",
")",
";",
"}",
"public",
"boolean",
"contains",
"(",
"T",
"vertex",
")",
"{",
"return",
"graph",
".",
"containsKey",
"(",
"vertex",
")",
";",
"}",
"public",
"boolean",
"areAdjacent",
"(",
"T",
"src",
",",
"T",
"dest",
")",
"throws",
"NoSuchVertexException",
"{",
"OrientedVertex",
"<",
"T",
">",
"srcVertex",
"=",
"graph",
".",
"get",
"(",
"src",
")",
";",
"OrientedVertex",
"<",
"T",
">",
"destVertex",
"=",
"graph",
".",
"get",
"(",
"dest",
")",
";",
"if",
"(",
"srcVertex",
"==",
"null",
"||",
"destVertex",
"==",
"null",
")",
"throw",
"new",
"NoSuchVertexException",
"(",
")",
";",
"return",
"srcVertex",
".",
"hasNeighbor",
"(",
"destVertex",
")",
";",
"}",
"public",
"void",
"addVertex",
"(",
"T",
"info",
")",
"{",
"OrientedVertex",
"<",
"T",
">",
"vertexNode",
"=",
"new",
"OrientedVertex",
"<",
">",
"(",
"info",
")",
";",
"graph",
".",
"put",
"(",
"info",
",",
"vertexNode",
")",
";",
"}",
"public",
"void",
"removeVertex",
"(",
"T",
"info",
")",
"throws",
"NoSuchVertexException",
"{",
"OrientedVertex",
"<",
"T",
">",
"vertexNode",
"=",
"graph",
".",
"get",
"(",
"info",
")",
";",
"if",
"(",
"vertexNode",
"==",
"null",
")",
"throw",
"new",
"NoSuchVertexException",
"(",
")",
";",
"Iterator",
"<",
"OrientedVertex",
"<",
"T",
">",
">",
"iterator",
"=",
"graph",
".",
"values",
"(",
")",
".",
"iterator",
"(",
")",
";",
"while",
"(",
"iterator",
".",
"hasNext",
"(",
")",
")",
"{",
"OrientedVertex",
"<",
"T",
">",
"possibleLink",
"=",
"iterator",
".",
"next",
"(",
")",
";",
"possibleLink",
".",
"removeEdgeTo",
"(",
"vertexNode",
")",
";",
"}",
"graph",
".",
"remove",
"(",
"info",
")",
";",
"}",
"public",
"void",
"addEdge",
"(",
"T",
"from",
",",
"T",
"to",
",",
"int",
"weight",
")",
"throws",
"NoSuchVertexException",
"{",
"OrientedVertex",
"<",
"T",
">",
"fromVertex",
"=",
"graph",
".",
"get",
"(",
"from",
")",
";",
"OrientedVertex",
"<",
"T",
">",
"toVertex",
"=",
"graph",
".",
"get",
"(",
"to",
")",
";",
"if",
"(",
"fromVertex",
"==",
"null",
"||",
"toVertex",
"==",
"null",
")",
"throw",
"new",
"NoSuchVertexException",
"(",
")",
";",
"Edge",
"<",
"T",
">",
"edge",
"=",
"new",
"Edge",
"<",
">",
"(",
"fromVertex",
",",
"toVertex",
",",
"weight",
")",
";",
"fromVertex",
".",
"addEdge",
"(",
"edge",
")",
";",
"}",
"public",
"void",
"removeEdge",
"(",
"T",
"from",
",",
"T",
"to",
")",
"throws",
"NoSuchVertexException",
"{",
"OrientedVertex",
"<",
"T",
">",
"fromVertex",
"=",
"graph",
".",
"get",
"(",
"from",
")",
";",
"OrientedVertex",
"<",
"T",
">",
"toVertex",
"=",
"graph",
".",
"get",
"(",
"to",
")",
";",
"if",
"(",
"fromVertex",
"==",
"null",
"||",
"toVertex",
"==",
"null",
")",
"throw",
"new",
"NoSuchVertexException",
"(",
")",
";",
"if",
"(",
"fromVertex",
".",
"hasNeighbor",
"(",
"toVertex",
")",
")",
"{",
"fromVertex",
".",
"removeEdgeTo",
"(",
"toVertex",
")",
";",
"}",
"}",
"public",
"List",
"<",
"T",
">",
"getNeighborsFor",
"(",
"T",
"vertex",
")",
"throws",
"NoSuchVertexException",
"{",
"if",
"(",
"graph",
".",
"get",
"(",
"vertex",
")",
"==",
"null",
")",
"throw",
"new",
"NoSuchVertexException",
"(",
")",
";",
"return",
"graph",
".",
"get",
"(",
"vertex",
")",
".",
"getNeighbors",
"(",
")",
";",
"}",
"/**\n * @param start\n * @throws NoSuchVertexException\n */",
"@",
"Override",
"@",
"BFS",
"public",
"Collection",
"<",
"T",
">",
"breathFirstSearch",
"(",
"T",
"start",
")",
"throws",
"NoSuchVertexException",
"{",
"if",
"(",
"graph",
".",
"get",
"(",
"start",
")",
"==",
"null",
")",
"throw",
"new",
"NoSuchVertexException",
"(",
")",
";",
"Collection",
"<",
"T",
">",
"visited",
"=",
"new",
"HashSet",
"<",
">",
"(",
")",
";",
"visited",
".",
"add",
"(",
"start",
")",
";",
"Queue",
"<",
"T",
">",
"queue",
"=",
"new",
"ArrayDeque",
"<",
">",
"(",
")",
";",
"queue",
".",
"add",
"(",
"start",
")",
";",
"System",
".",
"out",
".",
"println",
"(",
"start",
")",
";",
"while",
"(",
"!",
"queue",
".",
"isEmpty",
"(",
")",
")",
"{",
"T",
"current",
"=",
"queue",
".",
"remove",
"(",
")",
";",
"T",
"neighbor",
"=",
"null",
";",
"Iterator",
"<",
"T",
">",
"iterator",
"=",
"getNeighborsFor",
"(",
"current",
")",
".",
"iterator",
"(",
")",
";",
"while",
"(",
"iterator",
".",
"hasNext",
"(",
")",
")",
"{",
"neighbor",
"=",
"iterator",
".",
"next",
"(",
")",
";",
"if",
"(",
"!",
"visited",
".",
"contains",
"(",
"neighbor",
")",
")",
"{",
"visited",
".",
"add",
"(",
"neighbor",
")",
";",
"System",
".",
"out",
".",
"println",
"(",
"neighbor",
")",
";",
"queue",
".",
"add",
"(",
"neighbor",
")",
";",
"}",
"}",
"}",
"return",
"visited",
";",
"}",
"/**\n * @param start\n * @throws NoSuchVertexException\n */",
"@",
"Override",
"public",
"Collection",
"<",
"T",
">",
"depthFirstSearch",
"(",
"T",
"start",
")",
"throws",
"NoSuchVertexException",
"{",
"if",
"(",
"graph",
".",
"get",
"(",
"start",
")",
"==",
"null",
")",
"throw",
"new",
"NoSuchVertexException",
"(",
")",
";",
"Collection",
"<",
"T",
">",
"visited",
"=",
"new",
"HashSet",
"<",
">",
"(",
")",
";",
"visited",
".",
"add",
"(",
"start",
")",
";",
"Stack",
"<",
"T",
">",
"stack",
"=",
"new",
"Stack",
"<",
">",
"(",
")",
";",
"stack",
".",
"push",
"(",
"start",
")",
";",
"System",
".",
"out",
".",
"println",
"(",
"start",
")",
";",
"while",
"(",
"!",
"stack",
".",
"empty",
"(",
")",
")",
"{",
"T",
"current",
"=",
"stack",
".",
"peek",
"(",
")",
";",
"T",
"neighbor",
"=",
"null",
";",
"Iterator",
"<",
"T",
">",
"iterator",
"=",
"getNeighborsFor",
"(",
"current",
")",
".",
"iterator",
"(",
")",
";",
"while",
"(",
"iterator",
".",
"hasNext",
"(",
")",
")",
"{",
"neighbor",
"=",
"iterator",
".",
"next",
"(",
")",
";",
"if",
"(",
"!",
"visited",
".",
"contains",
"(",
"neighbor",
")",
")",
"break",
";",
"}",
"if",
"(",
"neighbor",
"!=",
"null",
"&&",
"!",
"visited",
".",
"contains",
"(",
"neighbor",
")",
")",
"{",
"visited",
".",
"add",
"(",
"neighbor",
")",
";",
"System",
".",
"out",
".",
"println",
"(",
"neighbor",
")",
";",
"stack",
".",
"push",
"(",
"neighbor",
")",
";",
"}",
"else",
"{",
"stack",
".",
"pop",
"(",
")",
";",
"}",
"}",
"return",
"visited",
";",
"}",
"}"
] |
simple oriented graph as part of an exercise in both Object Oriented Programming
and Data Structures.
|
[
"simple",
"oriented",
"graph",
"as",
"part",
"of",
"an",
"exercise",
"in",
"both",
"Object",
"Oriented",
"Programming",
"and",
"Data",
"Structures",
"."
] |
[
"// private OrientedVertex<T>[] graph;",
"// private Set<OrientedVertex<T>> graph;"
] |
[
{
"param": "Graph<T>",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "Graph<T>",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 14
| 920
| 179
|
bcfdb4d58da39d3907426c6d77fe913864eeada7
|
jonghough/Subspace
|
src/main/java/arithmetic/Totient.java
|
[
"BSD-2-Clause"
] |
Java
|
Totient
|
/**
* Euler Totient function calculator.
* <i>Totient function</i> is defined for positive integer <i>n</i><br>
* as the number of positive integers less than n which ar ecorpime to<br>
* n.<br>
* e.g. if <code>n=7</code>, then <code>totient(n)</code> is <code>6</code><br>
* because <i>1,2,3,4,5,6</i> are all coprime to <i>7</i>.
*
*/
|
Euler Totient function calculator.
Totient function is defined for positive integer n
as the number of positive integers less than n which ar ecorpime to
n.
e.g. if n=7, then totient(n) is 6
because 1,2,3,4,5,6 are all coprime to 7.
|
[
"Euler",
"Totient",
"function",
"calculator",
".",
"Totient",
"function",
"is",
"defined",
"for",
"positive",
"integer",
"n",
"as",
"the",
"number",
"of",
"positive",
"integers",
"less",
"than",
"n",
"which",
"ar",
"ecorpime",
"to",
"n",
".",
"e",
".",
"g",
".",
"if",
"n",
"=",
"7",
"then",
"totient",
"(",
"n",
")",
"is",
"6",
"because",
"1",
"2",
"3",
"4",
"5",
"6",
"are",
"all",
"coprime",
"to",
"7",
"."
] |
public class Totient {
/**
* Returns totient function fo BigInteger n. Uses Pollard Rho algorithm to
* factor n.<br>
*
* @param n
* BigInteger to factor.
* @return Totient(n), the number of positive integers less than n, which
* <br> are coprime with n.
*/
public static BigInteger totient(BigInteger n) {
if (n.compareTo(BigInteger.ONE) <= 0) {
return BigInteger.ONE;
}
ArrayList<BigInteger> factorList = Factorizor.factor(n, Factorizor.FactorMethod.RHO);
HashMap<BigInteger, Integer> map = HashMapBuilder.toHashMap(factorList);
BigInteger prod = BigInteger.ONE;
Iterator<Entry<BigInteger, Integer>> iter = map.entrySet().iterator();
while (iter.hasNext()) {
Entry<BigInteger, Integer> entry = iter.next();
BigInteger primeVal = (entry.getKey().pow(entry.getValue()))
.subtract(entry.getKey().pow(entry.getValue() - 1));
prod = prod.multiply(primeVal);
}
return prod;
}
}
|
[
"public",
"class",
"Totient",
"{",
"/**\n\t * Returns totient function fo BigInteger n. Uses Pollard Rho algorithm to\n\t * factor n.<br>\n\t * \n\t * @param n\n\t * BigInteger to factor.\n\t * @return Totient(n), the number of positive integers less than n, which\n\t * <br> are coprime with n.\n\t */",
"public",
"static",
"BigInteger",
"totient",
"(",
"BigInteger",
"n",
")",
"{",
"if",
"(",
"n",
".",
"compareTo",
"(",
"BigInteger",
".",
"ONE",
")",
"<=",
"0",
")",
"{",
"return",
"BigInteger",
".",
"ONE",
";",
"}",
"ArrayList",
"<",
"BigInteger",
">",
"factorList",
"=",
"Factorizor",
".",
"factor",
"(",
"n",
",",
"Factorizor",
".",
"FactorMethod",
".",
"RHO",
")",
";",
"HashMap",
"<",
"BigInteger",
",",
"Integer",
">",
"map",
"=",
"HashMapBuilder",
".",
"toHashMap",
"(",
"factorList",
")",
";",
"BigInteger",
"prod",
"=",
"BigInteger",
".",
"ONE",
";",
"Iterator",
"<",
"Entry",
"<",
"BigInteger",
",",
"Integer",
">",
">",
"iter",
"=",
"map",
".",
"entrySet",
"(",
")",
".",
"iterator",
"(",
")",
";",
"while",
"(",
"iter",
".",
"hasNext",
"(",
")",
")",
"{",
"Entry",
"<",
"BigInteger",
",",
"Integer",
">",
"entry",
"=",
"iter",
".",
"next",
"(",
")",
";",
"BigInteger",
"primeVal",
"=",
"(",
"entry",
".",
"getKey",
"(",
")",
".",
"pow",
"(",
"entry",
".",
"getValue",
"(",
")",
")",
")",
".",
"subtract",
"(",
"entry",
".",
"getKey",
"(",
")",
".",
"pow",
"(",
"entry",
".",
"getValue",
"(",
")",
"-",
"1",
")",
")",
";",
"prod",
"=",
"prod",
".",
"multiply",
"(",
"primeVal",
")",
";",
"}",
"return",
"prod",
";",
"}",
"}"
] |
Euler Totient function calculator.
|
[
"Euler",
"Totient",
"function",
"calculator",
"."
] |
[] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 16
| 241
| 121
|
18c6ac9fd2b210f7ba7baf0205a2c57015150aed
|
devragj/devragj.github.io
|
TypeBCD/Tableau.js
|
[
"MIT"
] |
JavaScript
|
Domino
|
/**
* This class stores the information for one domino of the tableau.
* Some objects in the Domino class are not actually domino shape,
* though they do reside in Domino tableaux. B type number tableaux require
* a square with a zero in it in the upper-left corner. Also, sign tableaux
* have 2x2 boxes in them as well as dominos.
*/
|
This class stores the information for one domino of the tableau.
Some objects in the Domino class are not actually domino shape,
though they do reside in Domino tableaux. B type number tableaux require
a square with a zero in it in the upper-left corner. Also, sign tableaux
have 2x2 boxes in them as well as dominos.
|
[
"This",
"class",
"stores",
"the",
"information",
"for",
"one",
"domino",
"of",
"the",
"tableau",
".",
"Some",
"objects",
"in",
"the",
"Domino",
"class",
"are",
"not",
"actually",
"domino",
"shape",
"though",
"they",
"do",
"reside",
"in",
"Domino",
"tableaux",
".",
"B",
"type",
"number",
"tableaux",
"require",
"a",
"square",
"with",
"a",
"zero",
"in",
"it",
"in",
"the",
"upper",
"-",
"left",
"corner",
".",
"Also",
"sign",
"tableaux",
"have",
"2x2",
"boxes",
"in",
"them",
"as",
"well",
"as",
"dominos",
"."
] |
class Domino {
/**
* @param {Object} table
* @param {number|string} table.n - The number occupying the domino. Though,
* in some uses, the domino is occupied by a sign, not a number. In some cases
* the domino is blank, that is, <code>table.n == ''</code>.
* @param {number} table.x - The x-coordinate of the left-most square of the domino in the tableau.
* Zero-based, zero on the left.
* @param {number} table.y - The y-coordinate of the highest square of the domino in the tableau.
* Zero-based, zero on top.
* @param {boolean} [table.horizontal] - If true, the domino is horizontal,
* if false, the domino is vertical.
* @param {boolean} [table.box] - Some members of the Domino class are not actually dominos.
* If table.box is true, then this domino is a 2x2 box.
* @param {boolean} [table.zero] - If table.zero is true, this "domino" is actually a 1x1 square,
* holding a 0, situated in the top-left corner of the tableau.
* @description Exactly one of the optional parameters will be present.
*/
constructor(table) {
/**
* The content of the Domino
* @type {number|string}
*/
this.n = table.n;
/**
* The x-coordinate of the left-most square of the domino
* in the tableau.
* Zero-based, zero on the left.
* @type {number}
*/
this.x = table.x;
/**
* The y-coordinate of the highest square of the domino
* in the tableau.
* Zero-based, zero on top.
* @type {number}
*/
this.y = table.y;
if (table.box) {
/**
* If true, then this "domino" is a 2x2 box.
* @type {boolean|undefined}
*/
this.box = true;
} else if (table.zero) {
/**
* If true, this "domino" is actually a
* 1x1 square, holding a 0,
* situated in the top-left corner of the tableau.
* @type {boolean|undefined}
*/
this.zero = true;
} else {
/**
* If true, the domino is horizontal,
* if false, the domino is vertical.
* @type {boolean|undefined}
*/
this.horizontal = table.horizontal;
}
}
/**
* makes a copy
* @return {Domino}
*/
clone() {
return new Domino(this);
}
/**
* @return {string}
*/
toString() {
let dominoString = "Domino { n: " + this.n + ", x: " + this.x + ", y: " + this.y + ", ";
if (this.box) {
dominoString += "box: true";
} else if (this.zero) {
dominoString += "zero: true";
} else {
dominoString += "horizontal: " + this.horizontal;
}
dominoString += " }";
return dominoString;
}
/**
* Creates a zero "domino", that is, a 1x1 square,
* holding a 0, situated in the top-left corner of the tableau.
* @return {Domino}
*/
static makeZero() {
return new Domino({n: 0, x: 0, y: 0, zero: true});
}
/**
* makes a deep copy of an array of Domino
* @param {Domino[]} dominoList
* @return {Domino[]}
*/
static cloneList(dominoList) {
let newList = [];
dominoList.forEach((domino) => {newList.push(domino.clone())});
return newList;
}
}
|
[
"class",
"Domino",
"{",
"constructor",
"(",
"table",
")",
"{",
"this",
".",
"n",
"=",
"table",
".",
"n",
";",
"this",
".",
"x",
"=",
"table",
".",
"x",
";",
"this",
".",
"y",
"=",
"table",
".",
"y",
";",
"if",
"(",
"table",
".",
"box",
")",
"{",
"this",
".",
"box",
"=",
"true",
";",
"}",
"else",
"if",
"(",
"table",
".",
"zero",
")",
"{",
"this",
".",
"zero",
"=",
"true",
";",
"}",
"else",
"{",
"this",
".",
"horizontal",
"=",
"table",
".",
"horizontal",
";",
"}",
"}",
"clone",
"(",
")",
"{",
"return",
"new",
"Domino",
"(",
"this",
")",
";",
"}",
"toString",
"(",
")",
"{",
"let",
"dominoString",
"=",
"\"Domino { n: \"",
"+",
"this",
".",
"n",
"+",
"\", x: \"",
"+",
"this",
".",
"x",
"+",
"\", y: \"",
"+",
"this",
".",
"y",
"+",
"\", \"",
";",
"if",
"(",
"this",
".",
"box",
")",
"{",
"dominoString",
"+=",
"\"box: true\"",
";",
"}",
"else",
"if",
"(",
"this",
".",
"zero",
")",
"{",
"dominoString",
"+=",
"\"zero: true\"",
";",
"}",
"else",
"{",
"dominoString",
"+=",
"\"horizontal: \"",
"+",
"this",
".",
"horizontal",
";",
"}",
"dominoString",
"+=",
"\" }\"",
";",
"return",
"dominoString",
";",
"}",
"static",
"makeZero",
"(",
")",
"{",
"return",
"new",
"Domino",
"(",
"{",
"n",
":",
"0",
",",
"x",
":",
"0",
",",
"y",
":",
"0",
",",
"zero",
":",
"true",
"}",
")",
";",
"}",
"static",
"cloneList",
"(",
"dominoList",
")",
"{",
"let",
"newList",
"=",
"[",
"]",
";",
"dominoList",
".",
"forEach",
"(",
"(",
"domino",
")",
"=>",
"{",
"newList",
".",
"push",
"(",
"domino",
".",
"clone",
"(",
")",
")",
"}",
")",
";",
"return",
"newList",
";",
"}",
"}"
] |
This class stores the information for one domino of the tableau.
|
[
"This",
"class",
"stores",
"the",
"information",
"for",
"one",
"domino",
"of",
"the",
"tableau",
"."
] |
[
"/**\n * @param {Object} table\n * @param {number|string} table.n - The number occupying the domino. Though,\n * in some uses, the domino is occupied by a sign, not a number. In some cases\n * the domino is blank, that is, <code>table.n == ''</code>.\n * @param {number} table.x - The x-coordinate of the left-most square of the domino in the tableau.\n * Zero-based, zero on the left.\n * @param {number} table.y - The y-coordinate of the highest square of the domino in the tableau.\n * Zero-based, zero on top.\n * @param {boolean} [table.horizontal] - If true, the domino is horizontal,\n * if false, the domino is vertical.\n * @param {boolean} [table.box] - Some members of the Domino class are not actually dominos.\n * If table.box is true, then this domino is a 2x2 box.\n * @param {boolean} [table.zero] - If table.zero is true, this \"domino\" is actually a 1x1 square,\n * holding a 0, situated in the top-left corner of the tableau.\n * @description Exactly one of the optional parameters will be present.\n */",
"/**\n * The content of the Domino\n * @type {number|string}\n */",
"/**\n * The x-coordinate of the left-most square of the domino\n * in the tableau.\n * Zero-based, zero on the left.\n * @type {number}\n */",
"/**\n * The y-coordinate of the highest square of the domino\n * in the tableau.\n * Zero-based, zero on top.\n * @type {number}\n */",
"/**\n * If true, then this \"domino\" is a 2x2 box.\n * @type {boolean|undefined}\n */",
"/**\n * If true, this \"domino\" is actually a\n * 1x1 square, holding a 0,\n * situated in the top-left corner of the tableau.\n * @type {boolean|undefined}\n */",
"/**\n * If true, the domino is horizontal,\n * if false, the domino is vertical.\n * @type {boolean|undefined}\n */",
"/**\n * makes a copy\n * @return {Domino}\n */",
"/**\n * @return {string}\n */",
"/**\n * Creates a zero \"domino\", that is, a 1x1 square,\n * holding a 0, situated in the top-left corner of the tableau.\n * @return {Domino}\n */",
"/**\n * makes a deep copy of an array of Domino\n * @param {Domino[]} dominoList\n * @return {Domino[]}\n */"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 15
| 890
| 84
|
bb76ee28fbfb714dd847d0edb89e0309fafcc07d
|
Tatetaylor/kbplumbapp
|
jasperreports-5.6.0/src/net/sf/jasperreports/engine/JRPropertiesMap.java
|
[
"Apache-2.0"
] |
Java
|
JRPropertiesMap
|
/**
* Properties map of an JR element.
* <p/>
* The order of the properties (obtained by {@link #getPropertyNames() getPropertyNames()}
* is the same as the order in which the properties were added.
*
* @author Lucian Chirita ([email protected])
* @version $Id: JRPropertiesMap.java 6168 2013-05-16 17:27:14Z lucianc $
*/
|
Properties map of an JR element.
The order of the properties (obtained by #getPropertyNames() getPropertyNames()
is the same as the order in which the properties were added.
@author Lucian Chirita ([email protected])
@version $Id: JRPropertiesMap.java 6168 2013-05-16 17:27:14Z lucianc $
|
[
"Properties",
"map",
"of",
"an",
"JR",
"element",
".",
"The",
"order",
"of",
"the",
"properties",
"(",
"obtained",
"by",
"#getPropertyNames",
"()",
"getPropertyNames",
"()",
"is",
"the",
"same",
"as",
"the",
"order",
"in",
"which",
"the",
"properties",
"were",
"added",
".",
"@author",
"Lucian",
"Chirita",
"(",
"lucianc@users",
".",
"sourceforge",
".",
"net",
")",
"@version",
"$Id",
":",
"JRPropertiesMap",
".",
"java",
"6168",
"2013",
"-",
"05",
"-",
"16",
"17",
":",
"27",
":",
"14Z",
"lucianc",
"$"
] |
public class JRPropertiesMap implements Serializable, Cloneable
{
private static final long serialVersionUID = JRConstants.SERIAL_VERSION_UID;
private static final Log log = LogFactory.getLog(JRPropertiesMap.class);
public static final String PROPERTY_VALUE = "value";
private Map<String, String> propertiesMap;
private List<String> propertiesList;
private JRPropertiesMap base;
/**
* Creates a properties map.
*/
public JRPropertiesMap()
{
}
/**
* Clones a properties map.
*
* @param propertiesMap the original properties map
*/
public JRPropertiesMap(JRPropertiesMap propertiesMap)
{
this();
this.base = propertiesMap.base;
//this copies all properties from base to this instance
//FIXME in some cases we might want to keep the properties in base
String[] propertyNames = propertiesMap.getPropertyNames();
if (propertyNames != null && propertyNames.length > 0)
{
for(int i = 0; i < propertyNames.length; i++)
{
setProperty(propertyNames[i], propertiesMap.getProperty(propertyNames[i]));
}
}
}
protected synchronized void ensureInit()
{
if (propertiesMap == null)
{
init();
}
}
private void init()
{
// start with small collections
propertiesMap = new HashMap<String, String>(4, 0.75f);
propertiesList = new ArrayList<String>(2);
}
/**
* Returns the names of the properties.
*
* @return the names of the properties
*/
public String[] getPropertyNames()
{
String[] names;
if (hasOwnProperties())
{
if (base == null)
{
names = propertiesList.toArray(new String[propertiesList.size()]);
}
else
{
LinkedHashSet<String> namesSet = new LinkedHashSet<String>();
collectPropertyNames(namesSet);
names = namesSet.toArray(new String[namesSet.size()]);
}
}
else if (base != null)
{
names = base.getPropertyNames();
}
else
{
names = new String[0];
}
return names;
}
public String[] getOwnPropertyNames()
{
String[] names;
if (hasOwnProperties())
{
names = propertiesList.toArray(new String[propertiesList.size()]);
}
else
{
names = new String[0];
}
return names;
}
protected void collectPropertyNames(Collection<String> names)
{
if (base != null)
{
base.collectPropertyNames(names);
}
if (propertiesList != null)
{
names.addAll(propertiesList);
}
}
/**
* Returns the value of a property.
*
* @param propName the name of the property
* @return the value
*/
public String getProperty(String propName)
{
String val;
if (hasOwnProperty(propName))
{
val = getOwnProperty(propName);
}
else if (base != null)
{
val = base.getProperty(propName);
}
else
{
val = null;
}
return val;
}
/**
* Decides whether the map contains a specified property.
*
* The method returns true even if the property value is null.
*
* @param propName the property name
* @return <code>true</code> if and only if the map contains the property
*/
public boolean containsProperty(String propName)
{
return hasOwnProperty(propName)
|| base != null && base.containsProperty(propName);
}
protected boolean hasOwnProperty(String propName)
{
return propertiesMap != null && propertiesMap.containsKey(propName);
}
protected String getOwnProperty(String propName)
{
return propertiesMap != null ? (String) propertiesMap.get(propName) : null;
}
/**
* Adds/sets a property value.
*
* @param propName the name of the property
* @param value the value of the property
*/
public void setProperty(String propName, String value)
{
Object old = getOwnProperty(propName);
ensureInit();
if (!hasOwnProperty(propName))
{
propertiesList.add(propName);
}
propertiesMap.put(propName, value);
if (hasEventSupport())
{
getEventSupport().firePropertyChange(PROPERTY_VALUE, old, value);
}
}
/**
* Removes a property.
*
* @param propName the property name
*/
public void removeProperty(String propName)
{
//FIXME base properties?
if (hasOwnProperty(propName))
{
propertiesList.remove(propName);
propertiesMap.remove(propName);
}
}
/**
* Clones this property map.
*
* @return a clone of this property map
*/
public JRPropertiesMap cloneProperties()
{
return new JRPropertiesMap(this);
}
/**
*
*/
public Object clone()
{
return this.cloneProperties();
}
public String toString()
{
return propertiesMap == null ? "" : propertiesMap.toString();
}
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException
{
in.defaultReadObject();
if (propertiesList == null && propertiesMap != null)// an instance from an old version has been deserialized
{
//recreate the properties list and map
propertiesList = new ArrayList<String>(propertiesMap.keySet());
propertiesMap = new HashMap<String, String>(propertiesMap);
}
}
/**
* Checks whether there are any properties.
*
* @return whether there are any properties
*/
public boolean hasProperties()
{
return hasOwnProperties()
|| base != null && base.hasProperties();
}
public boolean isEmpty()
{
// only checking base for null and not whether base has any properties
return !hasOwnProperties() && base == null;
}
/**
* Checks whether this object has properties of its own
* (i.e. not inherited from the base properties).
*
* @return whether this object has properties of its own
* @see #setBaseProperties(JRPropertiesMap)
*/
public boolean hasOwnProperties()
{
return propertiesList != null && !propertiesList.isEmpty();
}
/**
* Clones the properties map of a properties holder.
* If the holder does not have any properties, null is returned.
*
* @param propertiesHolder the properties holder
* @return a clone of the holder's properties map, or <code>null</code>
* if the holder does not have any properties
*/
public static JRPropertiesMap getPropertiesClone(JRPropertiesHolder propertiesHolder)
{
JRPropertiesMap clone;
if (propertiesHolder.hasProperties())
{
clone = propertiesHolder.getPropertiesMap().cloneProperties();
}
else
{
clone = null;
}
return clone;
}
/**
* Returns the base properties map, if any.
*
* @return the base properties map
* @see #setBaseProperties(JRPropertiesMap)
*/
public JRPropertiesMap getBaseProperties()
{
return base;
}
/**
* Sets the base properties map.
*
* <p>
* The base properties map are used as base/default properties for this
* instance. All of the {@link #containsProperty(String)},
* {@link #getProperty(String)}, {@link #getPropertyNames()} and
* {@link #hasProperties()} methods include base properties as well.
* </p>
*
* @param base the base properties map
*/
public void setBaseProperties(JRPropertiesMap base)
{
this.base = base;
}
/**
* Loads a properties file from a location.
*
* @param location the properties file URL
* @return the properties file loaded as a in-memory properties map
*/
public static JRPropertiesMap loadProperties(URL location)
{
boolean close = true;
InputStream stream = null;
try
{
stream = location.openStream();
Properties props = new Properties();
props.load(stream);
close = false;
stream.close();
JRPropertiesMap properties = new JRPropertiesMap();
for (Enumeration<?> names = props.propertyNames(); names.hasMoreElements(); )
{
String name = (String) names.nextElement();
String value = props.getProperty(name);
properties.setProperty(name, value);
}
return properties;
}
catch (IOException e)
{
throw new JRRuntimeException(e);
}
finally
{
if (close && stream != null)
{
try
{
stream.close();
}
catch (IOException e)
{
if (log.isWarnEnabled())
{
log.warn("Error closing stream for " + location, e);
}
}
}
}
}
private transient JRPropertyChangeSupport eventSupport;
protected boolean hasEventSupport()
{
return eventSupport != null;
}
public JRPropertyChangeSupport getEventSupport()
{
synchronized (this)
{
if (eventSupport == null)
{
eventSupport = new JRPropertyChangeSupport(this);
}
}
return eventSupport;
}
}
|
[
"public",
"class",
"JRPropertiesMap",
"implements",
"Serializable",
",",
"Cloneable",
"{",
"private",
"static",
"final",
"long",
"serialVersionUID",
"=",
"JRConstants",
".",
"SERIAL_VERSION_UID",
";",
"private",
"static",
"final",
"Log",
"log",
"=",
"LogFactory",
".",
"getLog",
"(",
"JRPropertiesMap",
".",
"class",
")",
";",
"public",
"static",
"final",
"String",
"PROPERTY_VALUE",
"=",
"\"",
"value",
"\"",
";",
"private",
"Map",
"<",
"String",
",",
"String",
">",
"propertiesMap",
";",
"private",
"List",
"<",
"String",
">",
"propertiesList",
";",
"private",
"JRPropertiesMap",
"base",
";",
"/**\n\t * Creates a properties map.\n\t */",
"public",
"JRPropertiesMap",
"(",
")",
"{",
"}",
"/**\n\t * Clones a properties map.\n\t * \n\t * @param propertiesMap the original properties map\n\t */",
"public",
"JRPropertiesMap",
"(",
"JRPropertiesMap",
"propertiesMap",
")",
"{",
"this",
"(",
")",
";",
"this",
".",
"base",
"=",
"propertiesMap",
".",
"base",
";",
"String",
"[",
"]",
"propertyNames",
"=",
"propertiesMap",
".",
"getPropertyNames",
"(",
")",
";",
"if",
"(",
"propertyNames",
"!=",
"null",
"&&",
"propertyNames",
".",
"length",
">",
"0",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"propertyNames",
".",
"length",
";",
"i",
"++",
")",
"{",
"setProperty",
"(",
"propertyNames",
"[",
"i",
"]",
",",
"propertiesMap",
".",
"getProperty",
"(",
"propertyNames",
"[",
"i",
"]",
")",
")",
";",
"}",
"}",
"}",
"protected",
"synchronized",
"void",
"ensureInit",
"(",
")",
"{",
"if",
"(",
"propertiesMap",
"==",
"null",
")",
"{",
"init",
"(",
")",
";",
"}",
"}",
"private",
"void",
"init",
"(",
")",
"{",
"propertiesMap",
"=",
"new",
"HashMap",
"<",
"String",
",",
"String",
">",
"(",
"4",
",",
"0.75f",
")",
";",
"propertiesList",
"=",
"new",
"ArrayList",
"<",
"String",
">",
"(",
"2",
")",
";",
"}",
"/**\n\t * Returns the names of the properties.\n\t * \n\t * @return the names of the properties\n\t */",
"public",
"String",
"[",
"]",
"getPropertyNames",
"(",
")",
"{",
"String",
"[",
"]",
"names",
";",
"if",
"(",
"hasOwnProperties",
"(",
")",
")",
"{",
"if",
"(",
"base",
"==",
"null",
")",
"{",
"names",
"=",
"propertiesList",
".",
"toArray",
"(",
"new",
"String",
"[",
"propertiesList",
".",
"size",
"(",
")",
"]",
")",
";",
"}",
"else",
"{",
"LinkedHashSet",
"<",
"String",
">",
"namesSet",
"=",
"new",
"LinkedHashSet",
"<",
"String",
">",
"(",
")",
";",
"collectPropertyNames",
"(",
"namesSet",
")",
";",
"names",
"=",
"namesSet",
".",
"toArray",
"(",
"new",
"String",
"[",
"namesSet",
".",
"size",
"(",
")",
"]",
")",
";",
"}",
"}",
"else",
"if",
"(",
"base",
"!=",
"null",
")",
"{",
"names",
"=",
"base",
".",
"getPropertyNames",
"(",
")",
";",
"}",
"else",
"{",
"names",
"=",
"new",
"String",
"[",
"0",
"]",
";",
"}",
"return",
"names",
";",
"}",
"public",
"String",
"[",
"]",
"getOwnPropertyNames",
"(",
")",
"{",
"String",
"[",
"]",
"names",
";",
"if",
"(",
"hasOwnProperties",
"(",
")",
")",
"{",
"names",
"=",
"propertiesList",
".",
"toArray",
"(",
"new",
"String",
"[",
"propertiesList",
".",
"size",
"(",
")",
"]",
")",
";",
"}",
"else",
"{",
"names",
"=",
"new",
"String",
"[",
"0",
"]",
";",
"}",
"return",
"names",
";",
"}",
"protected",
"void",
"collectPropertyNames",
"(",
"Collection",
"<",
"String",
">",
"names",
")",
"{",
"if",
"(",
"base",
"!=",
"null",
")",
"{",
"base",
".",
"collectPropertyNames",
"(",
"names",
")",
";",
"}",
"if",
"(",
"propertiesList",
"!=",
"null",
")",
"{",
"names",
".",
"addAll",
"(",
"propertiesList",
")",
";",
"}",
"}",
"/**\n\t * Returns the value of a property.\n\t * \n\t * @param propName the name of the property\n\t * @return the value\n\t */",
"public",
"String",
"getProperty",
"(",
"String",
"propName",
")",
"{",
"String",
"val",
";",
"if",
"(",
"hasOwnProperty",
"(",
"propName",
")",
")",
"{",
"val",
"=",
"getOwnProperty",
"(",
"propName",
")",
";",
"}",
"else",
"if",
"(",
"base",
"!=",
"null",
")",
"{",
"val",
"=",
"base",
".",
"getProperty",
"(",
"propName",
")",
";",
"}",
"else",
"{",
"val",
"=",
"null",
";",
"}",
"return",
"val",
";",
"}",
"/**\n\t * Decides whether the map contains a specified property.\n\t * \n\t * The method returns true even if the property value is null.\n\t * \n\t * @param propName the property name\n\t * @return <code>true</code> if and only if the map contains the property\n\t */",
"public",
"boolean",
"containsProperty",
"(",
"String",
"propName",
")",
"{",
"return",
"hasOwnProperty",
"(",
"propName",
")",
"||",
"base",
"!=",
"null",
"&&",
"base",
".",
"containsProperty",
"(",
"propName",
")",
";",
"}",
"protected",
"boolean",
"hasOwnProperty",
"(",
"String",
"propName",
")",
"{",
"return",
"propertiesMap",
"!=",
"null",
"&&",
"propertiesMap",
".",
"containsKey",
"(",
"propName",
")",
";",
"}",
"protected",
"String",
"getOwnProperty",
"(",
"String",
"propName",
")",
"{",
"return",
"propertiesMap",
"!=",
"null",
"?",
"(",
"String",
")",
"propertiesMap",
".",
"get",
"(",
"propName",
")",
":",
"null",
";",
"}",
"/**\n\t * Adds/sets a property value.\n\t * \n\t * @param propName the name of the property\n\t * @param value the value of the property\n\t */",
"public",
"void",
"setProperty",
"(",
"String",
"propName",
",",
"String",
"value",
")",
"{",
"Object",
"old",
"=",
"getOwnProperty",
"(",
"propName",
")",
";",
"ensureInit",
"(",
")",
";",
"if",
"(",
"!",
"hasOwnProperty",
"(",
"propName",
")",
")",
"{",
"propertiesList",
".",
"add",
"(",
"propName",
")",
";",
"}",
"propertiesMap",
".",
"put",
"(",
"propName",
",",
"value",
")",
";",
"if",
"(",
"hasEventSupport",
"(",
")",
")",
"{",
"getEventSupport",
"(",
")",
".",
"firePropertyChange",
"(",
"PROPERTY_VALUE",
",",
"old",
",",
"value",
")",
";",
"}",
"}",
"/**\n\t * Removes a property.\n\t * \n\t * @param propName the property name\n\t */",
"public",
"void",
"removeProperty",
"(",
"String",
"propName",
")",
"{",
"if",
"(",
"hasOwnProperty",
"(",
"propName",
")",
")",
"{",
"propertiesList",
".",
"remove",
"(",
"propName",
")",
";",
"propertiesMap",
".",
"remove",
"(",
"propName",
")",
";",
"}",
"}",
"/**\n\t * Clones this property map.\n\t * \n\t * @return a clone of this property map\n\t */",
"public",
"JRPropertiesMap",
"cloneProperties",
"(",
")",
"{",
"return",
"new",
"JRPropertiesMap",
"(",
"this",
")",
";",
"}",
"/**\n\t *\n\t */",
"public",
"Object",
"clone",
"(",
")",
"{",
"return",
"this",
".",
"cloneProperties",
"(",
")",
";",
"}",
"public",
"String",
"toString",
"(",
")",
"{",
"return",
"propertiesMap",
"==",
"null",
"?",
"\"",
"\"",
":",
"propertiesMap",
".",
"toString",
"(",
")",
";",
"}",
"private",
"void",
"readObject",
"(",
"java",
".",
"io",
".",
"ObjectInputStream",
"in",
")",
"throws",
"IOException",
",",
"ClassNotFoundException",
"{",
"in",
".",
"defaultReadObject",
"(",
")",
";",
"if",
"(",
"propertiesList",
"==",
"null",
"&&",
"propertiesMap",
"!=",
"null",
")",
"{",
"propertiesList",
"=",
"new",
"ArrayList",
"<",
"String",
">",
"(",
"propertiesMap",
".",
"keySet",
"(",
")",
")",
";",
"propertiesMap",
"=",
"new",
"HashMap",
"<",
"String",
",",
"String",
">",
"(",
"propertiesMap",
")",
";",
"}",
"}",
"/**\n\t * Checks whether there are any properties.\n\t * \n\t * @return whether there are any properties\n\t */",
"public",
"boolean",
"hasProperties",
"(",
")",
"{",
"return",
"hasOwnProperties",
"(",
")",
"||",
"base",
"!=",
"null",
"&&",
"base",
".",
"hasProperties",
"(",
")",
";",
"}",
"public",
"boolean",
"isEmpty",
"(",
")",
"{",
"return",
"!",
"hasOwnProperties",
"(",
")",
"&&",
"base",
"==",
"null",
";",
"}",
"/**\n\t * Checks whether this object has properties of its own\n\t * (i.e. not inherited from the base properties).\n\t * \n\t * @return whether this object has properties of its own\n\t * @see #setBaseProperties(JRPropertiesMap)\n\t */",
"public",
"boolean",
"hasOwnProperties",
"(",
")",
"{",
"return",
"propertiesList",
"!=",
"null",
"&&",
"!",
"propertiesList",
".",
"isEmpty",
"(",
")",
";",
"}",
"/**\n\t * Clones the properties map of a properties holder.\n\t * If the holder does not have any properties, null is returned.\n\t * \n\t * @param propertiesHolder the properties holder\n\t * @return a clone of the holder's properties map, or <code>null</code>\n\t * if the holder does not have any properties\n\t */",
"public",
"static",
"JRPropertiesMap",
"getPropertiesClone",
"(",
"JRPropertiesHolder",
"propertiesHolder",
")",
"{",
"JRPropertiesMap",
"clone",
";",
"if",
"(",
"propertiesHolder",
".",
"hasProperties",
"(",
")",
")",
"{",
"clone",
"=",
"propertiesHolder",
".",
"getPropertiesMap",
"(",
")",
".",
"cloneProperties",
"(",
")",
";",
"}",
"else",
"{",
"clone",
"=",
"null",
";",
"}",
"return",
"clone",
";",
"}",
"/**\n\t * Returns the base properties map, if any.\n\t * \n\t * @return the base properties map\n\t * @see #setBaseProperties(JRPropertiesMap)\n\t */",
"public",
"JRPropertiesMap",
"getBaseProperties",
"(",
")",
"{",
"return",
"base",
";",
"}",
"/**\n\t * Sets the base properties map.\n\t * \n\t * <p>\n\t * The base properties map are used as base/default properties for this\n\t * instance. All of the {@link #containsProperty(String)}, \n\t * {@link #getProperty(String)}, {@link #getPropertyNames()} and \n\t * {@link #hasProperties()} methods include base properties as well.\n\t * </p>\n\t * \n\t * @param base the base properties map\n\t */",
"public",
"void",
"setBaseProperties",
"(",
"JRPropertiesMap",
"base",
")",
"{",
"this",
".",
"base",
"=",
"base",
";",
"}",
"/**\n\t * Loads a properties file from a location.\n\t * \n\t * @param location the properties file URL\n\t * @return the properties file loaded as a in-memory properties map\n\t */",
"public",
"static",
"JRPropertiesMap",
"loadProperties",
"(",
"URL",
"location",
")",
"{",
"boolean",
"close",
"=",
"true",
";",
"InputStream",
"stream",
"=",
"null",
";",
"try",
"{",
"stream",
"=",
"location",
".",
"openStream",
"(",
")",
";",
"Properties",
"props",
"=",
"new",
"Properties",
"(",
")",
";",
"props",
".",
"load",
"(",
"stream",
")",
";",
"close",
"=",
"false",
";",
"stream",
".",
"close",
"(",
")",
";",
"JRPropertiesMap",
"properties",
"=",
"new",
"JRPropertiesMap",
"(",
")",
";",
"for",
"(",
"Enumeration",
"<",
"?",
">",
"names",
"=",
"props",
".",
"propertyNames",
"(",
")",
";",
"names",
".",
"hasMoreElements",
"(",
")",
";",
")",
"{",
"String",
"name",
"=",
"(",
"String",
")",
"names",
".",
"nextElement",
"(",
")",
";",
"String",
"value",
"=",
"props",
".",
"getProperty",
"(",
"name",
")",
";",
"properties",
".",
"setProperty",
"(",
"name",
",",
"value",
")",
";",
"}",
"return",
"properties",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"JRRuntimeException",
"(",
"e",
")",
";",
"}",
"finally",
"{",
"if",
"(",
"close",
"&&",
"stream",
"!=",
"null",
")",
"{",
"try",
"{",
"stream",
".",
"close",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"if",
"(",
"log",
".",
"isWarnEnabled",
"(",
")",
")",
"{",
"log",
".",
"warn",
"(",
"\"",
"Error closing stream for ",
"\"",
"+",
"location",
",",
"e",
")",
";",
"}",
"}",
"}",
"}",
"}",
"private",
"transient",
"JRPropertyChangeSupport",
"eventSupport",
";",
"protected",
"boolean",
"hasEventSupport",
"(",
")",
"{",
"return",
"eventSupport",
"!=",
"null",
";",
"}",
"public",
"JRPropertyChangeSupport",
"getEventSupport",
"(",
")",
"{",
"synchronized",
"(",
"this",
")",
"{",
"if",
"(",
"eventSupport",
"==",
"null",
")",
"{",
"eventSupport",
"=",
"new",
"JRPropertyChangeSupport",
"(",
"this",
")",
";",
"}",
"}",
"return",
"eventSupport",
";",
"}",
"}"
] |
Properties map of an JR element.
|
[
"Properties",
"map",
"of",
"an",
"JR",
"element",
"."
] |
[
"//this copies all properties from base to this instance",
"//FIXME in some cases we might want to keep the properties in base",
"// start with small collections",
"//FIXME base properties?",
"// an instance from an old version has been deserialized",
"//recreate the properties list and map",
"// only checking base for null and not whether base has any properties"
] |
[
{
"param": "Serializable, Cloneable",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "Serializable, Cloneable",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 20
| 2,101
| 108
|
88f449d8550ae38a00456afa7c49ba15c9a54e1c
|
arnonax/TestEssentials
|
TestAutomationEssentials.MSTest/AssertsAggregator.cs
|
[
"MIT"
] |
C#
|
AssertsAggregator
|
/// <summary>
/// Performs a sequence of assertions, reporting the results of all of them indenpendently from one another
/// </summary>
/// <remarks>
/// <para>
/// In most cases, after one assertion fails, the test should stop and not continue to the rest of the test. However, there are cases
/// where a test should few related things, even though each can fail indenpendently from one anther. In this case, you can use this class
/// to make sure you get the results of all the assertions and only the first one that fails. For example, If the test should assert that
/// a message box appears with certain text, certain title and a certain icon - each of these assertions are independent from one another
/// even though they validate the result of the same operation.
/// </para>
/// <para>
/// This class evaluates and writes the result of each assertion to the log, immediately when one of the assertion methods is called, but
/// throws an <see cref="AssertFailedException"/> only when <see cref="Dispose"/> is called if one or more assertions have failed. Normally,
/// instead of calling <see cref="Dispose"/> directly, you would use the <code>using</code> keyword.
/// </para>
/// </remarks>
/// <example>
/// using(var asserts = new AssertsAggregator("Message Box")
/// {
/// asserts.AreEqual("Add customer", () => messageBox.Title, "Title");
/// asserts.AreEqual("The customer you tried to add already exists", () => messageBox.Text, "Text");
/// asserts.AreEqual(MessageBoxIcon.Error, () => messageBox.Icon, "Icon");
/// }
/// </example>
|
Performs a sequence of assertions, reporting the results of all of them indenpendently from one another
|
[
"Performs",
"a",
"sequence",
"of",
"assertions",
"reporting",
"the",
"results",
"of",
"all",
"of",
"them",
"indenpendently",
"from",
"one",
"another"
] |
public class AssertsAggregator : IDisposable
{
private readonly string _description;
private bool _failed;
private readonly IDisposable _loggerSection;
public AssertsAggregator(string description)
{
if (description == null)
throw new ArgumentNullException("description");
_description = description;
_loggerSection = Logger.StartSection("Verifying: {0}", description);
}
[ExcludeFromCodeCoverage]
public void Dispose()
{
try
{
if (!_failed)
return;
Assert.Fail("Verfying '{0}' failed. See log for details.", _description);
}
finally
{
_loggerSection.Dispose();
}
}
public void AreEqual<T>(T expected, Func<T> getActual, string validationMessage, params object[] args)
{
Try(() =>
{
LoggerAssert.AreEqual(expected, getActual(), validationMessage, args);
});
}
public void IsTrue(Func<bool> condition, string validationMessage, params object[] args)
{
Try(() =>
{
LoggerAssert.IsTrue(condition(), validationMessage, args);
});
}
[ExcludeFromCodeCoverage]
private void Try(Action action)
{
try
{
action();
}
catch (Exception ex)
{
_failed = true;
Logger.WriteLine("Assertion fail: " + ex);
}
}
}
|
[
"public",
"class",
"AssertsAggregator",
":",
"IDisposable",
"{",
"private",
"readonly",
"string",
"_description",
";",
"private",
"bool",
"_failed",
";",
"private",
"readonly",
"IDisposable",
"_loggerSection",
";",
"public",
"AssertsAggregator",
"(",
"string",
"description",
")",
"{",
"if",
"(",
"description",
"==",
"null",
")",
"throw",
"new",
"ArgumentNullException",
"(",
"\"",
"description",
"\"",
")",
";",
"_description",
"=",
"description",
";",
"_loggerSection",
"=",
"Logger",
".",
"StartSection",
"(",
"\"",
"Verifying: {0}",
"\"",
",",
"description",
")",
";",
"}",
"[",
"ExcludeFromCodeCoverage",
"]",
"public",
"void",
"Dispose",
"(",
")",
"{",
"try",
"{",
"if",
"(",
"!",
"_failed",
")",
"return",
";",
"Assert",
".",
"Fail",
"(",
"\"",
"Verfying '{0}' failed. See log for details.",
"\"",
",",
"_description",
")",
";",
"}",
"finally",
"{",
"_loggerSection",
".",
"Dispose",
"(",
")",
";",
"}",
"}",
"public",
"void",
"AreEqual",
"<",
"T",
">",
"(",
"T",
"expected",
",",
"Func",
"<",
"T",
">",
"getActual",
",",
"string",
"validationMessage",
",",
"params",
"object",
"[",
"]",
"args",
")",
"{",
"Try",
"(",
"(",
")",
"=>",
"{",
"LoggerAssert",
".",
"AreEqual",
"(",
"expected",
",",
"getActual",
"(",
")",
",",
"validationMessage",
",",
"args",
")",
";",
"}",
")",
";",
"}",
"public",
"void",
"IsTrue",
"(",
"Func",
"<",
"bool",
">",
"condition",
",",
"string",
"validationMessage",
",",
"params",
"object",
"[",
"]",
"args",
")",
"{",
"Try",
"(",
"(",
")",
"=>",
"{",
"LoggerAssert",
".",
"IsTrue",
"(",
"condition",
"(",
")",
",",
"validationMessage",
",",
"args",
")",
";",
"}",
")",
";",
"}",
"[",
"ExcludeFromCodeCoverage",
"]",
"private",
"void",
"Try",
"(",
"Action",
"action",
")",
"{",
"try",
"{",
"action",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"ex",
")",
"{",
"_failed",
"=",
"true",
";",
"Logger",
".",
"WriteLine",
"(",
"\"",
"Assertion fail: ",
"\"",
"+",
"ex",
")",
";",
"}",
"}",
"}"
] |
Performs a sequence of assertions, reporting the results of all of them indenpendently from one another
|
[
"Performs",
"a",
"sequence",
"of",
"assertions",
"reporting",
"the",
"results",
"of",
"all",
"of",
"them",
"indenpendently",
"from",
"one",
"another"
] |
[
"/// <summary>",
"/// Initializes a new instance of <see cref=\"AssertsAggregator\"/> with the spcified description that is written to the log",
"/// </summary>",
"/// <param name=\"description\">The description for the section that is written to the log</param>",
"/// <summary>",
"/// Closes the evaluation section in the log and thrown an <see cref=\"AssertFailedException\"/> if one of the assertions in it failed.",
"/// </summary>",
"/// <exception cref=\"AssertFailedException\">One or more of the assertions in the scope failed</exception>",
"/// <summary>",
"/// Verifies that the actual value matches the expected one",
"/// </summary>",
"/// <param name=\"expected\">The expected value</param>",
"/// <param name=\"getActual\">A delegate to a method that returns the actual value</param>",
"/// <param name=\"validationMessage\">The message that describes the validation, to be written in the log and to be reported in case of a failure</param>",
"/// <param name=\"args\">Additional format arguments to <paramref name=\"validationMessage\"/></param>",
"/// <typeparam name=\"T\">The type of the value to compare</typeparam>",
"/// <remarks>",
"/// This method calls the method delegated by <paramref name=\"getActual\"/> inside a try/catch clause, so that if either the comparison",
"/// failed or the <paramref name=\"getActual\"/> method failed, the program continues (mainly to reach the next assertions). The ",
"/// assertion's result is written to the log (whether it succeeded or failed), and only after <see cref=\"Dispose\"/> is called, an",
"/// <see cref=\"AssertFailedException\"/> exception will be thrown.",
"/// </remarks>",
"/// <summary>",
"/// Verifies the the specified condition is true",
"/// </summary>",
"/// <param name=\"condition\">A delegate to a method that evaluates the condition</param>",
"/// <param name=\"validationMessage\">The message that describes the validation, to be written in the log and to be reported in case of a failure</param>",
"/// <param name=\"args\">Additional format arguments to <paramref name=\"validationMessage\"/></param>",
"/// <remarks>",
"/// This method calls the method delegated by <paramref name=\"condition\"/> inside a try/catch clause, so that if either it returns",
"/// false or if fails, the program continues (mainly to reach the next assertions). The assertion's result is written to the log ",
"/// (whether it succeeded or failed), and only after <see cref=\"Dispose\"/> is called, an <see cref=\"AssertFailedException\"/> exception ",
"/// will be thrown.",
"/// </remarks>"
] |
[
{
"param": "IDisposable",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "IDisposable",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": [
{
"identifier": "remarks",
"docstring": "In most cases, after one assertion fails, the test should stop and not continue to the rest of the test. However, there are cases\nwhere a test should few related things, even though each can fail indenpendently from one anther. In this case, you can use this class\nto make sure you get the results of all the assertions and only the first one that fails. For example, If the test should assert that\na message box appears with certain text, certain title and a certain icon - each of these assertions are independent from one another\neven though they validate the result of the same operation.\n\nThis class evaluates and writes the result of each assertion to the log, immediately when one of the assertion methods is called, but\nthrows an only when is called if one or more assertions have failed. Normally,\ninstead of calling directly, you would use the using",
"docstring_tokens": [
"In",
"most",
"cases",
"after",
"one",
"assertion",
"fails",
"the",
"test",
"should",
"stop",
"and",
"not",
"continue",
"to",
"the",
"rest",
"of",
"the",
"test",
".",
"However",
"there",
"are",
"cases",
"where",
"a",
"test",
"should",
"few",
"related",
"things",
"even",
"though",
"each",
"can",
"fail",
"indenpendently",
"from",
"one",
"anther",
".",
"In",
"this",
"case",
"you",
"can",
"use",
"this",
"class",
"to",
"make",
"sure",
"you",
"get",
"the",
"results",
"of",
"all",
"the",
"assertions",
"and",
"only",
"the",
"first",
"one",
"that",
"fails",
".",
"For",
"example",
"If",
"the",
"test",
"should",
"assert",
"that",
"a",
"message",
"box",
"appears",
"with",
"certain",
"text",
"certain",
"title",
"and",
"a",
"certain",
"icon",
"-",
"each",
"of",
"these",
"assertions",
"are",
"independent",
"from",
"one",
"another",
"even",
"though",
"they",
"validate",
"the",
"result",
"of",
"the",
"same",
"operation",
".",
"This",
"class",
"evaluates",
"and",
"writes",
"the",
"result",
"of",
"each",
"assertion",
"to",
"the",
"log",
"immediately",
"when",
"one",
"of",
"the",
"assertion",
"methods",
"is",
"called",
"but",
"throws",
"an",
"only",
"when",
"is",
"called",
"if",
"one",
"or",
"more",
"assertions",
"have",
"failed",
".",
"Normally",
"instead",
"of",
"calling",
"directly",
"you",
"would",
"use",
"the",
"using"
]
},
{
"identifier": "example",
"docstring": "using(var asserts = new AssertsAggregator(\"Message Box\")\n{\nasserts.AreEqual(\"Add customer\", () => messageBox.Title, \"Title\");\nasserts.AreEqual(\"The customer you tried to add already exists\", () => messageBox.Text, \"Text\");\nasserts.AreEqual(MessageBoxIcon.Error, () => messageBox.Icon, \"Icon\");\n}",
"docstring_tokens": [
"using",
"(",
"var",
"asserts",
"=",
"new",
"AssertsAggregator",
"(",
"\"",
"Message",
"Box",
"\"",
")",
"{",
"asserts",
".",
"AreEqual",
"(",
"\"",
"Add",
"customer",
"\"",
"()",
"=",
">",
"messageBox",
".",
"Title",
"\"",
"Title",
"\"",
")",
";",
"asserts",
".",
"AreEqual",
"(",
"\"",
"The",
"customer",
"you",
"tried",
"to",
"add",
"already",
"exists",
"\"",
"()",
"=",
">",
"messageBox",
".",
"Text",
"\"",
"Text",
"\"",
")",
";",
"asserts",
".",
"AreEqual",
"(",
"MessageBoxIcon",
".",
"Error",
"()",
"=",
">",
"messageBox",
".",
"Icon",
"\"",
"Icon",
"\"",
")",
";",
"}"
]
}
]
}
| false
| 17
| 298
| 355
|
e9b3c9d404eeab05a4b92cccd9458dd1083d9b0e
|
seshathriR/ReactEXporee
|
src/components/app.js
|
[
"MIT"
] |
JavaScript
|
App
|
/*export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {open: false};
}
handleTouchTap = (event) => {
// This prevents ghost click.
event.preventDefault();
this.setState({
open: true,
anchorEl: event.currentTarget,
});
};
handleRequestClose = () => {
this.setState({
open: false,
});
};
render() {
return (
<div>
<Drawer open={true}>
<MenuItem data-tip="hello world">MenuItemHover
<ReactTooltip place="right" type="success" effect="float" data-event-off="click">
<Menu>
<MenuItem primaryText="Refresh" />
<MenuItem primaryText="Help & feedback" />
<MenuItem primaryText="Settings" />
<MenuItem primaryText="Sign out" />
</Menu>
</ReactTooltip></MenuItem>
<MenuItem>Menu Item 2</MenuItem>
</Drawer>
</div>
);
}
}*/
|
handleTouchTap = (event) => {
This prevents ghost click.
handleRequestClose = () => {
this.setState({
open: false,
});
}.
render() {
return (
Menu Item 2
|
[
"handleTouchTap",
"=",
"(",
"event",
")",
"=",
">",
"{",
"This",
"prevents",
"ghost",
"click",
".",
"handleRequestClose",
"=",
"()",
"=",
">",
"{",
"this",
".",
"setState",
"(",
"{",
"open",
":",
"false",
"}",
")",
";",
"}",
".",
"render",
"()",
"{",
"return",
"(",
"Menu",
"Item",
"2"
] |
class App extends React.Component {
state = { isMenuOpen: false,open:false };
toggle = () => {
this.setState({ isMenuOpen: !this.state.isMenuOpen,open:true });
}
close = () => {
this.setState({ isMenuOpen: false });
};
click = () => {
console.log('You clicked an item');
};
render() {
const menuOptions = {
isOpen: this.state.isMenuOpen,
close: this.close,
toggle: <button type="button" onClick={this.toggle}>Click me!</button>,
align: 'right',
};
const nestedProps = {
toggle: <a href="#">Hover me for Nested Menu!</a>,
animate: true,
};
const nestedPropsone = {
toggle: <a href="#">Hover For Secondary menu</a>,
animate: true,
};
return (
<DropdownMenu {...menuOptions}>
<li><a href="#">Example 1</a></li>
<li><button type="button" onClick={this.click}>Example 2</button></li>
<li role="separator" className="separator" />
<NestedDropdownMenu {...nestedProps}>
<MenuItem anchorOrigin= {"horizontal:left","vertical:bottom"}
targetOrigin= {"horizontal:left","vertical:top"} >
<Menu >
<MenuItem primaryText="Refresh" />
<MenuItem primaryText="Help & feedback" />
<MenuItem primaryText="Settings" />
<MenuItem primaryText="Sign out" />
</Menu>
</MenuItem>
</NestedDropdownMenu>
<NestedDropdownMenu {...nestedPropsone}>
<MenuItem anchorOrigin= {"horizontal:left","vertical:bottom"}
targetOrigin= {"horizontal:left","vertical:top"} >
<Menu >
<MenuItem primaryText="Refresh" />
<MenuItem primaryText="Help & feedback" />
<MenuItem primaryText="Settings" />
<MenuItem primaryText="Sign out" />
</Menu>
</MenuItem>
</NestedDropdownMenu>
</DropdownMenu>
);
}
}
|
[
"class",
"App",
"extends",
"React",
".",
"Component",
"{",
"state",
"=",
"{",
"isMenuOpen",
":",
"false",
",",
"open",
":",
"false",
"}",
";",
"toggle",
"=",
"(",
")",
"=>",
"{",
"this",
".",
"setState",
"(",
"{",
"isMenuOpen",
":",
"!",
"this",
".",
"state",
".",
"isMenuOpen",
",",
"open",
":",
"true",
"}",
")",
";",
"}",
"close",
"=",
"(",
")",
"=>",
"{",
"this",
".",
"setState",
"(",
"{",
"isMenuOpen",
":",
"false",
"}",
")",
";",
"}",
";",
"click",
"=",
"(",
")",
"=>",
"{",
"console",
".",
"log",
"(",
"'You clicked an item'",
")",
";",
"}",
";",
"render",
"(",
")",
"{",
"const",
"menuOptions",
"=",
"{",
"isOpen",
":",
"this",
".",
"state",
".",
"isMenuOpen",
",",
"close",
":",
"this",
".",
"close",
",",
"toggle",
":",
"<",
"button",
"type",
"=",
"\"button\"",
"onClick",
"=",
"{",
"this",
".",
"toggle",
"}",
">",
"Click me!",
"<",
"/",
"button",
">",
",",
"align",
":",
"'right'",
",",
"}",
";",
"const",
"nestedProps",
"=",
"{",
"toggle",
":",
"<",
"a",
"href",
"=",
"\"#\"",
">",
"Hover me for Nested Menu!",
"<",
"/",
"a",
">",
",",
"animate",
":",
"true",
",",
"}",
";",
"const",
"nestedPropsone",
"=",
"{",
"toggle",
":",
"<",
"a",
"href",
"=",
"\"#\"",
">",
"Hover For Secondary menu",
"<",
"/",
"a",
">",
",",
"animate",
":",
"true",
",",
"}",
";",
"return",
"(",
"<",
"DropdownMenu",
"{",
"...",
"menuOptions",
"}",
">",
"\n ",
"<",
"li",
">",
"<",
"a",
"href",
"=",
"\"#\"",
">",
"Example 1",
"<",
"/",
"a",
">",
"<",
"/",
"li",
">",
"\n ",
"<",
"li",
">",
"<",
"button",
"type",
"=",
"\"button\"",
"onClick",
"=",
"{",
"this",
".",
"click",
"}",
">",
"Example 2",
"<",
"/",
"button",
">",
"<",
"/",
"li",
">",
"\n ",
"<",
"li",
"role",
"=",
"\"separator\"",
"className",
"=",
"\"separator\"",
"/",
">",
"\n ",
"<",
"NestedDropdownMenu",
"{",
"...",
"nestedProps",
"}",
">",
"\n ",
"<",
"MenuItem",
"anchorOrigin",
"=",
"{",
"\"horizontal:left\"",
",",
"\"vertical:bottom\"",
"}",
"targetOrigin",
"=",
"{",
"\"horizontal:left\"",
",",
"\"vertical:top\"",
"}",
">",
"\n ",
"<",
"Menu",
">",
"\n ",
"<",
"MenuItem",
"primaryText",
"=",
"\"Refresh\"",
"/",
">",
"\n ",
"<",
"MenuItem",
"primaryText",
"=",
"\"Help & feedback\"",
"/",
">",
"\n ",
"<",
"MenuItem",
"primaryText",
"=",
"\"Settings\"",
"/",
">",
"\n ",
"<",
"MenuItem",
"primaryText",
"=",
"\"Sign out\"",
"/",
">",
"\n ",
"<",
"/",
"Menu",
">",
"\n ",
"<",
"/",
"MenuItem",
">",
"\n ",
"<",
"/",
"NestedDropdownMenu",
">",
"\n ",
"<",
"NestedDropdownMenu",
"{",
"...",
"nestedPropsone",
"}",
">",
"\n ",
"<",
"MenuItem",
"anchorOrigin",
"=",
"{",
"\"horizontal:left\"",
",",
"\"vertical:bottom\"",
"}",
"targetOrigin",
"=",
"{",
"\"horizontal:left\"",
",",
"\"vertical:top\"",
"}",
">",
"\n ",
"<",
"Menu",
">",
"\n ",
"<",
"MenuItem",
"primaryText",
"=",
"\"Refresh\"",
"/",
">",
"\n ",
"<",
"MenuItem",
"primaryText",
"=",
"\"Help & feedback\"",
"/",
">",
"\n ",
"<",
"MenuItem",
"primaryText",
"=",
"\"Settings\"",
"/",
">",
"\n ",
"<",
"MenuItem",
"primaryText",
"=",
"\"Sign out\"",
"/",
">",
"\n ",
"<",
"/",
"Menu",
">",
"\n ",
"<",
"/",
"MenuItem",
">",
"\n ",
"<",
"/",
"NestedDropdownMenu",
">",
"\n ",
"<",
"/",
"DropdownMenu",
">",
")",
";",
"}",
"}"
] |
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {open: false};
}
|
[
"export",
"default",
"class",
"App",
"extends",
"React",
".",
"Component",
"{",
"constructor",
"(",
"props",
")",
"{",
"super",
"(",
"props",
")",
";",
"this",
".",
"state",
"=",
"{",
"open",
":",
"false",
"}",
";",
"}"
] |
[] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 15
| 455
| 230
|
ddc32f109eb3d040d5190d2a3d688e43bfe6c13f
|
saikrishnav/testfx
|
src/Adapter/MSTest.CoreAdapter/Resources/Resource.Designer.cs
|
[
"MIT"
] |
C#
|
Resource
|
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
|
A strongly-typed resource class, for looking up localized strings, etc.
|
[
"A",
"strongly",
"-",
"typed",
"resource",
"class",
"for",
"looking",
"up",
"localized",
"strings",
"etc",
"."
] |
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resource {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resource() {
}
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Resources.Resource", typeof(Resource).GetTypeInfo().Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
internal static string AttachmentSetDisplayName {
get {
return ResourceManager.GetString("AttachmentSetDisplayName", resourceCulture);
}
}
internal static string Common_CannotBeNullOrEmpty {
get {
return ResourceManager.GetString("Common_CannotBeNullOrEmpty", resourceCulture);
}
}
internal static string Common_MustBeGreaterThanZero {
get {
return ResourceManager.GetString("Common_MustBeGreaterThanZero", resourceCulture);
}
}
internal static string CouldNotInspectTypeDuringDiscovery {
get {
return ResourceManager.GetString("CouldNotInspectTypeDuringDiscovery", resourceCulture);
}
}
internal static string CouldNotInspectTypeDuringDiscovery1 {
get {
return ResourceManager.GetString("CouldNotInspectTypeDuringDiscovery1", resourceCulture);
}
}
internal static string DataDrivenResultDisplayName {
get {
return ResourceManager.GetString("DataDrivenResultDisplayName", resourceCulture);
}
}
internal static string DebugTraceBanner {
get {
return ResourceManager.GetString("DebugTraceBanner", resourceCulture);
}
}
internal static string DiscoveryWarning {
get {
return ResourceManager.GetString("DiscoveryWarning", resourceCulture);
}
}
internal static string EnumeratorLoadTypeErrorFormat {
get {
return ResourceManager.GetString("EnumeratorLoadTypeErrorFormat", resourceCulture);
}
}
internal static string Execution_Test_Timeout {
get {
return ResourceManager.GetString("Execution_Test_Timeout", resourceCulture);
}
}
internal static string InvalidParallelScopeValue {
get {
return ResourceManager.GetString("InvalidParallelScopeValue", resourceCulture);
}
}
internal static string InvalidParallelWorkersValue {
get {
return ResourceManager.GetString("InvalidParallelWorkersValue", resourceCulture);
}
}
internal static string InvalidSettingsXmlAttribute {
get {
return ResourceManager.GetString("InvalidSettingsXmlAttribute", resourceCulture);
}
}
internal static string InvalidSettingsXmlElement {
get {
return ResourceManager.GetString("InvalidSettingsXmlElement", resourceCulture);
}
}
internal static string LegacyScenariosNotSupportedWarning {
get {
return ResourceManager.GetString("LegacyScenariosNotSupportedWarning", resourceCulture);
}
}
internal static string SourcesNotSupported {
get {
return ResourceManager.GetString("SourcesNotSupported", resourceCulture);
}
}
internal static string TestAssembly_AssemblyDiscoveryFailure {
get {
return ResourceManager.GetString("TestAssembly_AssemblyDiscoveryFailure", resourceCulture);
}
}
internal static string TestAssembly_FileDoesNotExist {
get {
return ResourceManager.GetString("TestAssembly_FileDoesNotExist", resourceCulture);
}
}
internal static string TestContextIsNull {
get {
return ResourceManager.GetString("TestContextIsNull", resourceCulture);
}
}
internal static string TestContextMessageBanner {
get {
return ResourceManager.GetString("TestContextMessageBanner", resourceCulture);
}
}
internal static string TestNotFound {
get {
return ResourceManager.GetString("TestNotFound", resourceCulture);
}
}
internal static string TestParallelizationBanner {
get {
return ResourceManager.GetString("TestParallelizationBanner", resourceCulture);
}
}
internal static string TypeLoadFailed {
get {
return ResourceManager.GetString("TypeLoadFailed", resourceCulture);
}
}
internal static string UTA_AssemblyCleanupMethodWasUnsuccesful {
get {
return ResourceManager.GetString("UTA_AssemblyCleanupMethodWasUnsuccesful", resourceCulture);
}
}
internal static string UTA_AssemblyInitMethodThrows {
get {
return ResourceManager.GetString("UTA_AssemblyInitMethodThrows", resourceCulture);
}
}
internal static string UTA_ClassCleanupMethodWasUnsuccesful {
get {
return ResourceManager.GetString("UTA_ClassCleanupMethodWasUnsuccesful", resourceCulture);
}
}
internal static string UTA_ClassInitMethodThrows {
get {
return ResourceManager.GetString("UTA_ClassInitMethodThrows", resourceCulture);
}
}
internal static string UTA_ClassOrAssemblyCleanupMethodHasWrongSignature {
get {
return ResourceManager.GetString("UTA_ClassOrAssemblyCleanupMethodHasWrongSignature", resourceCulture);
}
}
internal static string UTA_ClassOrAssemblyInitializeMethodHasWrongSignature {
get {
return ResourceManager.GetString("UTA_ClassOrAssemblyInitializeMethodHasWrongSignature", resourceCulture);
}
}
internal static string UTA_CleanupMethodThrows {
get {
return ResourceManager.GetString("UTA_CleanupMethodThrows", resourceCulture);
}
}
internal static string UTA_CleanupMethodThrowsGeneralError {
get {
return ResourceManager.GetString("UTA_CleanupMethodThrowsGeneralError", resourceCulture);
}
}
internal static string UTA_CleanupStackTrace {
get {
return ResourceManager.GetString("UTA_CleanupStackTrace", resourceCulture);
}
}
internal static string UTA_EndOfInnerExceptionTrace {
get {
return ResourceManager.GetString("UTA_EndOfInnerExceptionTrace", resourceCulture);
}
}
internal static string UTA_ErrorGenericTestMethod {
get {
return ResourceManager.GetString("UTA_ErrorGenericTestMethod", resourceCulture);
}
}
internal static string UTA_ErrorIncorrectTestMethodSignature {
get {
return ResourceManager.GetString("UTA_ErrorIncorrectTestMethodSignature", resourceCulture);
}
}
internal static string UTA_ErrorInValidTestContextSignature {
get {
return ResourceManager.GetString("UTA_ErrorInValidTestContextSignature", resourceCulture);
}
}
internal static string UTA_ErrorInvalidTimeout {
get {
return ResourceManager.GetString("UTA_ErrorInvalidTimeout", resourceCulture);
}
}
internal static string UTA_ErrorMultiAssemblyClean {
get {
return ResourceManager.GetString("UTA_ErrorMultiAssemblyClean", resourceCulture);
}
}
internal static string UTA_ErrorMultiAssemblyInit {
get {
return ResourceManager.GetString("UTA_ErrorMultiAssemblyInit", resourceCulture);
}
}
internal static string UTA_ErrorMultiClassClean {
get {
return ResourceManager.GetString("UTA_ErrorMultiClassClean", resourceCulture);
}
}
internal static string UTA_ErrorMultiClassInit {
get {
return ResourceManager.GetString("UTA_ErrorMultiClassInit", resourceCulture);
}
}
internal static string UTA_ErrorMultiClean {
get {
return ResourceManager.GetString("UTA_ErrorMultiClean", resourceCulture);
}
}
internal static string UTA_ErrorMultiInit {
get {
return ResourceManager.GetString("UTA_ErrorMultiInit", resourceCulture);
}
}
internal static string UTA_ErrorNonPublicTestClass {
get {
return ResourceManager.GetString("UTA_ErrorNonPublicTestClass", resourceCulture);
}
}
internal static string UTA_ErrorPredefinedTestProperty {
get {
return ResourceManager.GetString("UTA_ErrorPredefinedTestProperty", resourceCulture);
}
}
internal static string UTA_ErrorTestPropertyAlreadyDefined {
get {
return ResourceManager.GetString("UTA_ErrorTestPropertyAlreadyDefined", resourceCulture);
}
}
internal static string UTA_ErrorTestPropertyNullOrEmpty {
get {
return ResourceManager.GetString("UTA_ErrorTestPropertyNullOrEmpty", resourceCulture);
}
}
internal static string UTA_ExecuteThrewException {
get {
return ResourceManager.GetString("UTA_ExecuteThrewException", resourceCulture);
}
}
internal static string UTA_ExpectedExceptionAttributeConstructionException {
get {
return ResourceManager.GetString("UTA_ExpectedExceptionAttributeConstructionException", resourceCulture);
}
}
internal static string UTA_FailedToGetTestMethodException {
get {
return ResourceManager.GetString("UTA_FailedToGetTestMethodException", resourceCulture);
}
}
internal static string UTA_InitMethodThrows {
get {
return ResourceManager.GetString("UTA_InitMethodThrows", resourceCulture);
}
}
internal static string UTA_InstanceCreationError {
get {
return ResourceManager.GetString("UTA_InstanceCreationError", resourceCulture);
}
}
internal static string UTA_MethodDoesNotExists {
get {
return ResourceManager.GetString("UTA_MethodDoesNotExists", resourceCulture);
}
}
internal static string UTA_MultipleExpectedExceptionsOnTestMethod {
get {
return ResourceManager.GetString("UTA_MultipleExpectedExceptionsOnTestMethod", resourceCulture);
}
}
internal static string UTA_NoDefaultConstructor {
get {
return ResourceManager.GetString("UTA_NoDefaultConstructor", resourceCulture);
}
}
internal static string UTA_NoTestResult {
get {
return ResourceManager.GetString("UTA_NoTestResult", resourceCulture);
}
}
internal static string UTA_TestContextLoadError {
get {
return ResourceManager.GetString("UTA_TestContextLoadError", resourceCulture);
}
}
internal static string UTA_TestContextSetError {
get {
return ResourceManager.GetString("UTA_TestContextSetError", resourceCulture);
}
}
internal static string UTA_TestContextTypeMismatchLoadError {
get {
return ResourceManager.GetString("UTA_TestContextTypeMismatchLoadError", resourceCulture);
}
}
internal static string UTA_TestInitializeAndCleanupMethodHasWrongSignature {
get {
return ResourceManager.GetString("UTA_TestInitializeAndCleanupMethodHasWrongSignature", resourceCulture);
}
}
internal static string UTA_TestMethodThrows {
get {
return ResourceManager.GetString("UTA_TestMethodThrows", resourceCulture);
}
}
internal static string UTA_TypeLoadError {
get {
return ResourceManager.GetString("UTA_TypeLoadError", resourceCulture);
}
}
internal static string UTA_WrongThread {
get {
return ResourceManager.GetString("UTA_WrongThread", resourceCulture);
}
}
internal static string UTF_FailedToGetExceptionMessage {
get {
return ResourceManager.GetString("UTF_FailedToGetExceptionMessage", resourceCulture);
}
}
}
|
[
"[",
"global",
"::",
"System",
".",
"CodeDom",
".",
"Compiler",
".",
"GeneratedCodeAttribute",
"(",
"\"",
"System.Resources.Tools.StronglyTypedResourceBuilder",
"\"",
",",
"\"",
"15.0.0.0",
"\"",
")",
"]",
"[",
"global",
"::",
"System",
".",
"Diagnostics",
".",
"DebuggerNonUserCodeAttribute",
"(",
")",
"]",
"[",
"global",
"::",
"System",
".",
"Runtime",
".",
"CompilerServices",
".",
"CompilerGeneratedAttribute",
"(",
")",
"]",
"internal",
"class",
"Resource",
"{",
"private",
"static",
"global",
"::",
"System",
".",
"Resources",
".",
"ResourceManager",
"resourceMan",
";",
"private",
"static",
"global",
"::",
"System",
".",
"Globalization",
".",
"CultureInfo",
"resourceCulture",
";",
"[",
"global",
"::",
"System",
".",
"Diagnostics",
".",
"CodeAnalysis",
".",
"SuppressMessageAttribute",
"(",
"\"",
"Microsoft.Performance",
"\"",
",",
"\"",
"CA1811:AvoidUncalledPrivateCode",
"\"",
")",
"]",
"internal",
"Resource",
"(",
")",
"{",
"}",
"[",
"global",
"::",
"System",
".",
"ComponentModel",
".",
"EditorBrowsableAttribute",
"(",
"global",
"::",
"System",
".",
"ComponentModel",
".",
"EditorBrowsableState",
".",
"Advanced",
")",
"]",
"internal",
"static",
"global",
"::",
"System",
".",
"Resources",
".",
"ResourceManager",
"ResourceManager",
"{",
"get",
"{",
"if",
"(",
"object",
".",
"ReferenceEquals",
"(",
"resourceMan",
",",
"null",
")",
")",
"{",
"global",
"::",
"System",
".",
"Resources",
".",
"ResourceManager",
"temp",
"=",
"new",
"global",
"::",
"System",
".",
"Resources",
".",
"ResourceManager",
"(",
"\"",
"Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Resources.Resource",
"\"",
",",
"typeof",
"(",
"Resource",
")",
".",
"GetTypeInfo",
"(",
")",
".",
"Assembly",
")",
";",
"resourceMan",
"=",
"temp",
";",
"}",
"return",
"resourceMan",
";",
"}",
"}",
"[",
"global",
"::",
"System",
".",
"ComponentModel",
".",
"EditorBrowsableAttribute",
"(",
"global",
"::",
"System",
".",
"ComponentModel",
".",
"EditorBrowsableState",
".",
"Advanced",
")",
"]",
"internal",
"static",
"global",
"::",
"System",
".",
"Globalization",
".",
"CultureInfo",
"Culture",
"{",
"get",
"{",
"return",
"resourceCulture",
";",
"}",
"set",
"{",
"resourceCulture",
"=",
"value",
";",
"}",
"}",
"internal",
"static",
"string",
"AttachmentSetDisplayName",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"AttachmentSetDisplayName",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Common_CannotBeNullOrEmpty",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Common_CannotBeNullOrEmpty",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Common_MustBeGreaterThanZero",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Common_MustBeGreaterThanZero",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"CouldNotInspectTypeDuringDiscovery",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"CouldNotInspectTypeDuringDiscovery",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"CouldNotInspectTypeDuringDiscovery1",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"CouldNotInspectTypeDuringDiscovery1",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"DataDrivenResultDisplayName",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"DataDrivenResultDisplayName",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"DebugTraceBanner",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"DebugTraceBanner",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"DiscoveryWarning",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"DiscoveryWarning",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"EnumeratorLoadTypeErrorFormat",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"EnumeratorLoadTypeErrorFormat",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Execution_Test_Timeout",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Execution_Test_Timeout",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"InvalidParallelScopeValue",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"InvalidParallelScopeValue",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"InvalidParallelWorkersValue",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"InvalidParallelWorkersValue",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"InvalidSettingsXmlAttribute",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"InvalidSettingsXmlAttribute",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"InvalidSettingsXmlElement",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"InvalidSettingsXmlElement",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"LegacyScenariosNotSupportedWarning",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"LegacyScenariosNotSupportedWarning",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"SourcesNotSupported",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"SourcesNotSupported",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"TestAssembly_AssemblyDiscoveryFailure",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"TestAssembly_AssemblyDiscoveryFailure",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"TestAssembly_FileDoesNotExist",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"TestAssembly_FileDoesNotExist",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"TestContextIsNull",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"TestContextIsNull",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"TestContextMessageBanner",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"TestContextMessageBanner",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"TestNotFound",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"TestNotFound",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"TestParallelizationBanner",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"TestParallelizationBanner",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"TypeLoadFailed",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"TypeLoadFailed",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"UTA_AssemblyCleanupMethodWasUnsuccesful",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"UTA_AssemblyCleanupMethodWasUnsuccesful",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"UTA_AssemblyInitMethodThrows",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"UTA_AssemblyInitMethodThrows",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"UTA_ClassCleanupMethodWasUnsuccesful",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"UTA_ClassCleanupMethodWasUnsuccesful",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"UTA_ClassInitMethodThrows",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"UTA_ClassInitMethodThrows",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"UTA_ClassOrAssemblyCleanupMethodHasWrongSignature",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"UTA_ClassOrAssemblyCleanupMethodHasWrongSignature",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"UTA_ClassOrAssemblyInitializeMethodHasWrongSignature",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"UTA_ClassOrAssemblyInitializeMethodHasWrongSignature",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"UTA_CleanupMethodThrows",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"UTA_CleanupMethodThrows",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"UTA_CleanupMethodThrowsGeneralError",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"UTA_CleanupMethodThrowsGeneralError",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"UTA_CleanupStackTrace",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"UTA_CleanupStackTrace",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"UTA_EndOfInnerExceptionTrace",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"UTA_EndOfInnerExceptionTrace",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"UTA_ErrorGenericTestMethod",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"UTA_ErrorGenericTestMethod",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"UTA_ErrorIncorrectTestMethodSignature",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"UTA_ErrorIncorrectTestMethodSignature",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"UTA_ErrorInValidTestContextSignature",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"UTA_ErrorInValidTestContextSignature",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"UTA_ErrorInvalidTimeout",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"UTA_ErrorInvalidTimeout",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"UTA_ErrorMultiAssemblyClean",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"UTA_ErrorMultiAssemblyClean",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"UTA_ErrorMultiAssemblyInit",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"UTA_ErrorMultiAssemblyInit",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"UTA_ErrorMultiClassClean",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"UTA_ErrorMultiClassClean",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"UTA_ErrorMultiClassInit",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"UTA_ErrorMultiClassInit",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"UTA_ErrorMultiClean",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"UTA_ErrorMultiClean",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"UTA_ErrorMultiInit",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"UTA_ErrorMultiInit",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"UTA_ErrorNonPublicTestClass",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"UTA_ErrorNonPublicTestClass",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"UTA_ErrorPredefinedTestProperty",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"UTA_ErrorPredefinedTestProperty",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"UTA_ErrorTestPropertyAlreadyDefined",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"UTA_ErrorTestPropertyAlreadyDefined",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"UTA_ErrorTestPropertyNullOrEmpty",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"UTA_ErrorTestPropertyNullOrEmpty",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"UTA_ExecuteThrewException",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"UTA_ExecuteThrewException",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"UTA_ExpectedExceptionAttributeConstructionException",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"UTA_ExpectedExceptionAttributeConstructionException",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"UTA_FailedToGetTestMethodException",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"UTA_FailedToGetTestMethodException",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"UTA_InitMethodThrows",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"UTA_InitMethodThrows",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"UTA_InstanceCreationError",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"UTA_InstanceCreationError",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"UTA_MethodDoesNotExists",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"UTA_MethodDoesNotExists",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"UTA_MultipleExpectedExceptionsOnTestMethod",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"UTA_MultipleExpectedExceptionsOnTestMethod",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"UTA_NoDefaultConstructor",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"UTA_NoDefaultConstructor",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"UTA_NoTestResult",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"UTA_NoTestResult",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"UTA_TestContextLoadError",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"UTA_TestContextLoadError",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"UTA_TestContextSetError",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"UTA_TestContextSetError",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"UTA_TestContextTypeMismatchLoadError",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"UTA_TestContextTypeMismatchLoadError",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"UTA_TestInitializeAndCleanupMethodHasWrongSignature",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"UTA_TestInitializeAndCleanupMethodHasWrongSignature",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"UTA_TestMethodThrows",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"UTA_TestMethodThrows",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"UTA_TypeLoadError",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"UTA_TypeLoadError",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"UTA_WrongThread",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"UTA_WrongThread",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"UTF_FailedToGetExceptionMessage",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"UTF_FailedToGetExceptionMessage",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"}"
] |
A strongly-typed resource class, for looking up localized strings, etc.
|
[
"A",
"strongly",
"-",
"typed",
"resource",
"class",
"for",
"looking",
"up",
"localized",
"strings",
"etc",
"."
] |
[
"/// <summary>",
"/// Returns the cached ResourceManager instance used by this class.",
"/// </summary>",
"/// <summary>",
"/// Overrides the current thread's CurrentUICulture property for all",
"/// resource lookups using this strongly typed resource class.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to MSTestAdapterV2.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to The parameter should not be null or empty..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to The parameter must be greater than zero..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}'. Reason {2}..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to {0} (Data Row {1}).",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Debug Trace:.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to [MSTest][Discovery][{0}] {1}.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to {0}: {1}.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Test '{0}' exceeded execution timeout period..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Invalid settings '{0}'. Unexpected XmlElement: '{1}'..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Warning : A testsettings file, a runsettings file with a ForcedLegacyMode set to true or a vsmdi file is not supported with the MSTest V2 Adapter..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Running tests in any of the provided sources is not supported for the selected platform.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Failed to discover tests from assembly {0}. Reason:{1}.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to File does not exist: {0}.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to TestContext cannot be Null..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to TestContext Messages:.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Test method {0} was not found..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to MSTest Executor: Test Parallelization enabled for {0} (Workers: {1}, Scope: {2})..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3}.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3}.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Class Initialization method {0}.{1} threw exception. {2}: {3}..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be Task..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be Task..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to TestCleanup method {0}.{1} threw exception. {2}: {3}..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Error calling Test Cleanup method for test class {0}: {1}.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to TestCleanup Stack Trace.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to --- End of inner exception stack trace ---.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to UTA015: A generic method cannot be a test method. {0}.{1} has invalid signature.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be Task. Example: public async Task Test.Class1.Test2().",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, public and must not be read-only. For example: public TestContext TestContext..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be a valid integer value and cannot be less than 0..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to UTA024: {0}: Cannot define more than one method with the TestCleanup attribute..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to UTA018: {0}: Cannot define more than one method with the TestInitialize attribute..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to UTA001: TestClass attribute defined on non-public class {0}.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to UTA023: {0}: Cannot define predefined property {2} on method {1}..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to UTA022: {0}.{1}: The custom property "{2}" is already defined. Using "{3}" as value..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Exception thrown while executing test. If using extension of TestMethodAttribute then please contact vendor. Error message: {0}.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction.",
"///{2}.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Failed to obtain the exception thrown by test method {0}.{1}..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Initialization method {0}.{1} threw exception. {2}..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Unable to create instance of class {0}. Error: {1}..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Method {0}.{1} does not exist..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to The test method {0}.{1} has multiple attributes derived from ExpectedExceptionBaseAttribute defined on it. Only one such attribute is allowed..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Unable to get default constructor for class {0}..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Unable to find property {0}.TestContext. Error:{1}..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Unable to set TestContext property for the class {0}. Error: {1}..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to The {0}.TestContext has incorrect type..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be Task..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Test method {0}.{1} threw exception: ",
"///{2}.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Unable to get type {0}. Error: {1}..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to {0}. If you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to (Failed to get the message for an exception of type {0} due to an exception.).",
"/// </summary>"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 19
| 2,347
| 84
|
a707db46a5a8f0c44d03a2ca8f85d7b5fe540ad6
|
mjhydri/1D-StateSpace
|
src/jump_reward_inference/inference.py
|
[
"MIT"
] |
Python
|
inference_1D
|
Running the jump-reward inference for the 1D state spaces over the given activation functions to infer music rhythmic information jointly.
Parameters
----------
activations : numpy array, shape (num_frames, 2)
Activation function with probabilities corresponding to beats
and downbeats given in the first and second column, respectively.
Returns
----------
beats, downbeats, local tempo, local meter : numpy array, shape (num_beats, 4)
"1" at the second column indicates the downbeats.
References:
----------
|
Running the jump-reward inference for the 1D state spaces over the given activation functions to infer music rhythmic information jointly.
Parameters
activations : numpy array, shape (num_frames, 2)
Activation function with probabilities corresponding to beats
and downbeats given in the first and second column, respectively.
Returns
beats, downbeats, local tempo, local meter : numpy array, shape (num_beats, 4)
"1" at the second column indicates the downbeats.
|
[
"Running",
"the",
"jump",
"-",
"reward",
"inference",
"for",
"the",
"1D",
"state",
"spaces",
"over",
"the",
"given",
"activation",
"functions",
"to",
"infer",
"music",
"rhythmic",
"information",
"jointly",
".",
"Parameters",
"activations",
":",
"numpy",
"array",
"shape",
"(",
"num_frames",
"2",
")",
"Activation",
"function",
"with",
"probabilities",
"corresponding",
"to",
"beats",
"and",
"downbeats",
"given",
"in",
"the",
"first",
"and",
"second",
"column",
"respectively",
".",
"Returns",
"beats",
"downbeats",
"local",
"tempo",
"local",
"meter",
":",
"numpy",
"array",
"shape",
"(",
"num_beats",
"4",
")",
"\"",
"1",
"\"",
"at",
"the",
"second",
"column",
"indicates",
"the",
"downbeats",
"."
] |
class inference_1D:
'''
Running the jump-reward inference for the 1D state spaces over the given activation functions to infer music rhythmic information jointly.
Parameters
----------
activations : numpy array, shape (num_frames, 2)
Activation function with probabilities corresponding to beats
and downbeats given in the first and second column, respectively.
Returns
----------
beats, downbeats, local tempo, local meter : numpy array, shape (num_beats, 4)
"1" at the second column indicates the downbeats.
References:
----------
'''
MIN_BPM = 55.
MAX_BPM = 215.
LAMBDA_B = 0.01 # beat transition lambda
Lambda_D = 0.01 # downbeat transition lambda
OBSERVATION_LAMBDA = "B56"
fps = 50
T = 1 / fps
MIN_BEAT_PER_BAR = 1
MAX_BEAT_PER_BAR = 4
OFFSET = 4 # The point of time after which the inference model starts to work. Can be zero!
IG_THRESHOLD = 0.4 # Information Gate threshold
def __init__(self, beats_per_bar=[], min_bpm=MIN_BPM, max_bpm=MAX_BPM, offset=OFFSET,
min_bpb=MIN_BEAT_PER_BAR, max_bpb=MAX_BEAT_PER_BAR, ig_threshold=IG_THRESHOLD,
lambda_b=LAMBDA_B, lambda_d=Lambda_D, observation_lambda=OBSERVATION_LAMBDA,
fps=None, plot=False, **kwargs):
self.beats_per_bar = beats_per_bar
self.fps = fps
self.observation_lambda = observation_lambda
self.offset = offset
self.ig_threshold = ig_threshold
self.plot = plot
beats_per_bar = np.array(beats_per_bar, ndmin=1)
# convert timing information to construct a beat state space
min_interval = round(60. * fps / max_bpm)
max_interval = round(60. * fps / min_bpm)
# State spaces and observation models initialization
self.st = beat_state_space_1D(alpha=lambda_b, tempo=None, fps=None, min_interval=min_interval,
max_interval=max_interval, ) # beat tracking state space
self.st2 = downbeat_state_space_1D(alpha=lambda_d, meter=self.beats_per_bar, min_beats_per_bar=min_bpb,
max_beats_per_bar=max_bpb) # downbeat tracking state space
self.om = BDObservationModel(self.st, observation_lambda) # beat tracking observation model
self.om2 = BDObservationModel(self.st2, "B60") # downbeat tracking observation model
pass
def process(self, activations):
T = 1 / self.fps
font = {'color': 'green', 'weight': 'normal', 'size': 12}
counter = 0
if self.plot:
fig = plt.figure(figsize=(1800 / 96, 900 / 96), dpi=96)
subplot1 = fig.add_subplot(411)
subplot2 = fig.add_subplot(412)
subplot3 = fig.add_subplot(413)
subplot4 = fig.add_subplot(414)
subplot1.title.set_text('Beat tracking inference diagram')
subplot2.title.set_text('Beat states jumping back weigths')
subplot3.title.set_text('Downbeat tracking inference diagram')
subplot4.title.set_text('Downbeat states jumping back weigths')
fig.tight_layout()
# output vector initialization for beat, downbeat, tempo and meter
output = np.zeros((1, 4), dtype=float)
# Beat and downbeat belief state initialization
beat_distribution = np.ones(self.st.num_states) * 0.8
beat_distribution[5] = 1 # this is just a flag to show the initial transitions
down_distribution = np.ones(self.st2.num_states) * 0.8
# local tempo and meter initialization
local_tempo = 0
meter = 0
activations = activations[int(self.offset / T):]
both_activations = activations.copy()
activations = np.max(activations, axis=1)
activations[activations < self.ig_threshold] = 0.03
for i in range(len(activations)): # loop through all frames to infer beats/downbeats
counter += 1
# beat detection
# beat transition (motion)
local_beat = ''
if np.max(self.st.jump_weights) > 1:
self.st.jump_weights = 0.7 * self.st.jump_weights / np.max(self.st.jump_weights)
b_weight = self.st.jump_weights.copy()
beat_jump_rewards1 = -beat_distribution * b_weight # calculating the transition rewards
b_weight[b_weight < 0.7] = 0 # Thresholding the jump backs
beat_distribution1 = sum(beat_distribution * b_weight) # jump back
beat_distribution2 = np.roll((beat_distribution * (1 - b_weight)), 1) # move forward
beat_distribution2[0] += beat_distribution1
beat_distribution = beat_distribution2
# Beat correction
if activations[i] > self.ig_threshold: # beat correction is done only when there is a meaningful activation
obs = densities(activations[i], self.om, self.st)
beat_distribution_old = beat_distribution.copy()
beat_distribution = beat_distribution_old * obs
if np.min(beat_distribution) < 1e-5: # normalize beat distribution if its minimum is below a threshold
beat_distribution = 0.8 * beat_distribution / np.max(beat_distribution)
beat_max = np.argmax(beat_distribution)
beat_jump_rewards2 = beat_distribution - beat_distribution_old # beat correction rewards calculation
beat_jump_rewards = beat_jump_rewards2
beat_jump_rewards[:self.st.min_interval - 1] = 0
if np.max(-beat_jump_rewards) != 0:
beat_jump_rewards = -4 * beat_jump_rewards / np.max(-beat_jump_rewards)
self.st.jump_weights += beat_jump_rewards
local_tempo = round(self.fps * 60 / (np.argmax(self.st.jump_weights) + 1))
else:
beat_jump_rewards1[:self.st.min_interval - 1] = 0
self.st.jump_weights += 2 * beat_jump_rewards1
self.st.jump_weights[:self.st.min_interval - 1] = 0
beat_max = np.argmax(beat_distribution)
# downbeat detection
if (beat_max < (
int(.07 / T)) + 1) and (counter * T + self.offset) - output[-1][
0] > .45 * T * self.st.min_interval: # here the local tempo (:np.argmax(self.st.jump_weights)+1): can be used as the criteria rather than the minimum tempo
local_beat = 'NoooOOoooW!'
# downbeat transition (motion)
if np.max(self.st2.jump_weights) > 1:
self.st2.jump_weights = 0.2 * self.st2.jump_weights / np.max(self.st2.jump_weights)
d_weight = self.st2.jump_weights.copy()
down_jump_rewards1 = - down_distribution * d_weight
d_weight[d_weight < 0.2] = 0
down_distribution1 = sum(down_distribution * d_weight) # jump back
down_distribution2 = np.roll((down_distribution * (1 - d_weight)), 1) # move forward
down_distribution2[0] += down_distribution1
down_distribution = down_distribution2
# Downbeat correction
if both_activations[i][1] > 0.00002:
obs2 = densities2(both_activations[i], self.om2, self.st2)
down_distribution_old = down_distribution.copy()
down_distribution = down_distribution_old * obs2
if np.min(down_distribution) < 1e-5: # normalize downbeat distribution if its minimum is below a threshold
down_distribution = 0.8 * down_distribution/np.max(down_distribution)
down_max = np.argmax(down_distribution)
down_jump_rewards2 = down_distribution - down_distribution_old # downbeat correction rewards calculation
down_jump_rewards = down_jump_rewards2
down_jump_rewards[:self.st2.max_interval - 1] = 0
if np.max(-down_jump_rewards) != 0:
down_jump_rewards = -0.3 * down_jump_rewards / np.max(-down_jump_rewards)
self.st2.jump_weights = self.st2.jump_weights + down_jump_rewards
meter = np.argmax(self.st2.jump_weights) + 1
else:
down_jump_rewards1[:self.st2.min_interval - 1] = 0
self.st2.jump_weights += 2 * down_jump_rewards1
self.st2.jump_weights[:self.st2.min_interval - 1] = 0
down_max = np.argmax(down_distribution)
# Beat vs Downbeat mark off
if down_max == self.st2.first_states[0]:
output = np.append(output, [[counter * T + self.offset, 1, local_tempo, meter]], axis=0)
last_detected = "Downbeat"
else:
output = np.append(output, [[counter * T + self.offset, 2, local_tempo, meter]], axis=0)
last_detected = "Beat"
# Downbeat probability mass and weights
if self.plot:
subplot3.cla()
subplot4.cla()
down_distribution = down_distribution / np.max(down_distribution)
subplot3.bar(np.arange(self.st2.num_states), down_distribution, color='maroon', width=0.4,
alpha=0.2)
subplot3.bar(0, both_activations[i][1], color='green', width=0.4, alpha=0.3)
# subplot3.bar(np.arange(1, self.st2.num_states), both_activations[i][0], color='yellow', width=0.4, alpha=0.3)
subplot4.bar(np.arange(self.st2.num_states), self.st2.jump_weights, color='maroon', width=0.4,
alpha=0.2)
subplot4.set_ylim([0, 1])
subplot3.title.set_text('Downbeat tracking 1D inference model')
subplot4.title.set_text(f'Downbeat states jumping back weigths')
subplot4.text(1, -0.26, f'The type of the last detected event: {last_detected}',
horizontalalignment='right', verticalalignment='center', transform=subplot2.transAxes,
fontdict=font)
subplot4.text(1, -1.63, f'Local time signature = {meter}/4 ', horizontalalignment='right',
verticalalignment='center', transform=subplot2.transAxes, fontdict=font)
position2 = down_max
subplot3.axvline(x=position2)
# Downbeat probability mass and weights
if self.plot: # activates this when you want to plot the performance
if counter % 1 == 0: # Choosing how often to plot
print(counter)
subplot1.cla()
subplot2.cla()
beat_distribution = beat_distribution / np.max(beat_distribution)
subplot1.bar(np.arange(self.st.num_states), beat_distribution, color='maroon', width=0.4, alpha=0.2)
subplot1.bar(0, activations[i], color='green', width=0.4, alpha=0.3)
# subplot2.bar(np.arange(self.st.num_states), np.concatenate((np.zeros(self.st.min_interval),self.st.jump_weights)), color='maroon', width=0.4, alpha=0.2)
subplot2.bar(np.arange(self.st.num_states), self.st.jump_weights, color='maroon', width=0.4,
alpha=0.2)
subplot2.set_ylim([0, 1])
subplot1.title.set_text('Beat tracking 1D inference model')
subplot2.title.set_text("Beat states jumping back weigths")
subplot1.text(1, 2.48, f'Beat moment: {local_beat} ', horizontalalignment='right',
verticalalignment='top', transform=subplot2.transAxes, fontdict=font)
subplot2.text(1, 1.12, f'Local tempo: {local_tempo} (BPM)', horizontalalignment='right',
verticalalignment='top', transform=subplot2.transAxes, fontdict=font)
position = beat_max
subplot1.axvline(x=position)
plt.pause(0.05)
subplot1.clear()
return output[1:]
|
[
"class",
"inference_1D",
":",
"MIN_BPM",
"=",
"55.",
"MAX_BPM",
"=",
"215.",
"LAMBDA_B",
"=",
"0.01",
"Lambda_D",
"=",
"0.01",
"OBSERVATION_LAMBDA",
"=",
"\"B56\"",
"fps",
"=",
"50",
"T",
"=",
"1",
"/",
"fps",
"MIN_BEAT_PER_BAR",
"=",
"1",
"MAX_BEAT_PER_BAR",
"=",
"4",
"OFFSET",
"=",
"4",
"IG_THRESHOLD",
"=",
"0.4",
"def",
"__init__",
"(",
"self",
",",
"beats_per_bar",
"=",
"[",
"]",
",",
"min_bpm",
"=",
"MIN_BPM",
",",
"max_bpm",
"=",
"MAX_BPM",
",",
"offset",
"=",
"OFFSET",
",",
"min_bpb",
"=",
"MIN_BEAT_PER_BAR",
",",
"max_bpb",
"=",
"MAX_BEAT_PER_BAR",
",",
"ig_threshold",
"=",
"IG_THRESHOLD",
",",
"lambda_b",
"=",
"LAMBDA_B",
",",
"lambda_d",
"=",
"Lambda_D",
",",
"observation_lambda",
"=",
"OBSERVATION_LAMBDA",
",",
"fps",
"=",
"None",
",",
"plot",
"=",
"False",
",",
"**",
"kwargs",
")",
":",
"self",
".",
"beats_per_bar",
"=",
"beats_per_bar",
"self",
".",
"fps",
"=",
"fps",
"self",
".",
"observation_lambda",
"=",
"observation_lambda",
"self",
".",
"offset",
"=",
"offset",
"self",
".",
"ig_threshold",
"=",
"ig_threshold",
"self",
".",
"plot",
"=",
"plot",
"beats_per_bar",
"=",
"np",
".",
"array",
"(",
"beats_per_bar",
",",
"ndmin",
"=",
"1",
")",
"min_interval",
"=",
"round",
"(",
"60.",
"*",
"fps",
"/",
"max_bpm",
")",
"max_interval",
"=",
"round",
"(",
"60.",
"*",
"fps",
"/",
"min_bpm",
")",
"self",
".",
"st",
"=",
"beat_state_space_1D",
"(",
"alpha",
"=",
"lambda_b",
",",
"tempo",
"=",
"None",
",",
"fps",
"=",
"None",
",",
"min_interval",
"=",
"min_interval",
",",
"max_interval",
"=",
"max_interval",
",",
")",
"self",
".",
"st2",
"=",
"downbeat_state_space_1D",
"(",
"alpha",
"=",
"lambda_d",
",",
"meter",
"=",
"self",
".",
"beats_per_bar",
",",
"min_beats_per_bar",
"=",
"min_bpb",
",",
"max_beats_per_bar",
"=",
"max_bpb",
")",
"self",
".",
"om",
"=",
"BDObservationModel",
"(",
"self",
".",
"st",
",",
"observation_lambda",
")",
"self",
".",
"om2",
"=",
"BDObservationModel",
"(",
"self",
".",
"st2",
",",
"\"B60\"",
")",
"pass",
"def",
"process",
"(",
"self",
",",
"activations",
")",
":",
"T",
"=",
"1",
"/",
"self",
".",
"fps",
"font",
"=",
"{",
"'color'",
":",
"'green'",
",",
"'weight'",
":",
"'normal'",
",",
"'size'",
":",
"12",
"}",
"counter",
"=",
"0",
"if",
"self",
".",
"plot",
":",
"fig",
"=",
"plt",
".",
"figure",
"(",
"figsize",
"=",
"(",
"1800",
"/",
"96",
",",
"900",
"/",
"96",
")",
",",
"dpi",
"=",
"96",
")",
"subplot1",
"=",
"fig",
".",
"add_subplot",
"(",
"411",
")",
"subplot2",
"=",
"fig",
".",
"add_subplot",
"(",
"412",
")",
"subplot3",
"=",
"fig",
".",
"add_subplot",
"(",
"413",
")",
"subplot4",
"=",
"fig",
".",
"add_subplot",
"(",
"414",
")",
"subplot1",
".",
"title",
".",
"set_text",
"(",
"'Beat tracking inference diagram'",
")",
"subplot2",
".",
"title",
".",
"set_text",
"(",
"'Beat states jumping back weigths'",
")",
"subplot3",
".",
"title",
".",
"set_text",
"(",
"'Downbeat tracking inference diagram'",
")",
"subplot4",
".",
"title",
".",
"set_text",
"(",
"'Downbeat states jumping back weigths'",
")",
"fig",
".",
"tight_layout",
"(",
")",
"output",
"=",
"np",
".",
"zeros",
"(",
"(",
"1",
",",
"4",
")",
",",
"dtype",
"=",
"float",
")",
"beat_distribution",
"=",
"np",
".",
"ones",
"(",
"self",
".",
"st",
".",
"num_states",
")",
"*",
"0.8",
"beat_distribution",
"[",
"5",
"]",
"=",
"1",
"down_distribution",
"=",
"np",
".",
"ones",
"(",
"self",
".",
"st2",
".",
"num_states",
")",
"*",
"0.8",
"local_tempo",
"=",
"0",
"meter",
"=",
"0",
"activations",
"=",
"activations",
"[",
"int",
"(",
"self",
".",
"offset",
"/",
"T",
")",
":",
"]",
"both_activations",
"=",
"activations",
".",
"copy",
"(",
")",
"activations",
"=",
"np",
".",
"max",
"(",
"activations",
",",
"axis",
"=",
"1",
")",
"activations",
"[",
"activations",
"<",
"self",
".",
"ig_threshold",
"]",
"=",
"0.03",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"activations",
")",
")",
":",
"counter",
"+=",
"1",
"local_beat",
"=",
"''",
"if",
"np",
".",
"max",
"(",
"self",
".",
"st",
".",
"jump_weights",
")",
">",
"1",
":",
"self",
".",
"st",
".",
"jump_weights",
"=",
"0.7",
"*",
"self",
".",
"st",
".",
"jump_weights",
"/",
"np",
".",
"max",
"(",
"self",
".",
"st",
".",
"jump_weights",
")",
"b_weight",
"=",
"self",
".",
"st",
".",
"jump_weights",
".",
"copy",
"(",
")",
"beat_jump_rewards1",
"=",
"-",
"beat_distribution",
"*",
"b_weight",
"b_weight",
"[",
"b_weight",
"<",
"0.7",
"]",
"=",
"0",
"beat_distribution1",
"=",
"sum",
"(",
"beat_distribution",
"*",
"b_weight",
")",
"beat_distribution2",
"=",
"np",
".",
"roll",
"(",
"(",
"beat_distribution",
"*",
"(",
"1",
"-",
"b_weight",
")",
")",
",",
"1",
")",
"beat_distribution2",
"[",
"0",
"]",
"+=",
"beat_distribution1",
"beat_distribution",
"=",
"beat_distribution2",
"if",
"activations",
"[",
"i",
"]",
">",
"self",
".",
"ig_threshold",
":",
"obs",
"=",
"densities",
"(",
"activations",
"[",
"i",
"]",
",",
"self",
".",
"om",
",",
"self",
".",
"st",
")",
"beat_distribution_old",
"=",
"beat_distribution",
".",
"copy",
"(",
")",
"beat_distribution",
"=",
"beat_distribution_old",
"*",
"obs",
"if",
"np",
".",
"min",
"(",
"beat_distribution",
")",
"<",
"1e-5",
":",
"beat_distribution",
"=",
"0.8",
"*",
"beat_distribution",
"/",
"np",
".",
"max",
"(",
"beat_distribution",
")",
"beat_max",
"=",
"np",
".",
"argmax",
"(",
"beat_distribution",
")",
"beat_jump_rewards2",
"=",
"beat_distribution",
"-",
"beat_distribution_old",
"beat_jump_rewards",
"=",
"beat_jump_rewards2",
"beat_jump_rewards",
"[",
":",
"self",
".",
"st",
".",
"min_interval",
"-",
"1",
"]",
"=",
"0",
"if",
"np",
".",
"max",
"(",
"-",
"beat_jump_rewards",
")",
"!=",
"0",
":",
"beat_jump_rewards",
"=",
"-",
"4",
"*",
"beat_jump_rewards",
"/",
"np",
".",
"max",
"(",
"-",
"beat_jump_rewards",
")",
"self",
".",
"st",
".",
"jump_weights",
"+=",
"beat_jump_rewards",
"local_tempo",
"=",
"round",
"(",
"self",
".",
"fps",
"*",
"60",
"/",
"(",
"np",
".",
"argmax",
"(",
"self",
".",
"st",
".",
"jump_weights",
")",
"+",
"1",
")",
")",
"else",
":",
"beat_jump_rewards1",
"[",
":",
"self",
".",
"st",
".",
"min_interval",
"-",
"1",
"]",
"=",
"0",
"self",
".",
"st",
".",
"jump_weights",
"+=",
"2",
"*",
"beat_jump_rewards1",
"self",
".",
"st",
".",
"jump_weights",
"[",
":",
"self",
".",
"st",
".",
"min_interval",
"-",
"1",
"]",
"=",
"0",
"beat_max",
"=",
"np",
".",
"argmax",
"(",
"beat_distribution",
")",
"if",
"(",
"beat_max",
"<",
"(",
"int",
"(",
".07",
"/",
"T",
")",
")",
"+",
"1",
")",
"and",
"(",
"counter",
"*",
"T",
"+",
"self",
".",
"offset",
")",
"-",
"output",
"[",
"-",
"1",
"]",
"[",
"0",
"]",
">",
".45",
"*",
"T",
"*",
"self",
".",
"st",
".",
"min_interval",
":",
"local_beat",
"=",
"'NoooOOoooW!'",
"if",
"np",
".",
"max",
"(",
"self",
".",
"st2",
".",
"jump_weights",
")",
">",
"1",
":",
"self",
".",
"st2",
".",
"jump_weights",
"=",
"0.2",
"*",
"self",
".",
"st2",
".",
"jump_weights",
"/",
"np",
".",
"max",
"(",
"self",
".",
"st2",
".",
"jump_weights",
")",
"d_weight",
"=",
"self",
".",
"st2",
".",
"jump_weights",
".",
"copy",
"(",
")",
"down_jump_rewards1",
"=",
"-",
"down_distribution",
"*",
"d_weight",
"d_weight",
"[",
"d_weight",
"<",
"0.2",
"]",
"=",
"0",
"down_distribution1",
"=",
"sum",
"(",
"down_distribution",
"*",
"d_weight",
")",
"down_distribution2",
"=",
"np",
".",
"roll",
"(",
"(",
"down_distribution",
"*",
"(",
"1",
"-",
"d_weight",
")",
")",
",",
"1",
")",
"down_distribution2",
"[",
"0",
"]",
"+=",
"down_distribution1",
"down_distribution",
"=",
"down_distribution2",
"if",
"both_activations",
"[",
"i",
"]",
"[",
"1",
"]",
">",
"0.00002",
":",
"obs2",
"=",
"densities2",
"(",
"both_activations",
"[",
"i",
"]",
",",
"self",
".",
"om2",
",",
"self",
".",
"st2",
")",
"down_distribution_old",
"=",
"down_distribution",
".",
"copy",
"(",
")",
"down_distribution",
"=",
"down_distribution_old",
"*",
"obs2",
"if",
"np",
".",
"min",
"(",
"down_distribution",
")",
"<",
"1e-5",
":",
"down_distribution",
"=",
"0.8",
"*",
"down_distribution",
"/",
"np",
".",
"max",
"(",
"down_distribution",
")",
"down_max",
"=",
"np",
".",
"argmax",
"(",
"down_distribution",
")",
"down_jump_rewards2",
"=",
"down_distribution",
"-",
"down_distribution_old",
"down_jump_rewards",
"=",
"down_jump_rewards2",
"down_jump_rewards",
"[",
":",
"self",
".",
"st2",
".",
"max_interval",
"-",
"1",
"]",
"=",
"0",
"if",
"np",
".",
"max",
"(",
"-",
"down_jump_rewards",
")",
"!=",
"0",
":",
"down_jump_rewards",
"=",
"-",
"0.3",
"*",
"down_jump_rewards",
"/",
"np",
".",
"max",
"(",
"-",
"down_jump_rewards",
")",
"self",
".",
"st2",
".",
"jump_weights",
"=",
"self",
".",
"st2",
".",
"jump_weights",
"+",
"down_jump_rewards",
"meter",
"=",
"np",
".",
"argmax",
"(",
"self",
".",
"st2",
".",
"jump_weights",
")",
"+",
"1",
"else",
":",
"down_jump_rewards1",
"[",
":",
"self",
".",
"st2",
".",
"min_interval",
"-",
"1",
"]",
"=",
"0",
"self",
".",
"st2",
".",
"jump_weights",
"+=",
"2",
"*",
"down_jump_rewards1",
"self",
".",
"st2",
".",
"jump_weights",
"[",
":",
"self",
".",
"st2",
".",
"min_interval",
"-",
"1",
"]",
"=",
"0",
"down_max",
"=",
"np",
".",
"argmax",
"(",
"down_distribution",
")",
"if",
"down_max",
"==",
"self",
".",
"st2",
".",
"first_states",
"[",
"0",
"]",
":",
"output",
"=",
"np",
".",
"append",
"(",
"output",
",",
"[",
"[",
"counter",
"*",
"T",
"+",
"self",
".",
"offset",
",",
"1",
",",
"local_tempo",
",",
"meter",
"]",
"]",
",",
"axis",
"=",
"0",
")",
"last_detected",
"=",
"\"Downbeat\"",
"else",
":",
"output",
"=",
"np",
".",
"append",
"(",
"output",
",",
"[",
"[",
"counter",
"*",
"T",
"+",
"self",
".",
"offset",
",",
"2",
",",
"local_tempo",
",",
"meter",
"]",
"]",
",",
"axis",
"=",
"0",
")",
"last_detected",
"=",
"\"Beat\"",
"if",
"self",
".",
"plot",
":",
"subplot3",
".",
"cla",
"(",
")",
"subplot4",
".",
"cla",
"(",
")",
"down_distribution",
"=",
"down_distribution",
"/",
"np",
".",
"max",
"(",
"down_distribution",
")",
"subplot3",
".",
"bar",
"(",
"np",
".",
"arange",
"(",
"self",
".",
"st2",
".",
"num_states",
")",
",",
"down_distribution",
",",
"color",
"=",
"'maroon'",
",",
"width",
"=",
"0.4",
",",
"alpha",
"=",
"0.2",
")",
"subplot3",
".",
"bar",
"(",
"0",
",",
"both_activations",
"[",
"i",
"]",
"[",
"1",
"]",
",",
"color",
"=",
"'green'",
",",
"width",
"=",
"0.4",
",",
"alpha",
"=",
"0.3",
")",
"subplot4",
".",
"bar",
"(",
"np",
".",
"arange",
"(",
"self",
".",
"st2",
".",
"num_states",
")",
",",
"self",
".",
"st2",
".",
"jump_weights",
",",
"color",
"=",
"'maroon'",
",",
"width",
"=",
"0.4",
",",
"alpha",
"=",
"0.2",
")",
"subplot4",
".",
"set_ylim",
"(",
"[",
"0",
",",
"1",
"]",
")",
"subplot3",
".",
"title",
".",
"set_text",
"(",
"'Downbeat tracking 1D inference model'",
")",
"subplot4",
".",
"title",
".",
"set_text",
"(",
"f'Downbeat states jumping back weigths'",
")",
"subplot4",
".",
"text",
"(",
"1",
",",
"-",
"0.26",
",",
"f'The type of the last detected event: {last_detected}'",
",",
"horizontalalignment",
"=",
"'right'",
",",
"verticalalignment",
"=",
"'center'",
",",
"transform",
"=",
"subplot2",
".",
"transAxes",
",",
"fontdict",
"=",
"font",
")",
"subplot4",
".",
"text",
"(",
"1",
",",
"-",
"1.63",
",",
"f'Local time signature = {meter}/4 '",
",",
"horizontalalignment",
"=",
"'right'",
",",
"verticalalignment",
"=",
"'center'",
",",
"transform",
"=",
"subplot2",
".",
"transAxes",
",",
"fontdict",
"=",
"font",
")",
"position2",
"=",
"down_max",
"subplot3",
".",
"axvline",
"(",
"x",
"=",
"position2",
")",
"if",
"self",
".",
"plot",
":",
"if",
"counter",
"%",
"1",
"==",
"0",
":",
"print",
"(",
"counter",
")",
"subplot1",
".",
"cla",
"(",
")",
"subplot2",
".",
"cla",
"(",
")",
"beat_distribution",
"=",
"beat_distribution",
"/",
"np",
".",
"max",
"(",
"beat_distribution",
")",
"subplot1",
".",
"bar",
"(",
"np",
".",
"arange",
"(",
"self",
".",
"st",
".",
"num_states",
")",
",",
"beat_distribution",
",",
"color",
"=",
"'maroon'",
",",
"width",
"=",
"0.4",
",",
"alpha",
"=",
"0.2",
")",
"subplot1",
".",
"bar",
"(",
"0",
",",
"activations",
"[",
"i",
"]",
",",
"color",
"=",
"'green'",
",",
"width",
"=",
"0.4",
",",
"alpha",
"=",
"0.3",
")",
"subplot2",
".",
"bar",
"(",
"np",
".",
"arange",
"(",
"self",
".",
"st",
".",
"num_states",
")",
",",
"self",
".",
"st",
".",
"jump_weights",
",",
"color",
"=",
"'maroon'",
",",
"width",
"=",
"0.4",
",",
"alpha",
"=",
"0.2",
")",
"subplot2",
".",
"set_ylim",
"(",
"[",
"0",
",",
"1",
"]",
")",
"subplot1",
".",
"title",
".",
"set_text",
"(",
"'Beat tracking 1D inference model'",
")",
"subplot2",
".",
"title",
".",
"set_text",
"(",
"\"Beat states jumping back weigths\"",
")",
"subplot1",
".",
"text",
"(",
"1",
",",
"2.48",
",",
"f'Beat moment: {local_beat} '",
",",
"horizontalalignment",
"=",
"'right'",
",",
"verticalalignment",
"=",
"'top'",
",",
"transform",
"=",
"subplot2",
".",
"transAxes",
",",
"fontdict",
"=",
"font",
")",
"subplot2",
".",
"text",
"(",
"1",
",",
"1.12",
",",
"f'Local tempo: {local_tempo} (BPM)'",
",",
"horizontalalignment",
"=",
"'right'",
",",
"verticalalignment",
"=",
"'top'",
",",
"transform",
"=",
"subplot2",
".",
"transAxes",
",",
"fontdict",
"=",
"font",
")",
"position",
"=",
"beat_max",
"subplot1",
".",
"axvline",
"(",
"x",
"=",
"position",
")",
"plt",
".",
"pause",
"(",
"0.05",
")",
"subplot1",
".",
"clear",
"(",
")",
"return",
"output",
"[",
"1",
":",
"]"
] |
Running the jump-reward inference for the 1D state spaces over the given activation functions to infer music rhythmic information jointly.
|
[
"Running",
"the",
"jump",
"-",
"reward",
"inference",
"for",
"the",
"1D",
"state",
"spaces",
"over",
"the",
"given",
"activation",
"functions",
"to",
"infer",
"music",
"rhythmic",
"information",
"jointly",
"."
] |
[
"'''\n Running the jump-reward inference for the 1D state spaces over the given activation functions to infer music rhythmic information jointly.\n\n Parameters\n ----------\n activations : numpy array, shape (num_frames, 2)\n Activation function with probabilities corresponding to beats\n and downbeats given in the first and second column, respectively.\n\n Returns\n ----------\n beats, downbeats, local tempo, local meter : numpy array, shape (num_beats, 4)\n \"1\" at the second column indicates the downbeats. \n\n References:\n ---------- \n\n '''",
"# beat transition lambda",
"# downbeat transition lambda",
"# The point of time after which the inference model starts to work. Can be zero!",
"# Information Gate threshold",
"# convert timing information to construct a beat state space",
"# State spaces and observation models initialization",
"# beat tracking state space",
"# downbeat tracking state space",
"# beat tracking observation model",
"# downbeat tracking observation model",
"# output vector initialization for beat, downbeat, tempo and meter",
"# Beat and downbeat belief state initialization",
"# this is just a flag to show the initial transitions",
"# local tempo and meter initialization",
"# loop through all frames to infer beats/downbeats",
"# beat detection",
"# beat transition (motion)",
"# calculating the transition rewards",
"# Thresholding the jump backs",
"# jump back",
"# move forward",
"# Beat correction",
"# beat correction is done only when there is a meaningful activation",
"# normalize beat distribution if its minimum is below a threshold",
"# beat correction rewards calculation",
"# downbeat detection",
"# here the local tempo (:np.argmax(self.st.jump_weights)+1): can be used as the criteria rather than the minimum tempo",
"# downbeat transition (motion)",
"# jump back",
"# move forward",
"# Downbeat correction",
"# normalize downbeat distribution if its minimum is below a threshold",
"# downbeat correction rewards calculation",
"# Beat vs Downbeat mark off",
"# Downbeat probability mass and weights",
"# subplot3.bar(np.arange(1, self.st2.num_states), both_activations[i][0], color='yellow', width=0.4, alpha=0.3)",
"# Downbeat probability mass and weights",
"# activates this when you want to plot the performance",
"# Choosing how often to plot",
"# subplot2.bar(np.arange(self.st.num_states), np.concatenate((np.zeros(self.st.min_interval),self.st.jump_weights)), color='maroon', width=0.4, alpha=0.2)"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 20
| 2,842
| 123
|
e315344370ace661da317ca73ccc0afde3b9ca64
|
mikethicke/fedora-embed
|
src/blocks/src/class-fedora-repository.js
|
[
"MIT"
] |
JavaScript
|
FedoraRepository
|
/**
* Represents a remote Fedora-based repository.
*
* Intended to be a general wrapper for the Fedora API, but currently
* ideosyncratic to the Humanities Commons CORE API, as many of its endpoints
* are locked down and so cannot organically discover URLs of datastreams, etc.
*
* @link https://wiki.lyrasis.org/display/FEDORA38/REST+API
*/
|
Represents a remote Fedora-based repository.
Intended to be a general wrapper for the Fedora API, but currently
ideosyncratic to the Humanities Commons CORE API, as many of its endpoints
are locked down and so cannot organically discover URLs of datastreams, etc.
|
[
"Represents",
"a",
"remote",
"Fedora",
"-",
"based",
"repository",
".",
"Intended",
"to",
"be",
"a",
"general",
"wrapper",
"for",
"the",
"Fedora",
"API",
"but",
"currently",
"ideosyncratic",
"to",
"the",
"Humanities",
"Commons",
"CORE",
"API",
"as",
"many",
"of",
"its",
"endpoints",
"are",
"locked",
"down",
"and",
"so",
"cannot",
"organically",
"discover",
"URLs",
"of",
"datastreams",
"etc",
"."
] |
class FedoraRepository {
constructor( baseURL ) {
this.baseURL = baseURL;
// Descriptions based on field descriptions of Fedora API.
this.searchResultSchema = {
pid : {
description: 'Fedora persistent identifier',
type: 'string',
},
label : {
description: 'Label of object',
type: 'string',
},
state : {
description: 'State of object',
type: 'string'
},
ownerId : {
description: 'ID of object owner',
type: 'string'
},
cDate : {
description: 'Creation date of object',
type: 'string',
format: 'date-time'
},
mDate : {
description: 'Modification date',
type: 'string',
format: 'date-time'
},
dcmDate : {
description: 'Dublin core modification date',
type: 'string',
format: 'date-time'
},
title : {
description: 'Title of the object',
type: 'string'
},
creator : {
description: 'Creator(s) of object',
type: 'array',
items: {
type: 'string'
}
},
subject : {
description: 'Subject(s) of object',
type: 'array',
items: {
type: 'string'
}
},
description : {
description : 'Description of the object',
type: 'string'
},
publisher : {
description : 'Publisher(s) of the object',
type: 'array',
items: {
type: 'string'
}
},
contributor : {
description: 'Contributor(s) to the object',
type: 'array',
items: {
type: 'string'
}
},
date : {
description: 'Dublin Core date (publication date) of object',
type: 'string'
},
type : {
description: 'Dublin Core type of the object',
type: 'string'
},
format : {
description: 'Dublin Core format of the object',
type: 'string'
},
identifier : {
description: 'Dublin Core identifier(s) of the object',
type: 'array',
items: {
type: 'string'
}
},
source : {
description: 'Dublin Core source(s) of object',
type: 'array',
items: {
type: 'string'
}
},
language : {
description: 'Dublin Core language(s) of object',
type: 'array',
items: {
type: 'string'
}
},
relation : {
description: 'Dublin Core relation(s) of object',
type: 'array',
items: {
type: 'string'
}
},
coverage : {
description: 'Dublin Core coverage(s) of object',
type: 'array',
items: {
type: 'string'
}
},
rights : {
description: 'Dublin core rights of object',
type: 'array',
items: {
type: 'string'
}
}
}
}
/**
* Generates a query string from an array of key-comparator-value objects.
*
* @see: https://wiki.lyrasis.org/display/FEDORA38/REST+API#RESTAPI-findObjects
*
* query: a sequence of space-separated conditions. A condition consists of
* a metadata element name followed directly by an operator, followed
* directly by a value. Valid element names are (pid, label, state,
* ownerId, cDate, mDate, dcmDate, title, creator, subject, description,
* publisher, contributor, date, type, format, identifier, source,
* language, relation, coverage, rights). Valid operators are: contains (~),
* equals (=), greater than (>), less than (<), greater than or equals
* (>=), less than or equals (<=). The contains (~) operator may be used in
* combination with the ? and * wildcards to query for simple string
* patterns. Space-separators should be encoded in the URL as %20.
* Operators must be encoded when used in the URL syntax as follows: the
* (=) operator must be encoded as %3D, the (>) operator as %3E, the (<)
* operator as %3C, the (>=) operator as %3E%3D, the (<=) operator as
* %3C%3D, and the (~) operator as %7E. Values may be any string. If the
* string contains a space, the value should begin and end with a single
* quote character ('). If all conditions are met for an object, the object
* is considered a match. Do NOT use this parameter in combination with the
* "terms" parameter
*/
static generateQuery( searchParameters ) {
const comparatorEncodings = {
'=' : '%3D',
'>' : '%3E',
'<' : '%3C',
'~' : '%7E',
'>=' : '%3E%3D',
'<=' : '%3C%3D'
}
const queryString = searchParameters.reduce( ( qString, { field, comparator, searchText } ) => {
if ( searchText ) {
if ( qString ) {
qString += '%20'; // Space separator between query items
}
qString += field;
qString += comparatorEncodings[ comparator ];
qString += "'" + searchText.replace( ' ', '%20' ) + "'";
}
return qString;
}, '' );
return queryString;
}
/**
* Returns a list of fields based on the results schema.
*/
getFieldList() {
return Object.keys( this.searchResultSchema );
}
/**
* Find objects in the repository. Corresponds to the /objects endpoint of
* the Fedora API.
*
* @link https://wiki.lyrasis.org/display/FEDORA38/REST+API#RESTAPI-findObjects
*
* @param Object searchParameters Each object key corresponds to a search
* parameter and the value is the value of that parameter for the search.
*/
findObjects( searchParameters ) {
const fields = this.getFieldList();
const parameterDefaults = fields.reduce( ( params, field ) => {
params[ field ] = true;
return params;
}, {} );
parameterDefaults.maxResults = 25;
parameterDefaults.resultFormat = 'xml';
const newParameters = { ...searchParameters }
if ( newParameters.query && typeof newParameters.query !== 'string' ) {
newParameters.query = FedoraRepository.generateQuery( newParameters.query );
}
const finalParameters = {
...parameterDefaults,
...newParameters
}
const parameterString = Object.entries( finalParameters )
.reduce( ( paramString, params) => {
if ( paramString ) {
paramString += '&';
}
paramString += params[0] + '=' + params[1];
return paramString;
}, '' );
// Humanities Commons doesn't allow cross-origin requests, so need to
// make the request server-side, using the WordPress REST API.
return apiFetch( {
path: '/fem-embed/v1/find',
method: 'POST',
data: { baseURL: this.baseURL, parameterString: parameterString }
} ).then( result => {
return result
} );
}
/**
* Gets data for a particular Humanities Commons item.
*
* Corresponds to the objects/<pid>/datastreams/descMetadata/content
* endpoint of the Humanities Commons API.
*
* @param string pid The Persistent Identifier of the object. On HC, in the form HC:#####
*/
getItemData( pid ) {
return apiFetch( {
path: '/fem-embed/v1/item',
method: 'POST',
data: { baseURL: this.baseURL, pid: pid }
} ).then( result => {
return result
} );
}
}
|
[
"class",
"FedoraRepository",
"{",
"constructor",
"(",
"baseURL",
")",
"{",
"this",
".",
"baseURL",
"=",
"baseURL",
";",
"this",
".",
"searchResultSchema",
"=",
"{",
"pid",
":",
"{",
"description",
":",
"'Fedora persistent identifier'",
",",
"type",
":",
"'string'",
",",
"}",
",",
"label",
":",
"{",
"description",
":",
"'Label of object'",
",",
"type",
":",
"'string'",
",",
"}",
",",
"state",
":",
"{",
"description",
":",
"'State of object'",
",",
"type",
":",
"'string'",
"}",
",",
"ownerId",
":",
"{",
"description",
":",
"'ID of object owner'",
",",
"type",
":",
"'string'",
"}",
",",
"cDate",
":",
"{",
"description",
":",
"'Creation date of object'",
",",
"type",
":",
"'string'",
",",
"format",
":",
"'date-time'",
"}",
",",
"mDate",
":",
"{",
"description",
":",
"'Modification date'",
",",
"type",
":",
"'string'",
",",
"format",
":",
"'date-time'",
"}",
",",
"dcmDate",
":",
"{",
"description",
":",
"'Dublin core modification date'",
",",
"type",
":",
"'string'",
",",
"format",
":",
"'date-time'",
"}",
",",
"title",
":",
"{",
"description",
":",
"'Title of the object'",
",",
"type",
":",
"'string'",
"}",
",",
"creator",
":",
"{",
"description",
":",
"'Creator(s) of object'",
",",
"type",
":",
"'array'",
",",
"items",
":",
"{",
"type",
":",
"'string'",
"}",
"}",
",",
"subject",
":",
"{",
"description",
":",
"'Subject(s) of object'",
",",
"type",
":",
"'array'",
",",
"items",
":",
"{",
"type",
":",
"'string'",
"}",
"}",
",",
"description",
":",
"{",
"description",
":",
"'Description of the object'",
",",
"type",
":",
"'string'",
"}",
",",
"publisher",
":",
"{",
"description",
":",
"'Publisher(s) of the object'",
",",
"type",
":",
"'array'",
",",
"items",
":",
"{",
"type",
":",
"'string'",
"}",
"}",
",",
"contributor",
":",
"{",
"description",
":",
"'Contributor(s) to the object'",
",",
"type",
":",
"'array'",
",",
"items",
":",
"{",
"type",
":",
"'string'",
"}",
"}",
",",
"date",
":",
"{",
"description",
":",
"'Dublin Core date (publication date) of object'",
",",
"type",
":",
"'string'",
"}",
",",
"type",
":",
"{",
"description",
":",
"'Dublin Core type of the object'",
",",
"type",
":",
"'string'",
"}",
",",
"format",
":",
"{",
"description",
":",
"'Dublin Core format of the object'",
",",
"type",
":",
"'string'",
"}",
",",
"identifier",
":",
"{",
"description",
":",
"'Dublin Core identifier(s) of the object'",
",",
"type",
":",
"'array'",
",",
"items",
":",
"{",
"type",
":",
"'string'",
"}",
"}",
",",
"source",
":",
"{",
"description",
":",
"'Dublin Core source(s) of object'",
",",
"type",
":",
"'array'",
",",
"items",
":",
"{",
"type",
":",
"'string'",
"}",
"}",
",",
"language",
":",
"{",
"description",
":",
"'Dublin Core language(s) of object'",
",",
"type",
":",
"'array'",
",",
"items",
":",
"{",
"type",
":",
"'string'",
"}",
"}",
",",
"relation",
":",
"{",
"description",
":",
"'Dublin Core relation(s) of object'",
",",
"type",
":",
"'array'",
",",
"items",
":",
"{",
"type",
":",
"'string'",
"}",
"}",
",",
"coverage",
":",
"{",
"description",
":",
"'Dublin Core coverage(s) of object'",
",",
"type",
":",
"'array'",
",",
"items",
":",
"{",
"type",
":",
"'string'",
"}",
"}",
",",
"rights",
":",
"{",
"description",
":",
"'Dublin core rights of object'",
",",
"type",
":",
"'array'",
",",
"items",
":",
"{",
"type",
":",
"'string'",
"}",
"}",
"}",
"}",
"static",
"generateQuery",
"(",
"searchParameters",
")",
"{",
"const",
"comparatorEncodings",
"=",
"{",
"'='",
":",
"'%3D'",
",",
"'>'",
":",
"'%3E'",
",",
"'<'",
":",
"'%3C'",
",",
"'~'",
":",
"'%7E'",
",",
"'>='",
":",
"'%3E%3D'",
",",
"'<='",
":",
"'%3C%3D'",
"}",
"const",
"queryString",
"=",
"searchParameters",
".",
"reduce",
"(",
"(",
"qString",
",",
"{",
"field",
",",
"comparator",
",",
"searchText",
"}",
")",
"=>",
"{",
"if",
"(",
"searchText",
")",
"{",
"if",
"(",
"qString",
")",
"{",
"qString",
"+=",
"'%20'",
";",
"}",
"qString",
"+=",
"field",
";",
"qString",
"+=",
"comparatorEncodings",
"[",
"comparator",
"]",
";",
"qString",
"+=",
"\"'\"",
"+",
"searchText",
".",
"replace",
"(",
"' '",
",",
"'%20'",
")",
"+",
"\"'\"",
";",
"}",
"return",
"qString",
";",
"}",
",",
"''",
")",
";",
"return",
"queryString",
";",
"}",
"getFieldList",
"(",
")",
"{",
"return",
"Object",
".",
"keys",
"(",
"this",
".",
"searchResultSchema",
")",
";",
"}",
"findObjects",
"(",
"searchParameters",
")",
"{",
"const",
"fields",
"=",
"this",
".",
"getFieldList",
"(",
")",
";",
"const",
"parameterDefaults",
"=",
"fields",
".",
"reduce",
"(",
"(",
"params",
",",
"field",
")",
"=>",
"{",
"params",
"[",
"field",
"]",
"=",
"true",
";",
"return",
"params",
";",
"}",
",",
"{",
"}",
")",
";",
"parameterDefaults",
".",
"maxResults",
"=",
"25",
";",
"parameterDefaults",
".",
"resultFormat",
"=",
"'xml'",
";",
"const",
"newParameters",
"=",
"{",
"...",
"searchParameters",
"}",
"if",
"(",
"newParameters",
".",
"query",
"&&",
"typeof",
"newParameters",
".",
"query",
"!==",
"'string'",
")",
"{",
"newParameters",
".",
"query",
"=",
"FedoraRepository",
".",
"generateQuery",
"(",
"newParameters",
".",
"query",
")",
";",
"}",
"const",
"finalParameters",
"=",
"{",
"...",
"parameterDefaults",
",",
"...",
"newParameters",
"}",
"const",
"parameterString",
"=",
"Object",
".",
"entries",
"(",
"finalParameters",
")",
".",
"reduce",
"(",
"(",
"paramString",
",",
"params",
")",
"=>",
"{",
"if",
"(",
"paramString",
")",
"{",
"paramString",
"+=",
"'&'",
";",
"}",
"paramString",
"+=",
"params",
"[",
"0",
"]",
"+",
"'='",
"+",
"params",
"[",
"1",
"]",
";",
"return",
"paramString",
";",
"}",
",",
"''",
")",
";",
"return",
"apiFetch",
"(",
"{",
"path",
":",
"'/fem-embed/v1/find'",
",",
"method",
":",
"'POST'",
",",
"data",
":",
"{",
"baseURL",
":",
"this",
".",
"baseURL",
",",
"parameterString",
":",
"parameterString",
"}",
"}",
")",
".",
"then",
"(",
"result",
"=>",
"{",
"return",
"result",
"}",
")",
";",
"}",
"getItemData",
"(",
"pid",
")",
"{",
"return",
"apiFetch",
"(",
"{",
"path",
":",
"'/fem-embed/v1/item'",
",",
"method",
":",
"'POST'",
",",
"data",
":",
"{",
"baseURL",
":",
"this",
".",
"baseURL",
",",
"pid",
":",
"pid",
"}",
"}",
")",
".",
"then",
"(",
"result",
"=>",
"{",
"return",
"result",
"}",
")",
";",
"}",
"}"
] |
Represents a remote Fedora-based repository.
|
[
"Represents",
"a",
"remote",
"Fedora",
"-",
"based",
"repository",
"."
] |
[
"// Descriptions based on field descriptions of Fedora API.",
"/**\n\t * Generates a query string from an array of key-comparator-value objects.\n\t *\n\t * @see: https://wiki.lyrasis.org/display/FEDORA38/REST+API#RESTAPI-findObjects\n\t * \n\t * query: a sequence of space-separated conditions. A condition consists of\n\t * a metadata element name followed directly by an operator, followed\n\t * directly by a value. Valid element names are (pid, label, state,\n\t * ownerId, cDate, mDate, dcmDate, title, creator, subject, description,\n\t * publisher, contributor, date, type, format, identifier, source,\n\t * language, relation, coverage, rights). Valid operators are: contains (~),\n\t * equals (=), greater than (>), less than (<), greater than or equals\n\t * (>=), less than or equals (<=). The contains (~) operator may be used in\n\t * combination with the ? and * wildcards to query for simple string\n\t * patterns. Space-separators should be encoded in the URL as %20.\n\t * Operators must be encoded when used in the URL syntax as follows: the\n\t * (=) operator must be encoded as %3D, the (>) operator as %3E, the (<)\n\t * operator as %3C, the (>=) operator as %3E%3D, the (<=) operator as\n\t * %3C%3D, and the (~) operator as %7E. Values may be any string. If the\n\t * string contains a space, the value should begin and end with a single\n\t * quote character ('). If all conditions are met for an object, the object\n\t * is considered a match. Do NOT use this parameter in combination with the\n\t * \"terms\" parameter\n\t */",
"// Space separator between query items",
"/**\n\t * Returns a list of fields based on the results schema.\n\t */",
"/**\n\t * Find objects in the repository. Corresponds to the /objects endpoint of\n\t * the Fedora API.\n\t *\n\t * @link https://wiki.lyrasis.org/display/FEDORA38/REST+API#RESTAPI-findObjects\n\t *\n\t * @param Object searchParameters Each object key corresponds to a search\n\t * parameter and the value is the value of that parameter for the search. \n\t */",
"// Humanities Commons doesn't allow cross-origin requests, so need to",
"// make the request server-side, using the WordPress REST API.",
"/**\n\t * Gets data for a particular Humanities Commons item.\n\t *\n\t * Corresponds to the objects/<pid>/datastreams/descMetadata/content\n\t * endpoint of the Humanities Commons API.\n\t *\n\t * @param string pid The Persistent Identifier of the object. On HC, in the form HC:#####\n\t */"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 20
| 1,859
| 85
|
271e5b684ad84fae07791f4b9bf60d7359eb6cab
|
avantida/azure-libraries-for-net
|
src/ResourceManagement/Network/AzureReachabilityReportImpl.cs
|
[
"MIT"
] |
C#
|
AzureReachabilityReportImpl
|
/// <summary>
/// The implementation of AzureReachabilityReport.
/// </summary>
///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50Lm5ldHdvcmsuaW1wbGVtZW50YXRpb24uQXp1cmVSZWFjaGFiaWxpdHlSZXBvcnRJbXBs
|
The implementation of AzureReachabilityReport.
|
[
"The",
"implementation",
"of",
"AzureReachabilityReport",
"."
] |
internal partial class AzureReachabilityReportImpl :
Executable<Microsoft.Azure.Management.Network.Fluent.IAzureReachabilityReport>,
IAzureReachabilityReport,
IDefinition
{
private AzureReachabilityReportInner inner;
private AzureReachabilityReportParameters parameters = new AzureReachabilityReportParameters();
private NetworkWatcherImpl parent;
internal AzureReachabilityReportImpl(NetworkWatcherImpl parent)
{
this.parent = parent;
}
public string AggregationLevel()
{
return inner.AggregationLevel;
}
public AzureReachabilityReportParameters AzureReachabilityReportParameters()
{
return parameters;
}
public override async Task<IAzureReachabilityReport> ExecuteAsync(CancellationToken cancellationToken = default(CancellationToken), bool multiThreaded = true)
{
this.inner =
await parent.Manager.Inner.NetworkWatchers.GetAzureReachabilityReportAsync(parent.ResourceGroupName,
parent.Name, parameters, cancellationToken);
return this;
}
public AzureReachabilityReportInner Inner()
{
return this.inner;
}
public INetworkWatcher Parent()
{
return parent;
}
public AzureReachabilityReportLocation ProviderLocation()
{
return inner.ProviderLocation;
}
public IReadOnlyList<Models.AzureReachabilityReportItem> ReachabilityReport()
{
List<AzureReachabilityReportItem> result = new List<AzureReachabilityReportItem>();
if (this.Inner().ReachabilityReport != null)
{
result.AddRange(this.Inner().ReachabilityReport);
}
return result.AsReadOnly();
}
public IWithExecute WithAzureLocations(params string[] azureLocations)
{
this.parameters.AzureLocations = new List<String>();
foreach (var id in azureLocations)
{
this.parameters.AzureLocations.Add(id);
}
return this;
}
public AzureReachabilityReportImpl WithEndTime(DateTime endTime)
{
parameters.EndTime = endTime;
return this;
}
public AzureReachabilityReportImpl WithProviderLocation(string country)
{
parameters.ProviderLocation = new AzureReachabilityReportLocation(country: country);
return this;
}
public AzureReachabilityReportImpl WithProviderLocation(string country, string state)
{
parameters.ProviderLocation = new AzureReachabilityReportLocation(country: country, state: state);
return this;
}
public AzureReachabilityReportImpl WithProviderLocation(string country, string state, string city)
{
parameters.ProviderLocation = new AzureReachabilityReportLocation(country: country, state: state, city: city);
return this;
}
public IWithExecute WithProviders(params string[] providers)
{
this.parameters.Providers = new List<String>();
foreach (var id in providers)
{
this.parameters.Providers.Add(id);
}
return this;
}
public AzureReachabilityReportImpl WithStartTime(DateTime startTime)
{
parameters.StartTime = startTime;
return this;
}
AzureReachabilityReportInner IHasInner<AzureReachabilityReportInner>.Inner
{
get { return inner; }
}
}
|
[
"internal",
"partial",
"class",
"AzureReachabilityReportImpl",
":",
"Executable",
"<",
"Microsoft",
".",
"Azure",
".",
"Management",
".",
"Network",
".",
"Fluent",
".",
"IAzureReachabilityReport",
">",
",",
"IAzureReachabilityReport",
",",
"IDefinition",
"{",
"private",
"AzureReachabilityReportInner",
"inner",
";",
"private",
"AzureReachabilityReportParameters",
"parameters",
"=",
"new",
"AzureReachabilityReportParameters",
"(",
")",
";",
"private",
"NetworkWatcherImpl",
"parent",
";",
"internal",
"AzureReachabilityReportImpl",
"(",
"NetworkWatcherImpl",
"parent",
")",
"{",
"this",
".",
"parent",
"=",
"parent",
";",
"}",
"public",
"string",
"AggregationLevel",
"(",
")",
"{",
"return",
"inner",
".",
"AggregationLevel",
";",
"}",
"public",
"AzureReachabilityReportParameters",
"AzureReachabilityReportParameters",
"(",
")",
"{",
"return",
"parameters",
";",
"}",
"public",
"override",
"async",
"Task",
"<",
"IAzureReachabilityReport",
">",
"ExecuteAsync",
"(",
"CancellationToken",
"cancellationToken",
"=",
"default",
"(",
"CancellationToken",
")",
",",
"bool",
"multiThreaded",
"=",
"true",
")",
"{",
"this",
".",
"inner",
"=",
"await",
"parent",
".",
"Manager",
".",
"Inner",
".",
"NetworkWatchers",
".",
"GetAzureReachabilityReportAsync",
"(",
"parent",
".",
"ResourceGroupName",
",",
"parent",
".",
"Name",
",",
"parameters",
",",
"cancellationToken",
")",
";",
"return",
"this",
";",
"}",
"public",
"AzureReachabilityReportInner",
"Inner",
"(",
")",
"{",
"return",
"this",
".",
"inner",
";",
"}",
"public",
"INetworkWatcher",
"Parent",
"(",
")",
"{",
"return",
"parent",
";",
"}",
"public",
"AzureReachabilityReportLocation",
"ProviderLocation",
"(",
")",
"{",
"return",
"inner",
".",
"ProviderLocation",
";",
"}",
"public",
"IReadOnlyList",
"<",
"Models",
".",
"AzureReachabilityReportItem",
">",
"ReachabilityReport",
"(",
")",
"{",
"List",
"<",
"AzureReachabilityReportItem",
">",
"result",
"=",
"new",
"List",
"<",
"AzureReachabilityReportItem",
">",
"(",
")",
";",
"if",
"(",
"this",
".",
"Inner",
"(",
")",
".",
"ReachabilityReport",
"!=",
"null",
")",
"{",
"result",
".",
"AddRange",
"(",
"this",
".",
"Inner",
"(",
")",
".",
"ReachabilityReport",
")",
";",
"}",
"return",
"result",
".",
"AsReadOnly",
"(",
")",
";",
"}",
"public",
"IWithExecute",
"WithAzureLocations",
"(",
"params",
"string",
"[",
"]",
"azureLocations",
")",
"{",
"this",
".",
"parameters",
".",
"AzureLocations",
"=",
"new",
"List",
"<",
"String",
">",
"(",
")",
";",
"foreach",
"(",
"var",
"id",
"in",
"azureLocations",
")",
"{",
"this",
".",
"parameters",
".",
"AzureLocations",
".",
"Add",
"(",
"id",
")",
";",
"}",
"return",
"this",
";",
"}",
"public",
"AzureReachabilityReportImpl",
"WithEndTime",
"(",
"DateTime",
"endTime",
")",
"{",
"parameters",
".",
"EndTime",
"=",
"endTime",
";",
"return",
"this",
";",
"}",
"public",
"AzureReachabilityReportImpl",
"WithProviderLocation",
"(",
"string",
"country",
")",
"{",
"parameters",
".",
"ProviderLocation",
"=",
"new",
"AzureReachabilityReportLocation",
"(",
"country",
":",
"country",
")",
";",
"return",
"this",
";",
"}",
"public",
"AzureReachabilityReportImpl",
"WithProviderLocation",
"(",
"string",
"country",
",",
"string",
"state",
")",
"{",
"parameters",
".",
"ProviderLocation",
"=",
"new",
"AzureReachabilityReportLocation",
"(",
"country",
":",
"country",
",",
"state",
":",
"state",
")",
";",
"return",
"this",
";",
"}",
"public",
"AzureReachabilityReportImpl",
"WithProviderLocation",
"(",
"string",
"country",
",",
"string",
"state",
",",
"string",
"city",
")",
"{",
"parameters",
".",
"ProviderLocation",
"=",
"new",
"AzureReachabilityReportLocation",
"(",
"country",
":",
"country",
",",
"state",
":",
"state",
",",
"city",
":",
"city",
")",
";",
"return",
"this",
";",
"}",
"public",
"IWithExecute",
"WithProviders",
"(",
"params",
"string",
"[",
"]",
"providers",
")",
"{",
"this",
".",
"parameters",
".",
"Providers",
"=",
"new",
"List",
"<",
"String",
">",
"(",
")",
";",
"foreach",
"(",
"var",
"id",
"in",
"providers",
")",
"{",
"this",
".",
"parameters",
".",
"Providers",
".",
"Add",
"(",
"id",
")",
";",
"}",
"return",
"this",
";",
"}",
"public",
"AzureReachabilityReportImpl",
"WithStartTime",
"(",
"DateTime",
"startTime",
")",
"{",
"parameters",
".",
"StartTime",
"=",
"startTime",
";",
"return",
"this",
";",
"}",
"AzureReachabilityReportInner",
"IHasInner",
"<",
"AzureReachabilityReportInner",
">",
".",
"Inner",
"{",
"get",
"{",
"return",
"inner",
";",
"}",
"}",
"}"
] |
The implementation of AzureReachabilityReport.
|
[
"The",
"implementation",
"of",
"AzureReachabilityReport",
"."
] |
[
"///GENMHASH:B35D63B671CF6D8D001FDE561D5CFDCF:425AAA90FA44C25BF65D98CF87FB3E57",
"///GENMHASH:7310C299B150ACDDC5DAEFC3DB165FDF:C90872EB6C3409AAF1FEFC9F53B7B848",
"///GENMHASH:AF5B92F7D602ADD6835472AD2633A663:7A31B9AAF5466328BC49ECCDA3102A92",
"///GENMHASH:637F0A3522F2C635C23E54FAAD79CBEA:4891FA97A857767ACE1138F0F8DDD55F",
"///GENMHASH:C852FF1A7022E39B3C33C4B996B5E6D6:7F78D90F6498B472DCB9BE14FD336BC9",
"///GENMHASH:FD5D5A8D6904B467321E345BE1FA424E:8AB87020DE6C711CD971F3D80C33DD83",
"///GENMHASH:F544AD5C2AD1F62DB8EA5D7AD1FD5021:D1C74C8C0866743532927974EA5CFB3C",
"///GENMHASH:4FE530CF34C22FA621A20EC7342C5275:2CB8A0991EDDDCF72582C9946B051367",
"///GENMHASH:DBE908B51C2C3ACC09544176732C78B3:DBA36CA1C37ED3DF4C9385ED3FCE6A83",
"///GENMHASH:C4FF9250259C19995B551B017771F384:E389C065ACF7E72C2E6424B83216EEB7",
"///GENMHASH:66208FE3A0A4FC1FECC54CDA052552A1:65E1F47AFBE80C48C09EAA1BFBFB9292",
"///GENMHASH:402F2398A6E1237B28538BDC22CBA48F:F543AC24C3901A10BA5FBCA03E276F23",
"///GENMHASH:B31E557AA2AFC2C8F55DF55DAFA84670:53866A5F2C01767FD42720B1DAF2EB99",
"///GENMHASH:F524E41F91C15EEEE804F9935D7208A0:576339BA7B4830E4C48F96C379A9FA2C",
"///GENMHASH:99D252694C3BCB6EB9B8CD48B089D0F9:01DBD646E603079CE2678567D30B518A"
] |
[
{
"param": "IAzureReachabilityReport",
"type": null
},
{
"param": "IDefinition",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "IAzureReachabilityReport",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "IDefinition",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 14
| 641
| 103
|
d8b334f3ef7c0435fd51a6386a3a8a9ad816655e
|
cheind/gcsl
|
gcsl/__init__.py
|
[
"MIT"
] |
Python
|
ExperienceBuffer
|
Experience buffer of limited capacity.
This buffers stores (state, action, horizon) tuples of trajectories
in a flat memory layout. Here horizon is time (offset >= 0) to tuple
representing the final trajectory state.
Once the capacity is reached oldest tuples will get discarded first,
leaving potentially partial trajectories in memory. Since we only
required that a future state is available for relabeling, this does
not pose a problem.
|
Experience buffer of limited capacity.
This buffers stores (state, action, horizon) tuples of trajectories
in a flat memory layout. Here horizon is time (offset >= 0) to tuple
representing the final trajectory state.
Once the capacity is reached oldest tuples will get discarded first,
leaving potentially partial trajectories in memory. Since we only
required that a future state is available for relabeling, this does
not pose a problem.
|
[
"Experience",
"buffer",
"of",
"limited",
"capacity",
".",
"This",
"buffers",
"stores",
"(",
"state",
"action",
"horizon",
")",
"tuples",
"of",
"trajectories",
"in",
"a",
"flat",
"memory",
"layout",
".",
"Here",
"horizon",
"is",
"time",
"(",
"offset",
">",
"=",
"0",
")",
"to",
"tuple",
"representing",
"the",
"final",
"trajectory",
"state",
".",
"Once",
"the",
"capacity",
"is",
"reached",
"oldest",
"tuples",
"will",
"get",
"discarded",
"first",
"leaving",
"potentially",
"partial",
"trajectories",
"in",
"memory",
".",
"Since",
"we",
"only",
"required",
"that",
"a",
"future",
"state",
"is",
"available",
"for",
"relabeling",
"this",
"does",
"not",
"pose",
"a",
"problem",
"."
] |
class ExperienceBuffer:
"""Experience buffer of limited capacity.
This buffers stores (state, action, horizon) tuples of trajectories
in a flat memory layout. Here horizon is time (offset >= 0) to tuple
representing the final trajectory state.
Once the capacity is reached oldest tuples will get discarded first,
leaving potentially partial trajectories in memory. Since we only
required that a future state is available for relabeling, this does
not pose a problem.
"""
def __init__(self, max_experiences) -> None:
self.memory = deque(maxlen=max_experiences)
def insert(self, trajectories: List[Trajectory]):
"""Append experiences. This might remove oldest values
if capacity of the buffer is reached."""
for t in itertools.chain(*trajectories):
self.memory.append(t)
def sample(
self,
num_experiences: int,
goal_relabel_fn: GoalRelabelFn,
max_horizon: int = None,
) -> List[SAGHTuple]:
"""Uniform randomly sample N (state,action,goal,horizon) tuples."""
indices = np.random.choice(len(self.memory), size=num_experiences)
if max_horizon is None:
max_horizon = np.iinfo(int).max
tuples = [self._relabel(idx, goal_relabel_fn, max_horizon) for idx in indices]
return tuples
def __len__(self):
return len(self.memory)
def _relabel(
self, idx: int, goal_relabel_fn: GoalRelabelFn, max_horizon: int
) -> SAGHTuple:
t0 = self.memory[idx]
s, a, _, h = t0
if h > 0:
# If not last element of trajectory, we can sample
# a new horizon, which defines the target tuple.
h = int(np.random.randint(1, min(h + 1, max_horizon)))
t1 = self.memory[idx + h]
# Note, h(t0) >= h(t1)
g = goal_relabel_fn(t0, t1)
return (s, a, g, h)
|
[
"class",
"ExperienceBuffer",
":",
"def",
"__init__",
"(",
"self",
",",
"max_experiences",
")",
"->",
"None",
":",
"self",
".",
"memory",
"=",
"deque",
"(",
"maxlen",
"=",
"max_experiences",
")",
"def",
"insert",
"(",
"self",
",",
"trajectories",
":",
"List",
"[",
"Trajectory",
"]",
")",
":",
"\"\"\"Append experiences. This might remove oldest values\n if capacity of the buffer is reached.\"\"\"",
"for",
"t",
"in",
"itertools",
".",
"chain",
"(",
"*",
"trajectories",
")",
":",
"self",
".",
"memory",
".",
"append",
"(",
"t",
")",
"def",
"sample",
"(",
"self",
",",
"num_experiences",
":",
"int",
",",
"goal_relabel_fn",
":",
"GoalRelabelFn",
",",
"max_horizon",
":",
"int",
"=",
"None",
",",
")",
"->",
"List",
"[",
"SAGHTuple",
"]",
":",
"\"\"\"Uniform randomly sample N (state,action,goal,horizon) tuples.\"\"\"",
"indices",
"=",
"np",
".",
"random",
".",
"choice",
"(",
"len",
"(",
"self",
".",
"memory",
")",
",",
"size",
"=",
"num_experiences",
")",
"if",
"max_horizon",
"is",
"None",
":",
"max_horizon",
"=",
"np",
".",
"iinfo",
"(",
"int",
")",
".",
"max",
"tuples",
"=",
"[",
"self",
".",
"_relabel",
"(",
"idx",
",",
"goal_relabel_fn",
",",
"max_horizon",
")",
"for",
"idx",
"in",
"indices",
"]",
"return",
"tuples",
"def",
"__len__",
"(",
"self",
")",
":",
"return",
"len",
"(",
"self",
".",
"memory",
")",
"def",
"_relabel",
"(",
"self",
",",
"idx",
":",
"int",
",",
"goal_relabel_fn",
":",
"GoalRelabelFn",
",",
"max_horizon",
":",
"int",
")",
"->",
"SAGHTuple",
":",
"t0",
"=",
"self",
".",
"memory",
"[",
"idx",
"]",
"s",
",",
"a",
",",
"_",
",",
"h",
"=",
"t0",
"if",
"h",
">",
"0",
":",
"h",
"=",
"int",
"(",
"np",
".",
"random",
".",
"randint",
"(",
"1",
",",
"min",
"(",
"h",
"+",
"1",
",",
"max_horizon",
")",
")",
")",
"t1",
"=",
"self",
".",
"memory",
"[",
"idx",
"+",
"h",
"]",
"g",
"=",
"goal_relabel_fn",
"(",
"t0",
",",
"t1",
")",
"return",
"(",
"s",
",",
"a",
",",
"g",
",",
"h",
")"
] |
Experience buffer of limited capacity.
|
[
"Experience",
"buffer",
"of",
"limited",
"capacity",
"."
] |
[
"\"\"\"Experience buffer of limited capacity.\n\n This buffers stores (state, action, horizon) tuples of trajectories\n in a flat memory layout. Here horizon is time (offset >= 0) to tuple\n representing the final trajectory state.\n\n Once the capacity is reached oldest tuples will get discarded first,\n leaving potentially partial trajectories in memory. Since we only\n required that a future state is available for relabeling, this does\n not pose a problem.\n \"\"\"",
"\"\"\"Append experiences. This might remove oldest values\n if capacity of the buffer is reached.\"\"\"",
"\"\"\"Uniform randomly sample N (state,action,goal,horizon) tuples.\"\"\"",
"# If not last element of trajectory, we can sample",
"# a new horizon, which defines the target tuple.",
"# Note, h(t0) >= h(t1)"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 16
| 468
| 96
|
61d6ac1422f3d5b813eadbb4b38f2e6e2284e905
|
shy950521/ecs-samples
|
aws-net-workshop/aws-net-workshop/examples_bonus/_04_Lifecycle.cs
|
[
"Apache-2.0"
] |
C#
|
_04_Lifecycle
|
/// <summary>
/// Configure bucket lifecycle
/// </summary>
/// <remarks>
/// Lifecycle configuration enables you to specify the lifecycle management
/// of objects in a bucket. The configuration is a set of one or more rules,
/// where each rule defines an action to apply to a group of objects.
/// The expiration action allows you to specify when the objects expire, then
/// ECS will delete the expired object.
///
/// This sample will go through the following steps:
///
/// 1. Create a bucket
/// 2. Configure bucket lifecycle rules to automatically set an expiration time
/// 3. Retrieve the bucket lifecycle configuration and verify the rules were applied
/// 4. Delete the bucket lifecycle configuration
/// 5. Retrieve the bucket lifecycle configuration and verify it is empty
/// 6. Delete the bucket
///
/// </remarks>
|
Configure bucket lifecycle
|
[
"Configure",
"bucket",
"lifecycle"
] |
class _04_Lifecycle
{
public static void Main(string[] args)
{
AmazonS3Client s3 = AWSS3Factory.getS3Client();
String bucketName = String.Join("-", AWSS3Factory.S3_BUCKET, DateTime.Now.ToString("yyyyMMddHHmmss"));
Console.Write(string.Format(" [*] Creating bucket '{0}'... ", bucketName));
PutBucketResponse pbRes = s3.PutBucket(bucketName);
if (pbRes.HttpStatusCode != System.Net.HttpStatusCode.OK)
{
Console.WriteLine("fail");
Console.ReadLine();
System.Environment.Exit(1);
}
Console.WriteLine("done");
Console.Write(string.Format(" [*] Updating lifecycle configuration for bucket '{0}'... ", bucketName));
LifecycleConfiguration newConfiguration = new LifecycleConfiguration
{
Rules = new List<LifecycleRule>
{
// Rule
new LifecycleRule
{
Prefix = "Test-",
Expiration = new LifecycleRuleExpiration { Days = 5 },
Status = LifecycleRuleStatus.Enabled
},
// Rule
new LifecycleRule
{
Prefix = "Logs/",
Expiration = new LifecycleRuleExpiration { Days = 2 },
Id = "log-file-removal",
Status = LifecycleRuleStatus.Enabled
}
}
};
PutLifecycleConfigurationRequest plcReq = new PutLifecycleConfigurationRequest
{
BucketName = bucketName,
Configuration = newConfiguration
};
PutLifecycleConfigurationResponse plcRes = s3.PutLifecycleConfiguration(plcReq);
if (plcRes.HttpStatusCode != System.Net.HttpStatusCode.OK)
{
Console.WriteLine("fail");
Console.ReadLine();
System.Environment.Exit(1);
}
Console.WriteLine("done");
Console.Write(string.Format(" [*] Retrieving current lifecycle configuration for bucket '{0}'... ", bucketName));
GetLifecycleConfigurationResponse glcRes = s3.GetLifecycleConfiguration(bucketName);
if (glcRes.HttpStatusCode != System.Net.HttpStatusCode.OK)
{
Console.WriteLine("fail");
Console.ReadLine();
System.Environment.Exit(1);
}
Console.WriteLine("done");
Console.WriteLine(String.Format(" [x] Configuration contains {0} rules", glcRes.Configuration.Rules.Count));
foreach (LifecycleRule rule in glcRes.Configuration.Rules)
{
Console.WriteLine(" [x] Rule:");
Console.WriteLine(" [x] Prefix = " + rule.Prefix);
Console.WriteLine(" [x] Expiration (days) = " + rule.Expiration.Days);
Console.WriteLine(" [x] Id = " + rule.Id);
Console.WriteLine(" [x] Status = " + rule.Status);
}
Console.Write(String.Format(" [*] Deleting current lifecycle configuration for bucket '{0}'... ", bucketName));
DeleteLifecycleConfigurationResponse dlcRes = s3.DeleteLifecycleConfiguration(bucketName);
if (dlcRes.HttpStatusCode != System.Net.HttpStatusCode.NoContent)
{
Console.WriteLine("fail");
Console.ReadLine();
System.Environment.Exit(1);
}
Console.WriteLine("done");
Console.Write(String.Format(" [*] Verifying current lifecycle rules for bucket '{0}' are empty... ", bucketName));
LifecycleConfiguration configuration = s3.GetLifecycleConfiguration(bucketName).Configuration;
if (configuration.Rules.Count != 0)
{
Console.WriteLine("fail");
Console.ReadLine();
System.Environment.Exit(1);
}
Console.WriteLine("done");
Console.Write(String.Format(" [*] Deleting bucket '{0}'... ", bucketName));
DeleteBucketResponse dbRes = s3.DeleteBucket(bucketName);
if (dbRes.HttpStatusCode != System.Net.HttpStatusCode.NoContent)
{
Console.WriteLine("fail");
Console.ReadLine();
System.Environment.Exit(1);
}
Console.WriteLine("done");
Console.WriteLine(" [*] Example is completed. Press any key to exit...");
Console.ReadLine();
}
}
|
[
"class",
"_04_Lifecycle",
"{",
"public",
"static",
"void",
"Main",
"(",
"string",
"[",
"]",
"args",
")",
"{",
"AmazonS3Client",
"s3",
"=",
"AWSS3Factory",
".",
"getS3Client",
"(",
")",
";",
"String",
"bucketName",
"=",
"String",
".",
"Join",
"(",
"\"",
"-",
"\"",
",",
"AWSS3Factory",
".",
"S3_BUCKET",
",",
"DateTime",
".",
"Now",
".",
"ToString",
"(",
"\"",
"yyyyMMddHHmmss",
"\"",
")",
")",
";",
"Console",
".",
"Write",
"(",
"string",
".",
"Format",
"(",
"\"",
" [*] Creating bucket '{0}'... ",
"\"",
",",
"bucketName",
")",
")",
";",
"PutBucketResponse",
"pbRes",
"=",
"s3",
".",
"PutBucket",
"(",
"bucketName",
")",
";",
"if",
"(",
"pbRes",
".",
"HttpStatusCode",
"!=",
"System",
".",
"Net",
".",
"HttpStatusCode",
".",
"OK",
")",
"{",
"Console",
".",
"WriteLine",
"(",
"\"",
"fail",
"\"",
")",
";",
"Console",
".",
"ReadLine",
"(",
")",
";",
"System",
".",
"Environment",
".",
"Exit",
"(",
"1",
")",
";",
"}",
"Console",
".",
"WriteLine",
"(",
"\"",
"done",
"\"",
")",
";",
"Console",
".",
"Write",
"(",
"string",
".",
"Format",
"(",
"\"",
" [*] Updating lifecycle configuration for bucket '{0}'... ",
"\"",
",",
"bucketName",
")",
")",
";",
"LifecycleConfiguration",
"newConfiguration",
"=",
"new",
"LifecycleConfiguration",
"{",
"Rules",
"=",
"new",
"List",
"<",
"LifecycleRule",
">",
"{",
"cyc",
"eRule",
"{",
"Prefix",
"=",
"\"",
"Test-",
"\"",
",",
"Expiration",
"=",
"new",
"LifecycleRuleExpiration",
"{",
"Days",
"=",
"5",
"}",
",",
"Status",
"=",
"LifecycleRuleStatus",
".",
"Enabled",
"}",
",",
"cyc",
"eRule",
"{",
"Prefix",
"=",
"\"",
"Logs/",
"\"",
",",
"Expiration",
"=",
"new",
"LifecycleRuleExpiration",
"{",
"Days",
"=",
"2",
"}",
",",
"Id",
"=",
"\"",
"log-file-removal",
"\"",
",",
"Status",
"=",
"LifecycleRuleStatus",
".",
"Enabled",
"}",
"}",
"}",
";",
"PutLifecycleConfigurationRequest",
"plcReq",
"=",
"new",
"PutLifecycleConfigurationRequest",
"{",
"BucketName",
"=",
"bucketName",
",",
"Configuration",
"=",
"newConfiguration",
"}",
";",
"PutLifecycleConfigurationResponse",
"plcRes",
"=",
"s3",
".",
"PutLifecycleConfiguration",
"(",
"plcReq",
")",
";",
"if",
"(",
"plcRes",
".",
"HttpStatusCode",
"!=",
"System",
".",
"Net",
".",
"HttpStatusCode",
".",
"OK",
")",
"{",
"Console",
".",
"WriteLine",
"(",
"\"",
"fail",
"\"",
")",
";",
"Console",
".",
"ReadLine",
"(",
")",
";",
"System",
".",
"Environment",
".",
"Exit",
"(",
"1",
")",
";",
"}",
"Console",
".",
"WriteLine",
"(",
"\"",
"done",
"\"",
")",
";",
"Console",
".",
"Write",
"(",
"string",
".",
"Format",
"(",
"\"",
" [*] Retrieving current lifecycle configuration for bucket '{0}'... ",
"\"",
",",
"bucketName",
")",
")",
";",
"GetLifecycleConfigurationResponse",
"glcRes",
"=",
"s3",
".",
"GetLifecycleConfiguration",
"(",
"bucketName",
")",
";",
"if",
"(",
"glcRes",
".",
"HttpStatusCode",
"!=",
"System",
".",
"Net",
".",
"HttpStatusCode",
".",
"OK",
")",
"{",
"Console",
".",
"WriteLine",
"(",
"\"",
"fail",
"\"",
")",
";",
"Console",
".",
"ReadLine",
"(",
")",
";",
"System",
".",
"Environment",
".",
"Exit",
"(",
"1",
")",
";",
"}",
"Console",
".",
"WriteLine",
"(",
"\"",
"done",
"\"",
")",
";",
"Console",
".",
"WriteLine",
"(",
"String",
".",
"Format",
"(",
"\"",
" [x] Configuration contains {0} rules",
"\"",
",",
"glcRes",
".",
"Configuration",
".",
"Rules",
".",
"Count",
")",
")",
";",
"foreach",
"(",
"LifecycleRule",
"rule",
"in",
"glcRes",
".",
"Configuration",
".",
"Rules",
")",
"{",
"Console",
".",
"WriteLine",
"(",
"\"",
" [x] Rule:",
"\"",
")",
";",
"Console",
".",
"WriteLine",
"(",
"\"",
" [x] Prefix = ",
"\"",
"+",
"rule",
".",
"Prefix",
")",
";",
"Console",
".",
"WriteLine",
"(",
"\"",
" [x] Expiration (days) = ",
"\"",
"+",
"rule",
".",
"Expiration",
".",
"Days",
")",
";",
"Console",
".",
"WriteLine",
"(",
"\"",
" [x] Id = ",
"\"",
"+",
"rule",
".",
"Id",
")",
";",
"Console",
".",
"WriteLine",
"(",
"\"",
" [x] Status = ",
"\"",
"+",
"rule",
".",
"Status",
")",
";",
"}",
"Console",
".",
"Write",
"(",
"String",
".",
"Format",
"(",
"\"",
" [*] Deleting current lifecycle configuration for bucket '{0}'... ",
"\"",
",",
"bucketName",
")",
")",
";",
"DeleteLifecycleConfigurationResponse",
"dlcRes",
"=",
"s3",
".",
"DeleteLifecycleConfiguration",
"(",
"bucketName",
")",
";",
"if",
"(",
"dlcRes",
".",
"HttpStatusCode",
"!=",
"System",
".",
"Net",
".",
"HttpStatusCode",
".",
"NoContent",
")",
"{",
"Console",
".",
"WriteLine",
"(",
"\"",
"fail",
"\"",
")",
";",
"Console",
".",
"ReadLine",
"(",
")",
";",
"System",
".",
"Environment",
".",
"Exit",
"(",
"1",
")",
";",
"}",
"Console",
".",
"WriteLine",
"(",
"\"",
"done",
"\"",
")",
";",
"Console",
".",
"Write",
"(",
"String",
".",
"Format",
"(",
"\"",
" [*] Verifying current lifecycle rules for bucket '{0}' are empty... ",
"\"",
",",
"bucketName",
")",
")",
";",
"LifecycleConfiguration",
"configuration",
"=",
"s3",
".",
"GetLifecycleConfiguration",
"(",
"bucketName",
")",
".",
"Configuration",
";",
"if",
"(",
"configuration",
".",
"Rules",
".",
"Count",
"!=",
"0",
")",
"{",
"Console",
".",
"WriteLine",
"(",
"\"",
"fail",
"\"",
")",
";",
"Console",
".",
"ReadLine",
"(",
")",
";",
"System",
".",
"Environment",
".",
"Exit",
"(",
"1",
")",
";",
"}",
"Console",
".",
"WriteLine",
"(",
"\"",
"done",
"\"",
")",
";",
"Console",
".",
"Write",
"(",
"String",
".",
"Format",
"(",
"\"",
" [*] Deleting bucket '{0}'... ",
"\"",
",",
"bucketName",
")",
")",
";",
"DeleteBucketResponse",
"dbRes",
"=",
"s3",
".",
"DeleteBucket",
"(",
"bucketName",
")",
";",
"if",
"(",
"dbRes",
".",
"HttpStatusCode",
"!=",
"System",
".",
"Net",
".",
"HttpStatusCode",
".",
"NoContent",
")",
"{",
"Console",
".",
"WriteLine",
"(",
"\"",
"fail",
"\"",
")",
";",
"Console",
".",
"ReadLine",
"(",
")",
";",
"System",
".",
"Environment",
".",
"Exit",
"(",
"1",
")",
";",
"}",
"Console",
".",
"WriteLine",
"(",
"\"",
"done",
"\"",
")",
";",
"Console",
".",
"WriteLine",
"(",
"\"",
" [*] Example is completed. Press any key to exit...",
"\"",
")",
";",
"Console",
".",
"ReadLine",
"(",
")",
";",
"}",
"}"
] |
Configure bucket lifecycle
|
[
"Configure",
"bucket",
"lifecycle"
] |
[
"// create the AWS S3 client",
"//************************//",
"// 1. Create a bucket //",
"//************************//",
"//*************************************//",
"// 2. Configure bucket lifecycle rules //",
"//*************************************//",
"to delete keys with prefix \"Test-\" after 5 days",
"to delete keys in subdirectory \"Logs\" after 2 days",
"//************************************************//",
"// 3. Retrieve the bucket lifecycle configuration //",
"//************************************************//",
"//**********************************************//",
"// 4. Delete the bucket lifecycle configuration //",
"//**********************************************//",
"//************************//",
"// 5. Delete the bucket //",
"//************************//"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": [
{
"identifier": "remarks",
"docstring": "Lifecycle configuration enables you to specify the lifecycle management\nof objects in a bucket. The configuration is a set of one or more rules,\nwhere each rule defines an action to apply to a group of objects.\nThe expiration action allows you to specify when the objects expire, then\nECS will delete the expired object.\n\nThis sample will go through the following steps.\n\n1. Create a bucket\n2. Configure bucket lifecycle rules to automatically set an expiration time\n3. Retrieve the bucket lifecycle configuration and verify the rules were applied\n4. Delete the bucket lifecycle configuration\n5. Retrieve the bucket lifecycle configuration and verify it is empty\n6. Delete the bucket",
"docstring_tokens": [
"Lifecycle",
"configuration",
"enables",
"you",
"to",
"specify",
"the",
"lifecycle",
"management",
"of",
"objects",
"in",
"a",
"bucket",
".",
"The",
"configuration",
"is",
"a",
"set",
"of",
"one",
"or",
"more",
"rules",
"where",
"each",
"rule",
"defines",
"an",
"action",
"to",
"apply",
"to",
"a",
"group",
"of",
"objects",
".",
"The",
"expiration",
"action",
"allows",
"you",
"to",
"specify",
"when",
"the",
"objects",
"expire",
"then",
"ECS",
"will",
"delete",
"the",
"expired",
"object",
".",
"This",
"sample",
"will",
"go",
"through",
"the",
"following",
"steps",
".",
"1",
".",
"Create",
"a",
"bucket",
"2",
".",
"Configure",
"bucket",
"lifecycle",
"rules",
"to",
"automatically",
"set",
"an",
"expiration",
"time",
"3",
".",
"Retrieve",
"the",
"bucket",
"lifecycle",
"configuration",
"and",
"verify",
"the",
"rules",
"were",
"applied",
"4",
".",
"Delete",
"the",
"bucket",
"lifecycle",
"configuration",
"5",
".",
"Retrieve",
"the",
"bucket",
"lifecycle",
"configuration",
"and",
"verify",
"it",
"is",
"empty",
"6",
".",
"Delete",
"the",
"bucket"
]
}
]
}
| false
| 19
| 829
| 179
|
cc985f17c3871eac17a506b3baab01673daa63c1
|
Richard-Tarbell/pysalt
|
saltspec/WavelengthSolution.py
|
[
"BSD-3-Clause"
] |
Python
|
WavelengthSolution
|
Wavelength Solution is a task describing the functional form for
transforming pixel position to wavelength. The inputs for this task
are the given pixel position and the corresponding wavelength. The user
selects an input functional form and order for that form. The task then
calculates the coefficients for that form. Possible options for the
wavelength solution include polynomial, legendre, spline.
|
Wavelength Solution is a task describing the functional form for
transforming pixel position to wavelength. The inputs for this task
are the given pixel position and the corresponding wavelength. The user
selects an input functional form and order for that form. The task then
calculates the coefficients for that form. Possible options for the
wavelength solution include polynomial, legendre, spline.
|
[
"Wavelength",
"Solution",
"is",
"a",
"task",
"describing",
"the",
"functional",
"form",
"for",
"transforming",
"pixel",
"position",
"to",
"wavelength",
".",
"The",
"inputs",
"for",
"this",
"task",
"are",
"the",
"given",
"pixel",
"position",
"and",
"the",
"corresponding",
"wavelength",
".",
"The",
"user",
"selects",
"an",
"input",
"functional",
"form",
"and",
"order",
"for",
"that",
"form",
".",
"The",
"task",
"then",
"calculates",
"the",
"coefficients",
"for",
"that",
"form",
".",
"Possible",
"options",
"for",
"the",
"wavelength",
"solution",
"include",
"polynomial",
"legendre",
"spline",
"."
] |
class WavelengthSolution:
"""Wavelength Solution is a task describing the functional form for
transforming pixel position to wavelength. The inputs for this task
are the given pixel position and the corresponding wavelength. The user
selects an input functional form and order for that form. The task then
calculates the coefficients for that form. Possible options for the
wavelength solution include polynomial, legendre, spline.
"""
func_options = ['poly', 'polynomial', 'spline', 'legendre',
'chebyshev', 'model']
def __init__(self, x, w, function='poly', order=3, niter=5, thresh=3,
sgraph=None, cfit='both', xlen=3162, yval=0, domain=None):
self.sgraph = sgraph
self.function = function
self.order = order
self.niter = niter
self.thresh = thresh
self.cfit = cfit
self.xlen = xlen
self.yval = yval
self.set_array(x, w)
self.set_func(domain=domain)
def set_array(self, x, w):
self.x_arr = x
self.w_arr = w
def set_thresh(self, thresh):
self.thresh = thresh
def set_niter(self, niter):
self.niter = niter
def set_func(self, domain=None):
if self.function in [
'poly', 'polynomial', 'spline', 'legendre', 'chebyshev']:
self.func = interfit(self.x_arr, self.w_arr,
function=self.function,
order=self.order, niter=self.niter,
thresh=self.thresh)
if domain:
self.func.func.domain=domain
if self.function == 'model':
self.func = ModelSolution(self.x_arr, self.w_arr,
sgraph=self.sgraph, xlen=self.xlen,
yval=self.yval, order=self.order)
def fit(self):
if self.function in [
'poly', 'polynomial', 'spline', 'legendre', 'chebyshev']:
self.func.interfit()
self.coef = self.func.func.parameters
if self.function in ['model']:
self.func.fit(cfit=self.cfit)
self.coef = np.array([c() for c in self.func.coef])
# self.set_coef(coef)
def set_coef(self, coef):
if self.function in [
'poly', 'polynomial', 'spline', 'legendre', 'chebyshev']:
self.func.func.parameters= coef
self.coef = self.func.func.parameters
if self.function in ['model']:
for i in range(len(self.func.coef)):
self.func.coef[i].set(coef[i])
self.coef = np.array([c() for c in self.func.coef])
def value(self, x):
return self.func(x)
def invvalue(self, w):
"""Given a wavelength, return the pixel position
"""
return w
def sigma(self, x, y):
"""Return the RMS of the fit """
# if there aren't many data points return the RMS
if len(x) < 4:
sig = (((y - self.value(x)) ** 2).mean()) ** 0.5
# Otherwise get the average distance between the 16th and
# 84th percentiles
# of the residuals divided by 2
# This should be less sensitive to outliers
else:
# Sort the residuals
rsdls = np.sort(y - self.value(x))
# Get the correct indices and take their difference
sig = (rsdls[int(0.84 * len(rsdls))] -
rsdls[int(0.16 * len(rsdls))]) / 2.0
return sig
def chisq(self, x, y, err):
"""Return the chi^2 of the fit"""
return (((y - self.value(x)) / err) ** 2).sum()
|
[
"class",
"WavelengthSolution",
":",
"func_options",
"=",
"[",
"'poly'",
",",
"'polynomial'",
",",
"'spline'",
",",
"'legendre'",
",",
"'chebyshev'",
",",
"'model'",
"]",
"def",
"__init__",
"(",
"self",
",",
"x",
",",
"w",
",",
"function",
"=",
"'poly'",
",",
"order",
"=",
"3",
",",
"niter",
"=",
"5",
",",
"thresh",
"=",
"3",
",",
"sgraph",
"=",
"None",
",",
"cfit",
"=",
"'both'",
",",
"xlen",
"=",
"3162",
",",
"yval",
"=",
"0",
",",
"domain",
"=",
"None",
")",
":",
"self",
".",
"sgraph",
"=",
"sgraph",
"self",
".",
"function",
"=",
"function",
"self",
".",
"order",
"=",
"order",
"self",
".",
"niter",
"=",
"niter",
"self",
".",
"thresh",
"=",
"thresh",
"self",
".",
"cfit",
"=",
"cfit",
"self",
".",
"xlen",
"=",
"xlen",
"self",
".",
"yval",
"=",
"yval",
"self",
".",
"set_array",
"(",
"x",
",",
"w",
")",
"self",
".",
"set_func",
"(",
"domain",
"=",
"domain",
")",
"def",
"set_array",
"(",
"self",
",",
"x",
",",
"w",
")",
":",
"self",
".",
"x_arr",
"=",
"x",
"self",
".",
"w_arr",
"=",
"w",
"def",
"set_thresh",
"(",
"self",
",",
"thresh",
")",
":",
"self",
".",
"thresh",
"=",
"thresh",
"def",
"set_niter",
"(",
"self",
",",
"niter",
")",
":",
"self",
".",
"niter",
"=",
"niter",
"def",
"set_func",
"(",
"self",
",",
"domain",
"=",
"None",
")",
":",
"if",
"self",
".",
"function",
"in",
"[",
"'poly'",
",",
"'polynomial'",
",",
"'spline'",
",",
"'legendre'",
",",
"'chebyshev'",
"]",
":",
"self",
".",
"func",
"=",
"interfit",
"(",
"self",
".",
"x_arr",
",",
"self",
".",
"w_arr",
",",
"function",
"=",
"self",
".",
"function",
",",
"order",
"=",
"self",
".",
"order",
",",
"niter",
"=",
"self",
".",
"niter",
",",
"thresh",
"=",
"self",
".",
"thresh",
")",
"if",
"domain",
":",
"self",
".",
"func",
".",
"func",
".",
"domain",
"=",
"domain",
"if",
"self",
".",
"function",
"==",
"'model'",
":",
"self",
".",
"func",
"=",
"ModelSolution",
"(",
"self",
".",
"x_arr",
",",
"self",
".",
"w_arr",
",",
"sgraph",
"=",
"self",
".",
"sgraph",
",",
"xlen",
"=",
"self",
".",
"xlen",
",",
"yval",
"=",
"self",
".",
"yval",
",",
"order",
"=",
"self",
".",
"order",
")",
"def",
"fit",
"(",
"self",
")",
":",
"if",
"self",
".",
"function",
"in",
"[",
"'poly'",
",",
"'polynomial'",
",",
"'spline'",
",",
"'legendre'",
",",
"'chebyshev'",
"]",
":",
"self",
".",
"func",
".",
"interfit",
"(",
")",
"self",
".",
"coef",
"=",
"self",
".",
"func",
".",
"func",
".",
"parameters",
"if",
"self",
".",
"function",
"in",
"[",
"'model'",
"]",
":",
"self",
".",
"func",
".",
"fit",
"(",
"cfit",
"=",
"self",
".",
"cfit",
")",
"self",
".",
"coef",
"=",
"np",
".",
"array",
"(",
"[",
"c",
"(",
")",
"for",
"c",
"in",
"self",
".",
"func",
".",
"coef",
"]",
")",
"def",
"set_coef",
"(",
"self",
",",
"coef",
")",
":",
"if",
"self",
".",
"function",
"in",
"[",
"'poly'",
",",
"'polynomial'",
",",
"'spline'",
",",
"'legendre'",
",",
"'chebyshev'",
"]",
":",
"self",
".",
"func",
".",
"func",
".",
"parameters",
"=",
"coef",
"self",
".",
"coef",
"=",
"self",
".",
"func",
".",
"func",
".",
"parameters",
"if",
"self",
".",
"function",
"in",
"[",
"'model'",
"]",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"func",
".",
"coef",
")",
")",
":",
"self",
".",
"func",
".",
"coef",
"[",
"i",
"]",
".",
"set",
"(",
"coef",
"[",
"i",
"]",
")",
"self",
".",
"coef",
"=",
"np",
".",
"array",
"(",
"[",
"c",
"(",
")",
"for",
"c",
"in",
"self",
".",
"func",
".",
"coef",
"]",
")",
"def",
"value",
"(",
"self",
",",
"x",
")",
":",
"return",
"self",
".",
"func",
"(",
"x",
")",
"def",
"invvalue",
"(",
"self",
",",
"w",
")",
":",
"\"\"\"Given a wavelength, return the pixel position\n\n \"\"\"",
"return",
"w",
"def",
"sigma",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"\"\"\"Return the RMS of the fit \"\"\"",
"if",
"len",
"(",
"x",
")",
"<",
"4",
":",
"sig",
"=",
"(",
"(",
"(",
"y",
"-",
"self",
".",
"value",
"(",
"x",
")",
")",
"**",
"2",
")",
".",
"mean",
"(",
")",
")",
"**",
"0.5",
"else",
":",
"rsdls",
"=",
"np",
".",
"sort",
"(",
"y",
"-",
"self",
".",
"value",
"(",
"x",
")",
")",
"sig",
"=",
"(",
"rsdls",
"[",
"int",
"(",
"0.84",
"*",
"len",
"(",
"rsdls",
")",
")",
"]",
"-",
"rsdls",
"[",
"int",
"(",
"0.16",
"*",
"len",
"(",
"rsdls",
")",
")",
"]",
")",
"/",
"2.0",
"return",
"sig",
"def",
"chisq",
"(",
"self",
",",
"x",
",",
"y",
",",
"err",
")",
":",
"\"\"\"Return the chi^2 of the fit\"\"\"",
"return",
"(",
"(",
"(",
"y",
"-",
"self",
".",
"value",
"(",
"x",
")",
")",
"/",
"err",
")",
"**",
"2",
")",
".",
"sum",
"(",
")"
] |
Wavelength Solution is a task describing the functional form for
transforming pixel position to wavelength.
|
[
"Wavelength",
"Solution",
"is",
"a",
"task",
"describing",
"the",
"functional",
"form",
"for",
"transforming",
"pixel",
"position",
"to",
"wavelength",
"."
] |
[
"\"\"\"Wavelength Solution is a task describing the functional form for\n transforming pixel position to wavelength. The inputs for this task\n are the given pixel position and the corresponding wavelength. The user\n selects an input functional form and order for that form. The task then\n calculates the coefficients for that form. Possible options for the\n wavelength solution include polynomial, legendre, spline.\n \"\"\"",
"# self.set_coef(coef)",
"\"\"\"Given a wavelength, return the pixel position\n\n \"\"\"",
"\"\"\"Return the RMS of the fit \"\"\"",
"# if there aren't many data points return the RMS",
"# Otherwise get the average distance between the 16th and",
"# 84th percentiles",
"# of the residuals divided by 2",
"# This should be less sensitive to outliers",
"# Sort the residuals",
"# Get the correct indices and take their difference",
"\"\"\"Return the chi^2 of the fit\"\"\""
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 19
| 901
| 84
|
7f76e700431bfb9022e4522eaa0314a0c8e4d546
|
ArnasAmankavicius/ProjectDV
|
src/main/java/com/lanterna/TerminalPosition.java
|
[
"Apache-2.0"
] |
Java
|
TerminalPosition
|
/**
* A 2-d position in 'terminal space'. Please note that the coordinates are 0-indexed, meaning 0x0 is the top left
* corner of the terminal. This object is immutable so you cannot change it after it has been created. Instead, you
* can easily create modified 'clones' by using the 'with' methods.
*
* @author Martin
*/
|
A 2-d position in 'terminal space'. Please note that the coordinates are 0-indexed, meaning 0x0 is the top left
corner of the terminal. This object is immutable so you cannot change it after it has been created. Instead, you
can easily create modified 'clones' by using the 'with' methods.
@author Martin
|
[
"A",
"2",
"-",
"d",
"position",
"in",
"'",
"terminal",
"space",
"'",
".",
"Please",
"note",
"that",
"the",
"coordinates",
"are",
"0",
"-",
"indexed",
"meaning",
"0x0",
"is",
"the",
"top",
"left",
"corner",
"of",
"the",
"terminal",
".",
"This",
"object",
"is",
"immutable",
"so",
"you",
"cannot",
"change",
"it",
"after",
"it",
"has",
"been",
"created",
".",
"Instead",
"you",
"can",
"easily",
"create",
"modified",
"'",
"clones",
"'",
"by",
"using",
"the",
"'",
"with",
"'",
"methods",
".",
"@author",
"Martin"
] |
public class TerminalPosition implements Comparable<TerminalPosition> {
/**
* Constant for the top-left corner (0x0)
*/
public static final TerminalPosition TOP_LEFT_CORNER = new TerminalPosition(0, 0);
/**
* Constant for the 1x1 position (one offset in both directions from top-left)
*/
public static final TerminalPosition OFFSET_1x1 = new TerminalPosition(1, 1);
private final int row;
private final int column;
/**
* Creates a new TerminalPosition object, which represents a location on the screen. There is no check to verify
* that the position you specified is within the size of the current terminal and you can specify negative positions
* as well.
*
* @param column Column of the location, or the "x" coordinate, zero indexed (the first column is 0)
* @param row Row of the location, or the "y" coordinate, zero indexed (the first row is 0)
*/
public TerminalPosition(int column, int row) {
this.row = row;
this.column = column;
}
/**
* Returns the index of the column this position is representing, zero indexed (the first column has index 0).
*
* @return Index of the column this position has
*/
public int getColumn() {
return column;
}
/**
* Returns the index of the row this position is representing, zero indexed (the first row has index 0)
*
* @return Index of the row this position has
*/
public int getRow() {
return row;
}
/**
* Creates a new TerminalPosition object representing a position with the same column index as this but with a
* supplied row index.
*
* @param row Index of the row for the new position
* @return A TerminalPosition object with the same column as this but with a specified row index
*/
public TerminalPosition withRow(int row) {
if (row == 0 && this.column == 0) {
return TOP_LEFT_CORNER;
}
return new TerminalPosition(this.column, row);
}
/**
* Creates a new TerminalPosition object representing a position with the same row index as this but with a
* supplied column index.
*
* @param column Index of the column for the new position
* @return A TerminalPosition object with the same row as this but with a specified column index
*/
public TerminalPosition withColumn(int column) {
if (column == 0 && this.row == 0) {
return TOP_LEFT_CORNER;
}
return new TerminalPosition(column, this.row);
}
/**
* Creates a new TerminalPosition object representing a position on the same row, but with a column offset by a
* supplied value. Calling this method with delta 0 will return this, calling it with a positive delta will return
* a terminal position <i>delta</i> number of columns to the right and for negative numbers the same to the left.
*
* @param delta Column offset
* @return New terminal position based off this one but with an applied offset
*/
public TerminalPosition withRelativeColumn(int delta) {
if (delta == 0) {
return this;
}
return withColumn(column + delta);
}
/**
* Creates a new TerminalPosition object representing a position on the same column, but with a row offset by a
* supplied value. Calling this method with delta 0 will return this, calling it with a positive delta will return
* a terminal position <i>delta</i> number of rows to the down and for negative numbers the same up.
*
* @param delta Row offset
* @return New terminal position based off this one but with an applied offset
*/
public TerminalPosition withRelativeRow(int delta) {
if (delta == 0) {
return this;
}
return withRow(row + delta);
}
/**
* Creates a new TerminalPosition object that is 'translated' by an amount of rows and columns specified by another
* TerminalPosition. Same as calling
* <code>withRelativeRow(translate.getRow()).withRelativeColumn(translate.getColumn())</code>
*
* @param translate How many columns and rows to translate
* @return New TerminalPosition that is the result of the original with added translation
*/
public TerminalPosition withRelative(TerminalPosition translate) {
return withRelative(translate.getColumn(), translate.getRow());
}
/**
* Creates a new TerminalPosition object that is 'translated' by an amount of rows and columns specified by the two
* parameters. Same as calling
* <code>withRelativeRow(deltaRow).withRelativeColumn(deltaColumn)</code>
*
* @param deltaColumn How many columns to move from the current position in the new TerminalPosition
* @param deltaRow How many rows to move from the current position in the new TerminalPosition
* @return New TerminalPosition that is the result of the original position with added translation
*/
public TerminalPosition withRelative(int deltaColumn, int deltaRow) {
return withRelativeRow(deltaRow).withRelativeColumn(deltaColumn);
}
/**
* Returns itself if it is equal to the supplied position, otherwise the supplied position. You can use this if you
* have a position field which is frequently recalculated but often resolves to the same; it will keep the same
* object in memory instead of swapping it out every cycle.
*
* @param position Position you want to return
* @return Itself if this position equals the position passed in, otherwise the position passed in
*/
public TerminalPosition with(TerminalPosition position) {
if (equals(position)) {
return this;
}
return position;
}
@Override
public int compareTo(TerminalPosition o) {
if (row < o.row) {
return -1;
} else if (row == o.row) {
if (column < o.column) {
return -1;
} else if (column == o.column) {
return 0;
}
}
return 1;
}
@Override
public String toString() {
return "[" + column + ":" + row + "]";
}
@Override
public int hashCode() {
int hash = 3;
hash = 23 * hash + this.row;
hash = 23 * hash + this.column;
return hash;
}
public boolean equals(int columnIndex, int rowIndex) {
return this.column == columnIndex &&
this.row == rowIndex;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final TerminalPosition other = (TerminalPosition) obj;
return this.row == other.row && this.column == other.column;
}
}
|
[
"public",
"class",
"TerminalPosition",
"implements",
"Comparable",
"<",
"TerminalPosition",
">",
"{",
"/**\n * Constant for the top-left corner (0x0)\n */",
"public",
"static",
"final",
"TerminalPosition",
"TOP_LEFT_CORNER",
"=",
"new",
"TerminalPosition",
"(",
"0",
",",
"0",
")",
";",
"/**\n * Constant for the 1x1 position (one offset in both directions from top-left)\n */",
"public",
"static",
"final",
"TerminalPosition",
"OFFSET_1x1",
"=",
"new",
"TerminalPosition",
"(",
"1",
",",
"1",
")",
";",
"private",
"final",
"int",
"row",
";",
"private",
"final",
"int",
"column",
";",
"/**\n * Creates a new TerminalPosition object, which represents a location on the screen. There is no check to verify\n * that the position you specified is within the size of the current terminal and you can specify negative positions\n * as well.\n *\n * @param column Column of the location, or the \"x\" coordinate, zero indexed (the first column is 0)\n * @param row Row of the location, or the \"y\" coordinate, zero indexed (the first row is 0)\n */",
"public",
"TerminalPosition",
"(",
"int",
"column",
",",
"int",
"row",
")",
"{",
"this",
".",
"row",
"=",
"row",
";",
"this",
".",
"column",
"=",
"column",
";",
"}",
"/**\n * Returns the index of the column this position is representing, zero indexed (the first column has index 0).\n *\n * @return Index of the column this position has\n */",
"public",
"int",
"getColumn",
"(",
")",
"{",
"return",
"column",
";",
"}",
"/**\n * Returns the index of the row this position is representing, zero indexed (the first row has index 0)\n *\n * @return Index of the row this position has\n */",
"public",
"int",
"getRow",
"(",
")",
"{",
"return",
"row",
";",
"}",
"/**\n * Creates a new TerminalPosition object representing a position with the same column index as this but with a\n * supplied row index.\n *\n * @param row Index of the row for the new position\n * @return A TerminalPosition object with the same column as this but with a specified row index\n */",
"public",
"TerminalPosition",
"withRow",
"(",
"int",
"row",
")",
"{",
"if",
"(",
"row",
"==",
"0",
"&&",
"this",
".",
"column",
"==",
"0",
")",
"{",
"return",
"TOP_LEFT_CORNER",
";",
"}",
"return",
"new",
"TerminalPosition",
"(",
"this",
".",
"column",
",",
"row",
")",
";",
"}",
"/**\n * Creates a new TerminalPosition object representing a position with the same row index as this but with a\n * supplied column index.\n *\n * @param column Index of the column for the new position\n * @return A TerminalPosition object with the same row as this but with a specified column index\n */",
"public",
"TerminalPosition",
"withColumn",
"(",
"int",
"column",
")",
"{",
"if",
"(",
"column",
"==",
"0",
"&&",
"this",
".",
"row",
"==",
"0",
")",
"{",
"return",
"TOP_LEFT_CORNER",
";",
"}",
"return",
"new",
"TerminalPosition",
"(",
"column",
",",
"this",
".",
"row",
")",
";",
"}",
"/**\n * Creates a new TerminalPosition object representing a position on the same row, but with a column offset by a\n * supplied value. Calling this method with delta 0 will return this, calling it with a positive delta will return\n * a terminal position <i>delta</i> number of columns to the right and for negative numbers the same to the left.\n *\n * @param delta Column offset\n * @return New terminal position based off this one but with an applied offset\n */",
"public",
"TerminalPosition",
"withRelativeColumn",
"(",
"int",
"delta",
")",
"{",
"if",
"(",
"delta",
"==",
"0",
")",
"{",
"return",
"this",
";",
"}",
"return",
"withColumn",
"(",
"column",
"+",
"delta",
")",
";",
"}",
"/**\n * Creates a new TerminalPosition object representing a position on the same column, but with a row offset by a\n * supplied value. Calling this method with delta 0 will return this, calling it with a positive delta will return\n * a terminal position <i>delta</i> number of rows to the down and for negative numbers the same up.\n *\n * @param delta Row offset\n * @return New terminal position based off this one but with an applied offset\n */",
"public",
"TerminalPosition",
"withRelativeRow",
"(",
"int",
"delta",
")",
"{",
"if",
"(",
"delta",
"==",
"0",
")",
"{",
"return",
"this",
";",
"}",
"return",
"withRow",
"(",
"row",
"+",
"delta",
")",
";",
"}",
"/**\n * Creates a new TerminalPosition object that is 'translated' by an amount of rows and columns specified by another\n * TerminalPosition. Same as calling\n * <code>withRelativeRow(translate.getRow()).withRelativeColumn(translate.getColumn())</code>\n *\n * @param translate How many columns and rows to translate\n * @return New TerminalPosition that is the result of the original with added translation\n */",
"public",
"TerminalPosition",
"withRelative",
"(",
"TerminalPosition",
"translate",
")",
"{",
"return",
"withRelative",
"(",
"translate",
".",
"getColumn",
"(",
")",
",",
"translate",
".",
"getRow",
"(",
")",
")",
";",
"}",
"/**\n * Creates a new TerminalPosition object that is 'translated' by an amount of rows and columns specified by the two\n * parameters. Same as calling\n * <code>withRelativeRow(deltaRow).withRelativeColumn(deltaColumn)</code>\n *\n * @param deltaColumn How many columns to move from the current position in the new TerminalPosition\n * @param deltaRow How many rows to move from the current position in the new TerminalPosition\n * @return New TerminalPosition that is the result of the original position with added translation\n */",
"public",
"TerminalPosition",
"withRelative",
"(",
"int",
"deltaColumn",
",",
"int",
"deltaRow",
")",
"{",
"return",
"withRelativeRow",
"(",
"deltaRow",
")",
".",
"withRelativeColumn",
"(",
"deltaColumn",
")",
";",
"}",
"/**\n * Returns itself if it is equal to the supplied position, otherwise the supplied position. You can use this if you\n * have a position field which is frequently recalculated but often resolves to the same; it will keep the same\n * object in memory instead of swapping it out every cycle.\n *\n * @param position Position you want to return\n * @return Itself if this position equals the position passed in, otherwise the position passed in\n */",
"public",
"TerminalPosition",
"with",
"(",
"TerminalPosition",
"position",
")",
"{",
"if",
"(",
"equals",
"(",
"position",
")",
")",
"{",
"return",
"this",
";",
"}",
"return",
"position",
";",
"}",
"@",
"Override",
"public",
"int",
"compareTo",
"(",
"TerminalPosition",
"o",
")",
"{",
"if",
"(",
"row",
"<",
"o",
".",
"row",
")",
"{",
"return",
"-",
"1",
";",
"}",
"else",
"if",
"(",
"row",
"==",
"o",
".",
"row",
")",
"{",
"if",
"(",
"column",
"<",
"o",
".",
"column",
")",
"{",
"return",
"-",
"1",
";",
"}",
"else",
"if",
"(",
"column",
"==",
"o",
".",
"column",
")",
"{",
"return",
"0",
";",
"}",
"}",
"return",
"1",
";",
"}",
"@",
"Override",
"public",
"String",
"toString",
"(",
")",
"{",
"return",
"\"",
"[",
"\"",
"+",
"column",
"+",
"\"",
":",
"\"",
"+",
"row",
"+",
"\"",
"]",
"\"",
";",
"}",
"@",
"Override",
"public",
"int",
"hashCode",
"(",
")",
"{",
"int",
"hash",
"=",
"3",
";",
"hash",
"=",
"23",
"*",
"hash",
"+",
"this",
".",
"row",
";",
"hash",
"=",
"23",
"*",
"hash",
"+",
"this",
".",
"column",
";",
"return",
"hash",
";",
"}",
"public",
"boolean",
"equals",
"(",
"int",
"columnIndex",
",",
"int",
"rowIndex",
")",
"{",
"return",
"this",
".",
"column",
"==",
"columnIndex",
"&&",
"this",
".",
"row",
"==",
"rowIndex",
";",
"}",
"@",
"Override",
"public",
"boolean",
"equals",
"(",
"Object",
"obj",
")",
"{",
"if",
"(",
"obj",
"==",
"null",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"getClass",
"(",
")",
"!=",
"obj",
".",
"getClass",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"final",
"TerminalPosition",
"other",
"=",
"(",
"TerminalPosition",
")",
"obj",
";",
"return",
"this",
".",
"row",
"==",
"other",
".",
"row",
"&&",
"this",
".",
"column",
"==",
"other",
".",
"column",
";",
"}",
"}"
] |
A 2-d position in 'terminal space'.
|
[
"A",
"2",
"-",
"d",
"position",
"in",
"'",
"terminal",
"space",
"'",
"."
] |
[] |
[
{
"param": "Comparable<TerminalPosition>",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "Comparable<TerminalPosition>",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 13
| 1,516
| 82
|
b8f3e37b2f45cf32e19bbaea8b2035acb61ae18f
|
YanaPIIDXer/MapsSDKForUnityTest
|
Assets/GoogleMaps/Examples/04_Advanced/Pathfinding/Scripts/PathFindingView.cs
|
[
"MIT"
] |
C#
|
PathFindingView
|
/// <summary>
/// Note: Road Lattice support is a beta feature subject to performance considerations and future
/// changes
///
/// This class handles the UI of the PathFinding example.
/// In particular it enables users to:
/// - Show/Hide nodes
/// - Pick a destination for the main character
/// - Activate AI agents to track the main character
/// - Display the active search path between AI agents and their target
/// </summary>
|
Road Lattice support is a beta feature subject to performance considerations and future
changes
This class handles the UI of the PathFinding example.
In particular it enables users to:
Show/Hide nodes
Pick a destination for the main character
Activate AI agents to track the main character
Display the active search path between AI agents and their target
|
[
"Road",
"Lattice",
"support",
"is",
"a",
"beta",
"feature",
"subject",
"to",
"performance",
"considerations",
"and",
"future",
"changes",
"This",
"class",
"handles",
"the",
"UI",
"of",
"the",
"PathFinding",
"example",
".",
"In",
"particular",
"it",
"enables",
"users",
"to",
":",
"Show",
"/",
"Hide",
"nodes",
"Pick",
"a",
"destination",
"for",
"the",
"main",
"character",
"Activate",
"AI",
"agents",
"to",
"track",
"the",
"main",
"character",
"Display",
"the",
"active",
"search",
"path",
"between",
"AI",
"agents",
"and",
"their",
"target"
] |
public class PathFindingView : MonoBehaviour {
[Tooltip("The Base Map Loader handles the Maps Service initialization and basic event flow.")]
public BaseMapLoader BaseMapLoader;
[Tooltip("Current latitude of the floating origin.")]
public Text latValue;
[Tooltip("Current longitude of the floating origin.")]
public Text lngValue;
[Tooltip("Camera controller WSAD + Up/Down")]
public CameraController cameraController;
[Tooltip("The PathFinding example")]
public PathFindingExample PathFindingExample;
[Tooltip("Reference to the nodes debug visualizer")]
public RoadLatticeNodesVisualizer RoadLatticeNodesVisualizer;
[Tooltip("Controls the visibility of the road lattice")]
public Toggle ShowRoadLatticeToggle;
[Tooltip("Controls the display of all active paths between AI agents and their targets")]
public Toggle ShowAIPathsToggle;
[Tooltip("Activates the search behavior of AI Agents")]
public Toggle ActivateAIBotsToggle;
private bool IsReady;
void Start() {
IsReady = true;
if (BaseMapLoader == null) {
Debug.LogError(ExampleErrors.MissingParameter(
this, BaseMapLoader, "Base Map Loader", "is required for this script to work."));
IsReady = false;
}
if (PathFindingExample == null) {
Debug.LogError(ExampleErrors.MissingParameter(
this,
PathFindingExample,
"Path Finding Example",
"is required for this script to work."));
IsReady = false;
}
if (RoadLatticeNodesVisualizer == null) {
Debug.LogError(ExampleErrors.MissingParameter(
this,
RoadLatticeNodesVisualizer,
"Road Lattice Nodes Visualizer",
"is required for this script to work."));
IsReady = false;
}
if (ShowRoadLatticeToggle != null)
ShowRoadLatticeToggle.isOn = RoadLatticeNodesVisualizer.RoadLattice.activeSelf;
if (ShowAIPathsToggle != null)
ShowAIPathsToggle.isOn = PathFindingExample.IsDebugPathOn;
if (ActivateAIBotsToggle != null)
ActivateAIBotsToggle.isOn = PathFindingExample.IsAISearchActive;
}
void Update() {
if (IsReady) {
latValue.text = BaseMapLoader.LatLng.Lat.ToString("N5");
lngValue.text = BaseMapLoader.LatLng.Lng.ToString("N5");
}
}
public void OnShowRoadLattice(Toggle change) {
if (!IsReady)
return;
RoadLatticeNodesVisualizer.RoadLattice.SetActive(change.isOn);
}
public void OnShowAIRoutes(Toggle change) {
if (!IsReady)
return;
PathFindingExample.ShowAIPaths(change.isOn);
}
public void OnActivateAIBots(Toggle change) {
if (!IsReady)
return;
PathFindingExample.ActiveAllNPCs(change.isOn);
}
}
|
[
"public",
"class",
"PathFindingView",
":",
"MonoBehaviour",
"{",
"[",
"Tooltip",
"(",
"\"",
"The Base Map Loader handles the Maps Service initialization and basic event flow.",
"\"",
")",
"]",
"public",
"BaseMapLoader",
"BaseMapLoader",
";",
"[",
"Tooltip",
"(",
"\"",
"Current latitude of the floating origin.",
"\"",
")",
"]",
"public",
"Text",
"latValue",
";",
"[",
"Tooltip",
"(",
"\"",
"Current longitude of the floating origin.",
"\"",
")",
"]",
"public",
"Text",
"lngValue",
";",
"[",
"Tooltip",
"(",
"\"",
"Camera controller WSAD + Up/Down",
"\"",
")",
"]",
"public",
"CameraController",
"cameraController",
";",
"[",
"Tooltip",
"(",
"\"",
"The PathFinding example",
"\"",
")",
"]",
"public",
"PathFindingExample",
"PathFindingExample",
";",
"[",
"Tooltip",
"(",
"\"",
"Reference to the nodes debug visualizer",
"\"",
")",
"]",
"public",
"RoadLatticeNodesVisualizer",
"RoadLatticeNodesVisualizer",
";",
"[",
"Tooltip",
"(",
"\"",
"Controls the visibility of the road lattice",
"\"",
")",
"]",
"public",
"Toggle",
"ShowRoadLatticeToggle",
";",
"[",
"Tooltip",
"(",
"\"",
"Controls the display of all active paths between AI agents and their targets",
"\"",
")",
"]",
"public",
"Toggle",
"ShowAIPathsToggle",
";",
"[",
"Tooltip",
"(",
"\"",
"Activates the search behavior of AI Agents",
"\"",
")",
"]",
"public",
"Toggle",
"ActivateAIBotsToggle",
";",
"private",
"bool",
"IsReady",
";",
"void",
"Start",
"(",
")",
"{",
"IsReady",
"=",
"true",
";",
"if",
"(",
"BaseMapLoader",
"==",
"null",
")",
"{",
"Debug",
".",
"LogError",
"(",
"ExampleErrors",
".",
"MissingParameter",
"(",
"this",
",",
"BaseMapLoader",
",",
"\"",
"Base Map Loader",
"\"",
",",
"\"",
"is required for this script to work.",
"\"",
")",
")",
";",
"IsReady",
"=",
"false",
";",
"}",
"if",
"(",
"PathFindingExample",
"==",
"null",
")",
"{",
"Debug",
".",
"LogError",
"(",
"ExampleErrors",
".",
"MissingParameter",
"(",
"this",
",",
"PathFindingExample",
",",
"\"",
"Path Finding Example",
"\"",
",",
"\"",
"is required for this script to work.",
"\"",
")",
")",
";",
"IsReady",
"=",
"false",
";",
"}",
"if",
"(",
"RoadLatticeNodesVisualizer",
"==",
"null",
")",
"{",
"Debug",
".",
"LogError",
"(",
"ExampleErrors",
".",
"MissingParameter",
"(",
"this",
",",
"RoadLatticeNodesVisualizer",
",",
"\"",
"Road Lattice Nodes Visualizer",
"\"",
",",
"\"",
"is required for this script to work.",
"\"",
")",
")",
";",
"IsReady",
"=",
"false",
";",
"}",
"if",
"(",
"ShowRoadLatticeToggle",
"!=",
"null",
")",
"ShowRoadLatticeToggle",
".",
"isOn",
"=",
"RoadLatticeNodesVisualizer",
".",
"RoadLattice",
".",
"activeSelf",
";",
"if",
"(",
"ShowAIPathsToggle",
"!=",
"null",
")",
"ShowAIPathsToggle",
".",
"isOn",
"=",
"PathFindingExample",
".",
"IsDebugPathOn",
";",
"if",
"(",
"ActivateAIBotsToggle",
"!=",
"null",
")",
"ActivateAIBotsToggle",
".",
"isOn",
"=",
"PathFindingExample",
".",
"IsAISearchActive",
";",
"}",
"void",
"Update",
"(",
")",
"{",
"if",
"(",
"IsReady",
")",
"{",
"latValue",
".",
"text",
"=",
"BaseMapLoader",
".",
"LatLng",
".",
"Lat",
".",
"ToString",
"(",
"\"",
"N5",
"\"",
")",
";",
"lngValue",
".",
"text",
"=",
"BaseMapLoader",
".",
"LatLng",
".",
"Lng",
".",
"ToString",
"(",
"\"",
"N5",
"\"",
")",
";",
"}",
"}",
"public",
"void",
"OnShowRoadLattice",
"(",
"Toggle",
"change",
")",
"{",
"if",
"(",
"!",
"IsReady",
")",
"return",
";",
"RoadLatticeNodesVisualizer",
".",
"RoadLattice",
".",
"SetActive",
"(",
"change",
".",
"isOn",
")",
";",
"}",
"public",
"void",
"OnShowAIRoutes",
"(",
"Toggle",
"change",
")",
"{",
"if",
"(",
"!",
"IsReady",
")",
"return",
";",
"PathFindingExample",
".",
"ShowAIPaths",
"(",
"change",
".",
"isOn",
")",
";",
"}",
"public",
"void",
"OnActivateAIBots",
"(",
"Toggle",
"change",
")",
"{",
"if",
"(",
"!",
"IsReady",
")",
"return",
";",
"PathFindingExample",
".",
"ActiveAllNPCs",
"(",
"change",
".",
"isOn",
")",
";",
"}",
"}"
] |
Note: Road Lattice support is a beta feature subject to performance considerations and future
changes
|
[
"Note",
":",
"Road",
"Lattice",
"support",
"is",
"a",
"beta",
"feature",
"subject",
"to",
"performance",
"considerations",
"and",
"future",
"changes"
] |
[
"/// <summary>",
"/// IsReady is set to true if all required components for the pathfinding view are accounted",
"/// for and initialized",
"/// </summary>",
"// Start is called before the first frame update",
"/// <summary>",
"/// Updates the current lat lng",
"/// </summary>",
"// Update maps service values as they change.",
"/// <summary>",
"/// Activates or deactivates the visual indicators for the road lattice.",
"/// </summary>",
"/// <param name=\"change\">State of the toggle.</param>",
"/// <summary>",
"/// Notifies all AI Agents to start showing their active path to target",
"/// </summary>",
"/// <param name=\"v\"></param>",
"/// <summary>",
"/// Activates the search behaviour of all AI Agents",
"/// </summary>",
"/// <param name=\"v\"></param>"
] |
[
{
"param": "MonoBehaviour",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "MonoBehaviour",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 15
| 626
| 92
|
cdb4092db271f9529609a98c6743edce5e889e48
|
nv-krishna/jibernate
|
src/java/personal/wuyi/jibernate/entitymanager/AbstractEntityManagerDao.java
|
[
"Apache-2.0"
] |
Java
|
AbstractEntityManagerDao
|
/**
* The generic DAO (Data Access Object) for processing database operations.
*
* <p>Implements DAO functionality based on JPA EntityManager. Concrete
* EntityManager DAO implementations should be specific to a persistence unit.
*
* <p>This class is an abstract class so that it is generic and other
* database-specific DAO class (like MysqlDao or OracleDao) needs to inherit
* this class.
*
* @author Wuyi Chen
* @date 08/07/2018
* @version 1.1
* @since 1.0
*/
|
The generic DAO (Data Access Object) for processing database operations.
Implements DAO functionality based on JPA EntityManager. Concrete
EntityManager DAO implementations should be specific to a persistence unit.
This class is an abstract class so that it is generic and other
database-specific DAO class (like MysqlDao or OracleDao) needs to inherit
this class.
|
[
"The",
"generic",
"DAO",
"(",
"Data",
"Access",
"Object",
")",
"for",
"processing",
"database",
"operations",
".",
"Implements",
"DAO",
"functionality",
"based",
"on",
"JPA",
"EntityManager",
".",
"Concrete",
"EntityManager",
"DAO",
"implementations",
"should",
"be",
"specific",
"to",
"a",
"persistence",
"unit",
".",
"This",
"class",
"is",
"an",
"abstract",
"class",
"so",
"that",
"it",
"is",
"generic",
"and",
"other",
"database",
"-",
"specific",
"DAO",
"class",
"(",
"like",
"MysqlDao",
"or",
"OracleDao",
")",
"needs",
"to",
"inherit",
"this",
"class",
"."
] |
abstract class AbstractEntityManagerDao implements Dao {
private EntityManagerFactory entityManagerFactory;
private static Logger logger = LoggerFactory.getLogger(AbstractEntityManagerDao.class);
/**
* Get the Hibernate dialect string corresponding to DB technology (MySQL, Oracle, etc.)
*
* @return The string of dialect.
*
* @since 1.0
*/
protected abstract String getDialect();
/**
* Build the {@code DataSource} used by current {@code EntityManager}
* which is specific to DB technology (MySQL, Oracle, etc.),
* host/environment and credentials.
*
* @return The {@code DataSource}.
*
* @since 1.0
*/
protected abstract DataSource getDataSource();
/**
* Get the name of persistence unit.
*
* @return The name of persistence unit.
*
* @since 1.0
*/
protected abstract String getPersistenceUnit();
/* (non-Javadoc)
* @see personal.wuyi.jibernate.core.Dao#read(personal.wuyi.jibernate.core.Uri)
*/
@Override
@SuppressWarnings("unchecked")
public <T extends Persisted> T read(Uri uri) {
final Object id = uri.getId();
final EntityManager entityManager = getEntityManager();
if (id == null) {
throw new IllegalArgumentException("id can not be null when you query by primary key.");
}
try {
return (T) entityManager.find(uri.getType(), id);
} finally {
entityManager.close();
}
}
/* (non-Javadoc)
* @see personal.wuyi.jibernate.core.Dao#read(personal.wuyi.jibernate.query.Query)
*/
@Override
@SuppressWarnings("unchecked")
public <T extends Persisted> List<T> read(JQuery<T> query) {
final EntityManager entityManager = getEntityManager();
try {
final Query jpaQuery = QueryConverter.getJpaQuery(entityManager, query);
return jpaQuery.getResultList();
} finally {
entityManager.close();
}
}
/* (non-Javadoc)
* @see personal.wuyi.jibernate.core.Dao#read(personal.wuyi.jibernate.query.Query, java.lang.String[])
*/
@Override
public List<List<?>> read(JQuery<? extends Persisted> query, String... fieldNames) {
final EntityManager entityManager = getEntityManager();
try {
final Query jpaQuery = QueryConverter.getJpaQuery(entityManager, query, fieldNames);
List<?> results = jpaQuery.getResultList();
List<List<?>> list = new ArrayList<>();
if(fieldNames.length == 1) {
for(Object result : results) {
List<Object> sublist = new ArrayList<>();
sublist.add(result);
list.add(sublist);
}
} else {
for(Object result : results) {
list.add(Arrays.asList(((Object[]) result)));
}
}
return list;
} finally {
entityManager.close();
}
}
/* (non-Javadoc)
* @see personal.wuyi.jibernate.core.Dao#count(personal.wuyi.jibernate.query.Query)
*/
@Override
public <T extends Persisted> long count(JQuery<T> query) {
final EntityManager entityManager = getEntityManager();
try {
// make a copy since we are going to modify query
JQuery<T> queryCopy = ReflectUtil.copy(query);
final Query jpaQuery = QueryConverter.getJpaQuery(entityManager, queryCopy, "COUNT(*)");
return (Long) jpaQuery.getSingleResult();
} finally {
entityManager.close();
}
}
/* (non-Javadoc)
* @see personal.wuyi.jibernate.core.Dao#write(personal.wuyi.jibernate.core.Persisted)
*
* @see <a href="http://stackoverflow.com/questions/1069992/jpa-entitymanager-why-use-persist-over-merge">
* Why use persist() over merge()?
* </a>
*
* @see <a href="http://spitballer.blogspot.com/2010/04/jpa-persisting-vs-merging-entites.html">
* JPA: persisting vs. merging entites
* </a>
*/
public <T extends Persisted> void write(T t) throws DatabaseOperationException {
final EntityManager entityManager = getEntityManager();
try {
entityManager.getTransaction().begin();
// create new records, use persist()
// update existing records, use merge()
if(((ManagedEntity) t).getId() == null) {
entityManager.persist(t);
} else {
entityManager.merge(t);
}
entityManager.getTransaction().commit();
} catch(Exception e) {
entityManager.getTransaction().rollback();
logger.error("Error occurred when writing an object", e);
throw new DatabaseOperationException("Error occurred when writing an object", e);
} finally {
entityManager.close();
}
}
/* (non-Javadoc)
* @see personal.wuyi.jibernate.core.Dao#write(java.util.List)
*
* @see <a href="http://stackoverflow.com/questions/1069992/jpa-entitymanager-why-use-persist-over-merge">
* Why use persist() over merge()?
* </a>
*
* @see <a href="http://spitballer.blogspot.com/2010/04/jpa-persisting-vs-merging-entites.html">
* JPA: persisting vs. merging entites
* </a>
*/
public <T extends Persisted> void write(List<T> tList) throws DatabaseOperationException {
final EntityManager entityManager = getEntityManager();
try {
entityManager.getTransaction().begin();
for (T t : tList) {
// create new records, use persist()
// update existing records, use merge()
if (((ManagedEntity) t).getId() == null) {
entityManager.persist(t);
} else {
entityManager.merge(t);
}
}
entityManager.getTransaction().commit();
} catch(Exception e) {
entityManager.getTransaction().rollback();
logger.error("Error occurred when writing objects", e);
throw new DatabaseOperationException("Error occurred when writing objects", e);
} finally {
entityManager.close();
}
}
/* (non-Javadoc)
* @see personal.wuyi.jibernate.core.Dao#delete(personal.wuyi.jibernate.core.Persisted)
*
* @see <a href="https://stackoverflow.com/questions/17027398/java-lang-illegalargumentexception-removing-a-detached-instance-com-test-user5">
* java.lang.IllegalArgumentException: Removing a detached instance com.test.User#5
* </a>
*/
@Override
public <T extends Persisted> void delete(T t) throws DatabaseOperationException {
final EntityManager entityManager = getEntityManager();
try {
entityManager.getTransaction().begin();
// Can not delete an entity which is not managed by entityManager
// So check an entity is managed or not, if not, manage it first.
entityManager.remove(entityManager.contains(t) ? t : entityManager.merge(t));
entityManager.getTransaction().commit();
} catch(Exception e) {
entityManager.getTransaction().rollback();
logger.error("Error occurred when deleting an object", e);
throw new DatabaseOperationException("Error occurred when deleting an object", e);
} finally {
entityManager.close();
}
}
/* (non-Javadoc)
* @see personal.wuyi.jibernate.core.Dao#delete(personal.wuyi.jibernate.core.Persisted)
*
* @see <a href="https://stackoverflow.com/questions/17027398/java-lang-illegalargumentexception-removing-a-detached-instance-com-test-user5">
* java.lang.IllegalArgumentException: Removing a detached instance com.test.User#5
* </a>
*/
@Override
public <T extends Persisted> void delete(List<T> tList) throws DatabaseOperationException {
final EntityManager entityManager = getEntityManager();
try {
entityManager.getTransaction().begin();
for (T t : tList) {
// Can not delete an entity which is not managed by entityManager
// So check an entity is managed or not, if not, manage it first.
entityManager.remove(entityManager.contains(t) ? t : entityManager.merge(t));
}
entityManager.getTransaction().commit();
} catch(Exception e) {
entityManager.getTransaction().rollback();
logger.error("Error occurred when deleting objects", e);
throw new DatabaseOperationException("Error occurred when deleting objects", e);
} finally {
entityManager.close();
}
}
/**
* Get an {@code EntityManager}.
*
* @return An {@code EntityManager}.
*
* @since 1.0
*/
protected EntityManager getEntityManager() {
return getEntityManagerFactory().createEntityManager();
}
/**
* Get an {@code EntityManagerFactory}.
*
* <p>{@code EntityManagerFactory} will be initialized once and reuse
* after that.
*
* @return An {@code EntityManagerFactory}.
*
* @since 1.0
*/
protected EntityManagerFactory getEntityManagerFactory() {
if (entityManagerFactory == null) {
Map<String, Object> properties = getProperties();
PersistenceUnitInfo persistenceUnitInfo = getPersistUnitInfo();
entityManagerFactory = new HibernatePersistenceProvider().createContainerEntityManagerFactory(persistenceUnitInfo, properties);
}
return entityManagerFactory;
}
/**
* Get the properties based on different types of {@code EntityManager}.
*
* @return The {@code HashMap} contains all the properties.
*
* @since 1.0
*/
private Map<String,Object> getProperties() {
Map<String,Object> properties = new HashMap<>();
properties.put(AvailableSettings.DIALECT, getDialect());
properties.put(AvailableSettings.DATASOURCE, getDataSource());
return properties;
}
/**
* Get the info of the persistence unit based on the {@code EntityManager}.
*
* @return The {@code PersistenceUnitInfo}.
*
* @since 1.0
*/
private PersistenceUnitInfo getPersistUnitInfo() {
return new CommonPersistenceUnitInfo(getPersistenceUnit());
}
/* (non-Javadoc)
* Open a {@code EntityManagerFactory}.
*
* @see personal.wuyi.jibernate.core.Plugin#start()
*/
@Override
public void start() {
getEntityManagerFactory();
}
/* (non-Javadoc)
* Close the {@code EntityManagerFactory}.
*
* @see personal.wuyi.jibernate.core.Plugin#stop()
*/
@Override
public void stop() {
getEntityManagerFactory().close();
entityManagerFactory = null;
}
}
|
[
"abstract",
"class",
"AbstractEntityManagerDao",
"implements",
"Dao",
"{",
"private",
"EntityManagerFactory",
"entityManagerFactory",
";",
"private",
"static",
"Logger",
"logger",
"=",
"LoggerFactory",
".",
"getLogger",
"(",
"AbstractEntityManagerDao",
".",
"class",
")",
";",
"/**\n\t * Get the Hibernate dialect string corresponding to DB technology (MySQL, Oracle, etc.)\n\t * \n\t * @return The string of dialect.\n\t * \n * @since 1.0\n\t */",
"protected",
"abstract",
"String",
"getDialect",
"(",
")",
";",
"/**\n * Build the {@code DataSource} used by current {@code EntityManager} \n * which is specific to DB technology (MySQL, Oracle, etc.),\n * host/environment and credentials.\n *\n * @return The {@code DataSource}.\n * \n * @since 1.0\n */",
"protected",
"abstract",
"DataSource",
"getDataSource",
"(",
")",
";",
"/**\n\t * Get the name of persistence unit.\n\t * \n\t * @return The name of persistence unit.\n\t * \n * @since 1.0\n\t */",
"protected",
"abstract",
"String",
"getPersistenceUnit",
"(",
")",
";",
"/* (non-Javadoc)\n\t * @see personal.wuyi.jibernate.core.Dao#read(personal.wuyi.jibernate.core.Uri)\n\t */",
"@",
"Override",
"@",
"SuppressWarnings",
"(",
"\"",
"unchecked",
"\"",
")",
"public",
"<",
"T",
"extends",
"Persisted",
">",
"T",
"read",
"(",
"Uri",
"uri",
")",
"{",
"final",
"Object",
"id",
"=",
"uri",
".",
"getId",
"(",
")",
";",
"final",
"EntityManager",
"entityManager",
"=",
"getEntityManager",
"(",
")",
";",
"if",
"(",
"id",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"",
"id can not be null when you query by primary key.",
"\"",
")",
";",
"}",
"try",
"{",
"return",
"(",
"T",
")",
"entityManager",
".",
"find",
"(",
"uri",
".",
"getType",
"(",
")",
",",
"id",
")",
";",
"}",
"finally",
"{",
"entityManager",
".",
"close",
"(",
")",
";",
"}",
"}",
"/* (non-Javadoc)\n\t * @see personal.wuyi.jibernate.core.Dao#read(personal.wuyi.jibernate.query.Query)\n\t */",
"@",
"Override",
"@",
"SuppressWarnings",
"(",
"\"",
"unchecked",
"\"",
")",
"public",
"<",
"T",
"extends",
"Persisted",
">",
"List",
"<",
"T",
">",
"read",
"(",
"JQuery",
"<",
"T",
">",
"query",
")",
"{",
"final",
"EntityManager",
"entityManager",
"=",
"getEntityManager",
"(",
")",
";",
"try",
"{",
"final",
"Query",
"jpaQuery",
"=",
"QueryConverter",
".",
"getJpaQuery",
"(",
"entityManager",
",",
"query",
")",
";",
"return",
"jpaQuery",
".",
"getResultList",
"(",
")",
";",
"}",
"finally",
"{",
"entityManager",
".",
"close",
"(",
")",
";",
"}",
"}",
"/* (non-Javadoc)\n * @see personal.wuyi.jibernate.core.Dao#read(personal.wuyi.jibernate.query.Query, java.lang.String[])\n */",
"@",
"Override",
"public",
"List",
"<",
"List",
"<",
"?",
">",
">",
"read",
"(",
"JQuery",
"<",
"?",
"extends",
"Persisted",
">",
"query",
",",
"String",
"...",
"fieldNames",
")",
"{",
"final",
"EntityManager",
"entityManager",
"=",
"getEntityManager",
"(",
")",
";",
"try",
"{",
"final",
"Query",
"jpaQuery",
"=",
"QueryConverter",
".",
"getJpaQuery",
"(",
"entityManager",
",",
"query",
",",
"fieldNames",
")",
";",
"List",
"<",
"?",
">",
"results",
"=",
"jpaQuery",
".",
"getResultList",
"(",
")",
";",
"List",
"<",
"List",
"<",
"?",
">",
">",
"list",
"=",
"new",
"ArrayList",
"<",
">",
"(",
")",
";",
"if",
"(",
"fieldNames",
".",
"length",
"==",
"1",
")",
"{",
"for",
"(",
"Object",
"result",
":",
"results",
")",
"{",
"List",
"<",
"Object",
">",
"sublist",
"=",
"new",
"ArrayList",
"<",
">",
"(",
")",
";",
"sublist",
".",
"add",
"(",
"result",
")",
";",
"list",
".",
"add",
"(",
"sublist",
")",
";",
"}",
"}",
"else",
"{",
"for",
"(",
"Object",
"result",
":",
"results",
")",
"{",
"list",
".",
"add",
"(",
"Arrays",
".",
"asList",
"(",
"(",
"(",
"Object",
"[",
"]",
")",
"result",
")",
")",
")",
";",
"}",
"}",
"return",
"list",
";",
"}",
"finally",
"{",
"entityManager",
".",
"close",
"(",
")",
";",
"}",
"}",
"/* (non-Javadoc)\n * @see personal.wuyi.jibernate.core.Dao#count(personal.wuyi.jibernate.query.Query)\n */",
"@",
"Override",
"public",
"<",
"T",
"extends",
"Persisted",
">",
"long",
"count",
"(",
"JQuery",
"<",
"T",
">",
"query",
")",
"{",
"final",
"EntityManager",
"entityManager",
"=",
"getEntityManager",
"(",
")",
";",
"try",
"{",
"JQuery",
"<",
"T",
">",
"queryCopy",
"=",
"ReflectUtil",
".",
"copy",
"(",
"query",
")",
";",
"final",
"Query",
"jpaQuery",
"=",
"QueryConverter",
".",
"getJpaQuery",
"(",
"entityManager",
",",
"queryCopy",
",",
"\"",
"COUNT(*)",
"\"",
")",
";",
"return",
"(",
"Long",
")",
"jpaQuery",
".",
"getSingleResult",
"(",
")",
";",
"}",
"finally",
"{",
"entityManager",
".",
"close",
"(",
")",
";",
"}",
"}",
"/* (non-Javadoc)\n * @see personal.wuyi.jibernate.core.Dao#write(personal.wuyi.jibernate.core.Persisted)\n * \n * @see <a href=\"http://stackoverflow.com/questions/1069992/jpa-entitymanager-why-use-persist-over-merge\">\n * Why use persist() over merge()?\n * </a>\n * \n * @see <a href=\"http://spitballer.blogspot.com/2010/04/jpa-persisting-vs-merging-entites.html\">\n * JPA: persisting vs. merging entites\n * </a>\n */",
"public",
"<",
"T",
"extends",
"Persisted",
">",
"void",
"write",
"(",
"T",
"t",
")",
"throws",
"DatabaseOperationException",
"{",
"final",
"EntityManager",
"entityManager",
"=",
"getEntityManager",
"(",
")",
";",
"try",
"{",
"entityManager",
".",
"getTransaction",
"(",
")",
".",
"begin",
"(",
")",
";",
"if",
"(",
"(",
"(",
"ManagedEntity",
")",
"t",
")",
".",
"getId",
"(",
")",
"==",
"null",
")",
"{",
"entityManager",
".",
"persist",
"(",
"t",
")",
";",
"}",
"else",
"{",
"entityManager",
".",
"merge",
"(",
"t",
")",
";",
"}",
"entityManager",
".",
"getTransaction",
"(",
")",
".",
"commit",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"entityManager",
".",
"getTransaction",
"(",
")",
".",
"rollback",
"(",
")",
";",
"logger",
".",
"error",
"(",
"\"",
"Error occurred when writing an object",
"\"",
",",
"e",
")",
";",
"throw",
"new",
"DatabaseOperationException",
"(",
"\"",
"Error occurred when writing an object",
"\"",
",",
"e",
")",
";",
"}",
"finally",
"{",
"entityManager",
".",
"close",
"(",
")",
";",
"}",
"}",
"/* (non-Javadoc)\n * @see personal.wuyi.jibernate.core.Dao#write(java.util.List)\n * \n * @see <a href=\"http://stackoverflow.com/questions/1069992/jpa-entitymanager-why-use-persist-over-merge\">\n * Why use persist() over merge()?\n * </a>\n * \n * @see <a href=\"http://spitballer.blogspot.com/2010/04/jpa-persisting-vs-merging-entites.html\">\n * JPA: persisting vs. merging entites\n * </a>\n */",
"public",
"<",
"T",
"extends",
"Persisted",
">",
"void",
"write",
"(",
"List",
"<",
"T",
">",
"tList",
")",
"throws",
"DatabaseOperationException",
"{",
"final",
"EntityManager",
"entityManager",
"=",
"getEntityManager",
"(",
")",
";",
"try",
"{",
"entityManager",
".",
"getTransaction",
"(",
")",
".",
"begin",
"(",
")",
";",
"for",
"(",
"T",
"t",
":",
"tList",
")",
"{",
"if",
"(",
"(",
"(",
"ManagedEntity",
")",
"t",
")",
".",
"getId",
"(",
")",
"==",
"null",
")",
"{",
"entityManager",
".",
"persist",
"(",
"t",
")",
";",
"}",
"else",
"{",
"entityManager",
".",
"merge",
"(",
"t",
")",
";",
"}",
"}",
"entityManager",
".",
"getTransaction",
"(",
")",
".",
"commit",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"entityManager",
".",
"getTransaction",
"(",
")",
".",
"rollback",
"(",
")",
";",
"logger",
".",
"error",
"(",
"\"",
"Error occurred when writing objects",
"\"",
",",
"e",
")",
";",
"throw",
"new",
"DatabaseOperationException",
"(",
"\"",
"Error occurred when writing objects",
"\"",
",",
"e",
")",
";",
"}",
"finally",
"{",
"entityManager",
".",
"close",
"(",
")",
";",
"}",
"}",
"/* (non-Javadoc)\n * @see personal.wuyi.jibernate.core.Dao#delete(personal.wuyi.jibernate.core.Persisted)\n * \n * @see <a href=\"https://stackoverflow.com/questions/17027398/java-lang-illegalargumentexception-removing-a-detached-instance-com-test-user5\">\n * java.lang.IllegalArgumentException: Removing a detached instance com.test.User#5\n * </a>\n */",
"@",
"Override",
"public",
"<",
"T",
"extends",
"Persisted",
">",
"void",
"delete",
"(",
"T",
"t",
")",
"throws",
"DatabaseOperationException",
"{",
"final",
"EntityManager",
"entityManager",
"=",
"getEntityManager",
"(",
")",
";",
"try",
"{",
"entityManager",
".",
"getTransaction",
"(",
")",
".",
"begin",
"(",
")",
";",
"entityManager",
".",
"remove",
"(",
"entityManager",
".",
"contains",
"(",
"t",
")",
"?",
"t",
":",
"entityManager",
".",
"merge",
"(",
"t",
")",
")",
";",
"entityManager",
".",
"getTransaction",
"(",
")",
".",
"commit",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"entityManager",
".",
"getTransaction",
"(",
")",
".",
"rollback",
"(",
")",
";",
"logger",
".",
"error",
"(",
"\"",
"Error occurred when deleting an object",
"\"",
",",
"e",
")",
";",
"throw",
"new",
"DatabaseOperationException",
"(",
"\"",
"Error occurred when deleting an object",
"\"",
",",
"e",
")",
";",
"}",
"finally",
"{",
"entityManager",
".",
"close",
"(",
")",
";",
"}",
"}",
"/* (non-Javadoc)\n * @see personal.wuyi.jibernate.core.Dao#delete(personal.wuyi.jibernate.core.Persisted)\n * \n * @see <a href=\"https://stackoverflow.com/questions/17027398/java-lang-illegalargumentexception-removing-a-detached-instance-com-test-user5\">\n * java.lang.IllegalArgumentException: Removing a detached instance com.test.User#5\n * </a>\n */",
"@",
"Override",
"public",
"<",
"T",
"extends",
"Persisted",
">",
"void",
"delete",
"(",
"List",
"<",
"T",
">",
"tList",
")",
"throws",
"DatabaseOperationException",
"{",
"final",
"EntityManager",
"entityManager",
"=",
"getEntityManager",
"(",
")",
";",
"try",
"{",
"entityManager",
".",
"getTransaction",
"(",
")",
".",
"begin",
"(",
")",
";",
"for",
"(",
"T",
"t",
":",
"tList",
")",
"{",
"entityManager",
".",
"remove",
"(",
"entityManager",
".",
"contains",
"(",
"t",
")",
"?",
"t",
":",
"entityManager",
".",
"merge",
"(",
"t",
")",
")",
";",
"}",
"entityManager",
".",
"getTransaction",
"(",
")",
".",
"commit",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"entityManager",
".",
"getTransaction",
"(",
")",
".",
"rollback",
"(",
")",
";",
"logger",
".",
"error",
"(",
"\"",
"Error occurred when deleting objects",
"\"",
",",
"e",
")",
";",
"throw",
"new",
"DatabaseOperationException",
"(",
"\"",
"Error occurred when deleting objects",
"\"",
",",
"e",
")",
";",
"}",
"finally",
"{",
"entityManager",
".",
"close",
"(",
")",
";",
"}",
"}",
"/**\n\t * Get an {@code EntityManager}.\n\t * \n\t * @return An {@code EntityManager}.\n\t * \n * @since 1.0\n\t */",
"protected",
"EntityManager",
"getEntityManager",
"(",
")",
"{",
"return",
"getEntityManagerFactory",
"(",
")",
".",
"createEntityManager",
"(",
")",
";",
"}",
"/**\n\t * Get an {@code EntityManagerFactory}.\n\t * \n\t * <p>{@code EntityManagerFactory} will be initialized once and reuse \n\t * after that.\n\t * \n\t * @return An {@code EntityManagerFactory}.\n\t * \n * @since 1.0\n\t */",
"protected",
"EntityManagerFactory",
"getEntityManagerFactory",
"(",
")",
"{",
"if",
"(",
"entityManagerFactory",
"==",
"null",
")",
"{",
"Map",
"<",
"String",
",",
"Object",
">",
"properties",
"=",
"getProperties",
"(",
")",
";",
"PersistenceUnitInfo",
"persistenceUnitInfo",
"=",
"getPersistUnitInfo",
"(",
")",
";",
"entityManagerFactory",
"=",
"new",
"HibernatePersistenceProvider",
"(",
")",
".",
"createContainerEntityManagerFactory",
"(",
"persistenceUnitInfo",
",",
"properties",
")",
";",
"}",
"return",
"entityManagerFactory",
";",
"}",
"/**\n\t * Get the properties based on different types of {@code EntityManager}.\n\t * \n\t * @return The {@code HashMap} contains all the properties.\n\t * \n * @since 1.0\n\t */",
"private",
"Map",
"<",
"String",
",",
"Object",
">",
"getProperties",
"(",
")",
"{",
"Map",
"<",
"String",
",",
"Object",
">",
"properties",
"=",
"new",
"HashMap",
"<",
">",
"(",
")",
";",
"properties",
".",
"put",
"(",
"AvailableSettings",
".",
"DIALECT",
",",
"getDialect",
"(",
")",
")",
";",
"properties",
".",
"put",
"(",
"AvailableSettings",
".",
"DATASOURCE",
",",
"getDataSource",
"(",
")",
")",
";",
"return",
"properties",
";",
"}",
"/**\n\t * Get the info of the persistence unit based on the {@code EntityManager}.\n\t * \n\t * @return The {@code PersistenceUnitInfo}.\n\t * \n\t * @since 1.0\n\t */",
"private",
"PersistenceUnitInfo",
"getPersistUnitInfo",
"(",
")",
"{",
"return",
"new",
"CommonPersistenceUnitInfo",
"(",
"getPersistenceUnit",
"(",
")",
")",
";",
"}",
"/* (non-Javadoc)\n * Open a {@code EntityManagerFactory}.\n * \n * @see personal.wuyi.jibernate.core.Plugin#start()\n */",
"@",
"Override",
"public",
"void",
"start",
"(",
")",
"{",
"getEntityManagerFactory",
"(",
")",
";",
"}",
"/* (non-Javadoc)\n * Close the {@code EntityManagerFactory}.\n * \n * @see personal.wuyi.jibernate.core.Plugin#stop()\n */",
"@",
"Override",
"public",
"void",
"stop",
"(",
")",
"{",
"getEntityManagerFactory",
"(",
")",
".",
"close",
"(",
")",
";",
"entityManagerFactory",
"=",
"null",
";",
"}",
"}"
] |
The generic DAO (Data Access Object) for processing database operations.
|
[
"The",
"generic",
"DAO",
"(",
"Data",
"Access",
"Object",
")",
"for",
"processing",
"database",
"operations",
"."
] |
[
"// make a copy since we are going to modify query",
"// create new records, use persist()",
"// update existing records, use merge()",
"// create new records, use persist()",
"// update existing records, use merge() ",
"// Can not delete an entity which is not managed by entityManager",
"// So check an entity is managed or not, if not, manage it first.",
"// Can not delete an entity which is not managed by entityManager",
"// So check an entity is managed or not, if not, manage it first."
] |
[
{
"param": "Dao",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "Dao",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 20
| 2,365
| 131
|
a5824aa3ff08b3d4e5772beb95760f33191d6e4c
|
hyundai-autoever-opensource/mdfstudio-hkmc
|
mdfstudio/blocks/v2_v3_blocks.py
|
[
"OML"
] |
Python
|
ChannelGroup
|
CGBLOCK class
CGBLOCK fields
* ``id`` - bytes : block ID; always b'CG'
* ``block_len`` - int : block bytes size
* ``next_cg_addr`` - int : next CGBLOCK address
* ``first_ch_addr`` - int : address of first channel block (CNBLOCK)
* ``comment_addr`` - int : address of TXBLOCK that contains the channel
group comment
* ``record_id`` - int : record ID used as identifier for a record if
the DGBLOCK defines a number of record IDs > 0 (unsorted group)
* ``ch_nr`` - int : number of channels
* ``samples_byte_nr`` - int : size of data record in bytes without
record ID
* ``cycles_nr`` - int : number of cycles (records) of this type in the data
block
* ``sample_reduction_addr`` - int : addresss to first sample reduction
block
Other attributes
* ``address`` - int : block address inside mdf file
* ``comment`` - str : channel group comment
Parameters
----------
stream : file handle
mdf file handle
address : int
block address inside mdf file
for dynamically created objects :
see the key-value pairs
Examples
--------
>>> with open('test.mdf', 'rb') as mdf:
... cg1 = ChannelGroup(stream=mdf, address=0xBA52)
>>> cg2 = ChannelGroup(sample_bytes_nr=32)
>>> hex(cg1.address)
0xBA52
>>> cg1['id']
b'CG'
|
CGBLOCK class
CGBLOCK fields
Other attributes
Parameters
stream : file handle
mdf file handle
address : int
block address inside mdf file
for dynamically created objects :
see the key-value pairs
Examples
|
[
"CGBLOCK",
"class",
"CGBLOCK",
"fields",
"Other",
"attributes",
"Parameters",
"stream",
":",
"file",
"handle",
"mdf",
"file",
"handle",
"address",
":",
"int",
"block",
"address",
"inside",
"mdf",
"file",
"for",
"dynamically",
"created",
"objects",
":",
"see",
"the",
"key",
"-",
"value",
"pairs",
"Examples"
] |
class ChannelGroup:
""" CGBLOCK class
CGBLOCK fields
* ``id`` - bytes : block ID; always b'CG'
* ``block_len`` - int : block bytes size
* ``next_cg_addr`` - int : next CGBLOCK address
* ``first_ch_addr`` - int : address of first channel block (CNBLOCK)
* ``comment_addr`` - int : address of TXBLOCK that contains the channel
group comment
* ``record_id`` - int : record ID used as identifier for a record if
the DGBLOCK defines a number of record IDs > 0 (unsorted group)
* ``ch_nr`` - int : number of channels
* ``samples_byte_nr`` - int : size of data record in bytes without
record ID
* ``cycles_nr`` - int : number of cycles (records) of this type in the data
block
* ``sample_reduction_addr`` - int : addresss to first sample reduction
block
Other attributes
* ``address`` - int : block address inside mdf file
* ``comment`` - str : channel group comment
Parameters
----------
stream : file handle
mdf file handle
address : int
block address inside mdf file
for dynamically created objects :
see the key-value pairs
Examples
--------
>>> with open('test.mdf', 'rb') as mdf:
... cg1 = ChannelGroup(stream=mdf, address=0xBA52)
>>> cg2 = ChannelGroup(sample_bytes_nr=32)
>>> hex(cg1.address)
0xBA52
>>> cg1['id']
b'CG'
"""
__slots__ = (
"address",
"comment",
"id",
"block_len",
"next_cg_addr",
"first_ch_addr",
"comment_addr",
"record_id",
"ch_nr",
"samples_byte_nr",
"cycles_nr",
"sample_reduction_addr",
)
def __init__(self, **kwargs):
super().__init__()
self.comment = ""
try:
stream = kwargs["stream"]
mapped = kwargs.get("mapped", False)
self.address = address = kwargs["address"]
if mapped:
(
self.id,
self.block_len,
self.next_cg_addr,
self.first_ch_addr,
self.comment_addr,
self.record_id,
self.ch_nr,
self.samples_byte_nr,
self.cycles_nr,
) = v23c.CHANNEL_GROUP_uf(stream, address)
if self.block_len == v23c.CG_POST_330_BLOCK_SIZE:
# sample reduction blocks are not yet used
self.sample_reduction_addr = 0
else:
stream.seek(address)
block = stream.read(v23c.CG_PRE_330_BLOCK_SIZE)
(
self.id,
self.block_len,
self.next_cg_addr,
self.first_ch_addr,
self.comment_addr,
self.record_id,
self.ch_nr,
self.samples_byte_nr,
self.cycles_nr,
) = unpack(v23c.FMT_CHANNEL_GROUP, block)
if self.block_len == v23c.CG_POST_330_BLOCK_SIZE:
# sample reduction blocks are not yet used
self.sample_reduction_addr = 0
if self.id != b"CG":
message = f'Expected "CG" block @{hex(address)} but found "{self.id}"'
raise MdfException(message.format(self.id))
if self.comment_addr:
self.comment = get_text_v3(
address=self.comment_addr, stream=stream, mapped=mapped
)
except KeyError:
self.address = 0
self.id = b"CG"
self.block_len = kwargs.get("block_len", v23c.CG_PRE_330_BLOCK_SIZE)
self.next_cg_addr = kwargs.get("next_cg_addr", 0)
self.first_ch_addr = kwargs.get("first_ch_addr", 0)
self.comment_addr = kwargs.get("comment_addr", 0)
self.record_id = kwargs.get("record_id", 1)
self.ch_nr = kwargs.get("ch_nr", 0)
self.samples_byte_nr = kwargs.get("samples_byte_nr", 0)
self.cycles_nr = kwargs.get("cycles_nr", 0)
if self.block_len == v23c.CG_POST_330_BLOCK_SIZE:
self.sample_reduction_addr = 0
def to_blocks(self, address, blocks, defined_texts, si_map):
key = "comment_addr"
text = self.comment
if text:
if text in defined_texts:
self[key] = defined_texts[text]
else:
tx_block = TextBlock(text=text)
self[key] = address
defined_texts[text] = address
tx_block.address = address
address += tx_block.block_len
blocks.append(tx_block)
else:
self[key] = 0
blocks.append(self)
self.address = address
address += self.block_len
return address
def __getitem__(self, item):
return self.__getattribute__(item)
def __setitem__(self, item, value):
self.__setattr__(item, value)
def __bytes__(self):
if self.block_len == v23c.CG_POST_330_BLOCK_SIZE:
return (
v23c.CHANNEL_GROUP_p(
self.id,
self.block_len,
self.next_cg_addr,
self.first_ch_addr,
self.comment_addr,
self.record_id,
self.ch_nr,
self.samples_byte_nr,
self.cycles_nr,
)
+ b"\0" * 4
)
else:
return v23c.CHANNEL_GROUP_p(
self.id,
self.block_len,
self.next_cg_addr,
self.first_ch_addr,
self.comment_addr,
self.record_id,
self.ch_nr,
self.samples_byte_nr,
self.cycles_nr,
)
def metadata(self):
keys = (
"id",
"block_len",
"next_cg_addr",
"first_ch_addr",
"comment_addr",
"record_id",
"ch_nr",
"samples_byte_nr",
"cycles_nr",
"sample_reduction_addr",
)
max_len = max(len(key) for key in keys)
template = f"{{: <{max_len}}}: {{}}"
metadata = []
lines = f"""
address: {hex(self.address)}
comment: {self.comment}
""".split(
"\n"
)
for key in keys:
if not hasattr(self, key):
continue
val = getattr(self, key)
if key.endswith("addr") or key.startswith("text_"):
lines.append(template.format(key, hex(val)))
elif isinstance(val, float):
lines.append(template.format(key, round(val, 6)))
else:
if isinstance(val, bytes):
try:
lines.append(template.format(key, val.decode()))
except:
lines.append(template.format(key, val.decode('latin-1').strip("\0")))
else:
lines.append(template.format(key, val))
for line in lines:
if not line:
metadata.append(line)
else:
for wrapped_line in wrap(line, width=120):
metadata.append(wrapped_line)
return "\n".join(metadata)
|
[
"class",
"ChannelGroup",
":",
"__slots__",
"=",
"(",
"\"address\"",
",",
"\"comment\"",
",",
"\"id\"",
",",
"\"block_len\"",
",",
"\"next_cg_addr\"",
",",
"\"first_ch_addr\"",
",",
"\"comment_addr\"",
",",
"\"record_id\"",
",",
"\"ch_nr\"",
",",
"\"samples_byte_nr\"",
",",
"\"cycles_nr\"",
",",
"\"sample_reduction_addr\"",
",",
")",
"def",
"__init__",
"(",
"self",
",",
"**",
"kwargs",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
")",
"self",
".",
"comment",
"=",
"\"\"",
"try",
":",
"stream",
"=",
"kwargs",
"[",
"\"stream\"",
"]",
"mapped",
"=",
"kwargs",
".",
"get",
"(",
"\"mapped\"",
",",
"False",
")",
"self",
".",
"address",
"=",
"address",
"=",
"kwargs",
"[",
"\"address\"",
"]",
"if",
"mapped",
":",
"(",
"self",
".",
"id",
",",
"self",
".",
"block_len",
",",
"self",
".",
"next_cg_addr",
",",
"self",
".",
"first_ch_addr",
",",
"self",
".",
"comment_addr",
",",
"self",
".",
"record_id",
",",
"self",
".",
"ch_nr",
",",
"self",
".",
"samples_byte_nr",
",",
"self",
".",
"cycles_nr",
",",
")",
"=",
"v23c",
".",
"CHANNEL_GROUP_uf",
"(",
"stream",
",",
"address",
")",
"if",
"self",
".",
"block_len",
"==",
"v23c",
".",
"CG_POST_330_BLOCK_SIZE",
":",
"self",
".",
"sample_reduction_addr",
"=",
"0",
"else",
":",
"stream",
".",
"seek",
"(",
"address",
")",
"block",
"=",
"stream",
".",
"read",
"(",
"v23c",
".",
"CG_PRE_330_BLOCK_SIZE",
")",
"(",
"self",
".",
"id",
",",
"self",
".",
"block_len",
",",
"self",
".",
"next_cg_addr",
",",
"self",
".",
"first_ch_addr",
",",
"self",
".",
"comment_addr",
",",
"self",
".",
"record_id",
",",
"self",
".",
"ch_nr",
",",
"self",
".",
"samples_byte_nr",
",",
"self",
".",
"cycles_nr",
",",
")",
"=",
"unpack",
"(",
"v23c",
".",
"FMT_CHANNEL_GROUP",
",",
"block",
")",
"if",
"self",
".",
"block_len",
"==",
"v23c",
".",
"CG_POST_330_BLOCK_SIZE",
":",
"self",
".",
"sample_reduction_addr",
"=",
"0",
"if",
"self",
".",
"id",
"!=",
"b\"CG\"",
":",
"message",
"=",
"f'Expected \"CG\" block @{hex(address)} but found \"{self.id}\"'",
"raise",
"MdfException",
"(",
"message",
".",
"format",
"(",
"self",
".",
"id",
")",
")",
"if",
"self",
".",
"comment_addr",
":",
"self",
".",
"comment",
"=",
"get_text_v3",
"(",
"address",
"=",
"self",
".",
"comment_addr",
",",
"stream",
"=",
"stream",
",",
"mapped",
"=",
"mapped",
")",
"except",
"KeyError",
":",
"self",
".",
"address",
"=",
"0",
"self",
".",
"id",
"=",
"b\"CG\"",
"self",
".",
"block_len",
"=",
"kwargs",
".",
"get",
"(",
"\"block_len\"",
",",
"v23c",
".",
"CG_PRE_330_BLOCK_SIZE",
")",
"self",
".",
"next_cg_addr",
"=",
"kwargs",
".",
"get",
"(",
"\"next_cg_addr\"",
",",
"0",
")",
"self",
".",
"first_ch_addr",
"=",
"kwargs",
".",
"get",
"(",
"\"first_ch_addr\"",
",",
"0",
")",
"self",
".",
"comment_addr",
"=",
"kwargs",
".",
"get",
"(",
"\"comment_addr\"",
",",
"0",
")",
"self",
".",
"record_id",
"=",
"kwargs",
".",
"get",
"(",
"\"record_id\"",
",",
"1",
")",
"self",
".",
"ch_nr",
"=",
"kwargs",
".",
"get",
"(",
"\"ch_nr\"",
",",
"0",
")",
"self",
".",
"samples_byte_nr",
"=",
"kwargs",
".",
"get",
"(",
"\"samples_byte_nr\"",
",",
"0",
")",
"self",
".",
"cycles_nr",
"=",
"kwargs",
".",
"get",
"(",
"\"cycles_nr\"",
",",
"0",
")",
"if",
"self",
".",
"block_len",
"==",
"v23c",
".",
"CG_POST_330_BLOCK_SIZE",
":",
"self",
".",
"sample_reduction_addr",
"=",
"0",
"def",
"to_blocks",
"(",
"self",
",",
"address",
",",
"blocks",
",",
"defined_texts",
",",
"si_map",
")",
":",
"key",
"=",
"\"comment_addr\"",
"text",
"=",
"self",
".",
"comment",
"if",
"text",
":",
"if",
"text",
"in",
"defined_texts",
":",
"self",
"[",
"key",
"]",
"=",
"defined_texts",
"[",
"text",
"]",
"else",
":",
"tx_block",
"=",
"TextBlock",
"(",
"text",
"=",
"text",
")",
"self",
"[",
"key",
"]",
"=",
"address",
"defined_texts",
"[",
"text",
"]",
"=",
"address",
"tx_block",
".",
"address",
"=",
"address",
"address",
"+=",
"tx_block",
".",
"block_len",
"blocks",
".",
"append",
"(",
"tx_block",
")",
"else",
":",
"self",
"[",
"key",
"]",
"=",
"0",
"blocks",
".",
"append",
"(",
"self",
")",
"self",
".",
"address",
"=",
"address",
"address",
"+=",
"self",
".",
"block_len",
"return",
"address",
"def",
"__getitem__",
"(",
"self",
",",
"item",
")",
":",
"return",
"self",
".",
"__getattribute__",
"(",
"item",
")",
"def",
"__setitem__",
"(",
"self",
",",
"item",
",",
"value",
")",
":",
"self",
".",
"__setattr__",
"(",
"item",
",",
"value",
")",
"def",
"__bytes__",
"(",
"self",
")",
":",
"if",
"self",
".",
"block_len",
"==",
"v23c",
".",
"CG_POST_330_BLOCK_SIZE",
":",
"return",
"(",
"v23c",
".",
"CHANNEL_GROUP_p",
"(",
"self",
".",
"id",
",",
"self",
".",
"block_len",
",",
"self",
".",
"next_cg_addr",
",",
"self",
".",
"first_ch_addr",
",",
"self",
".",
"comment_addr",
",",
"self",
".",
"record_id",
",",
"self",
".",
"ch_nr",
",",
"self",
".",
"samples_byte_nr",
",",
"self",
".",
"cycles_nr",
",",
")",
"+",
"b\"\\0\"",
"*",
"4",
")",
"else",
":",
"return",
"v23c",
".",
"CHANNEL_GROUP_p",
"(",
"self",
".",
"id",
",",
"self",
".",
"block_len",
",",
"self",
".",
"next_cg_addr",
",",
"self",
".",
"first_ch_addr",
",",
"self",
".",
"comment_addr",
",",
"self",
".",
"record_id",
",",
"self",
".",
"ch_nr",
",",
"self",
".",
"samples_byte_nr",
",",
"self",
".",
"cycles_nr",
",",
")",
"def",
"metadata",
"(",
"self",
")",
":",
"keys",
"=",
"(",
"\"id\"",
",",
"\"block_len\"",
",",
"\"next_cg_addr\"",
",",
"\"first_ch_addr\"",
",",
"\"comment_addr\"",
",",
"\"record_id\"",
",",
"\"ch_nr\"",
",",
"\"samples_byte_nr\"",
",",
"\"cycles_nr\"",
",",
"\"sample_reduction_addr\"",
",",
")",
"max_len",
"=",
"max",
"(",
"len",
"(",
"key",
")",
"for",
"key",
"in",
"keys",
")",
"template",
"=",
"f\"{{: <{max_len}}}: {{}}\"",
"metadata",
"=",
"[",
"]",
"lines",
"=",
"f\"\"\"\naddress: {hex(self.address)}\ncomment: {self.comment}\n\n\"\"\"",
".",
"split",
"(",
"\"\\n\"",
")",
"for",
"key",
"in",
"keys",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"key",
")",
":",
"continue",
"val",
"=",
"getattr",
"(",
"self",
",",
"key",
")",
"if",
"key",
".",
"endswith",
"(",
"\"addr\"",
")",
"or",
"key",
".",
"startswith",
"(",
"\"text_\"",
")",
":",
"lines",
".",
"append",
"(",
"template",
".",
"format",
"(",
"key",
",",
"hex",
"(",
"val",
")",
")",
")",
"elif",
"isinstance",
"(",
"val",
",",
"float",
")",
":",
"lines",
".",
"append",
"(",
"template",
".",
"format",
"(",
"key",
",",
"round",
"(",
"val",
",",
"6",
")",
")",
")",
"else",
":",
"if",
"isinstance",
"(",
"val",
",",
"bytes",
")",
":",
"try",
":",
"lines",
".",
"append",
"(",
"template",
".",
"format",
"(",
"key",
",",
"val",
".",
"decode",
"(",
")",
")",
")",
"except",
":",
"lines",
".",
"append",
"(",
"template",
".",
"format",
"(",
"key",
",",
"val",
".",
"decode",
"(",
"'latin-1'",
")",
".",
"strip",
"(",
"\"\\0\"",
")",
")",
")",
"else",
":",
"lines",
".",
"append",
"(",
"template",
".",
"format",
"(",
"key",
",",
"val",
")",
")",
"for",
"line",
"in",
"lines",
":",
"if",
"not",
"line",
":",
"metadata",
".",
"append",
"(",
"line",
")",
"else",
":",
"for",
"wrapped_line",
"in",
"wrap",
"(",
"line",
",",
"width",
"=",
"120",
")",
":",
"metadata",
".",
"append",
"(",
"wrapped_line",
")",
"return",
"\"\\n\"",
".",
"join",
"(",
"metadata",
")"
] |
CGBLOCK class
CGBLOCK fields
|
[
"CGBLOCK",
"class",
"CGBLOCK",
"fields"
] |
[
"\"\"\" CGBLOCK class\n\n CGBLOCK fields\n\n * ``id`` - bytes : block ID; always b'CG'\n * ``block_len`` - int : block bytes size\n * ``next_cg_addr`` - int : next CGBLOCK address\n * ``first_ch_addr`` - int : address of first channel block (CNBLOCK)\n * ``comment_addr`` - int : address of TXBLOCK that contains the channel\n group comment\n * ``record_id`` - int : record ID used as identifier for a record if\n the DGBLOCK defines a number of record IDs > 0 (unsorted group)\n * ``ch_nr`` - int : number of channels\n * ``samples_byte_nr`` - int : size of data record in bytes without\n record ID\n * ``cycles_nr`` - int : number of cycles (records) of this type in the data\n block\n * ``sample_reduction_addr`` - int : addresss to first sample reduction\n block\n\n Other attributes\n\n * ``address`` - int : block address inside mdf file\n * ``comment`` - str : channel group comment\n\n Parameters\n ----------\n stream : file handle\n mdf file handle\n address : int\n block address inside mdf file\n for dynamically created objects :\n see the key-value pairs\n\n\n Examples\n --------\n >>> with open('test.mdf', 'rb') as mdf:\n ... cg1 = ChannelGroup(stream=mdf, address=0xBA52)\n >>> cg2 = ChannelGroup(sample_bytes_nr=32)\n >>> hex(cg1.address)\n 0xBA52\n >>> cg1['id']\n b'CG'\n\n \"\"\"",
"# sample reduction blocks are not yet used",
"# sample reduction blocks are not yet used"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 25
| 1,614
| 372
|
9d9857ee4734f5d27273aead36af42ce34cc3666
|
fredemmott/user-documentation
|
md-render/HHVM/UserDocumentation/IncludeGuidesGeneratedMarkdownFilter.rb
|
[
"BSD-3-Clause"
] |
Ruby
|
HHVM
|
# This is not a HTML::Pipeline style filter. We want to deal with raw strings
# instead of NokoGiri Document Fragments, etc. So this is a standalone filter
# that does not require any HTML::Pipeline functionality. We go line by line
# in the text string and look for markers representing generated markdown.
# e.g., we have generated markdown for the HHVM supported PHP INI settings
# table
|
This is not a HTML::Pipeline style filter. We want to deal with raw strings
instead of NokoGiri Document Fragments, etc. So this is a standalone filter
that does not require any HTML::Pipeline functionality. We go line by line
in the text string and look for markers representing generated markdown.
e.g., we have generated markdown for the HHVM supported PHP INI settings
table
|
[
"This",
"is",
"not",
"a",
"HTML",
"::",
"Pipeline",
"style",
"filter",
".",
"We",
"want",
"to",
"deal",
"with",
"raw",
"strings",
"instead",
"of",
"NokoGiri",
"Document",
"Fragments",
"etc",
".",
"So",
"this",
"is",
"a",
"standalone",
"filter",
"that",
"does",
"not",
"require",
"any",
"HTML",
"::",
"Pipeline",
"functionality",
".",
"We",
"go",
"line",
"by",
"line",
"in",
"the",
"text",
"string",
"and",
"look",
"for",
"markers",
"representing",
"generated",
"markdown",
".",
"e",
".",
"g",
".",
"we",
"have",
"generated",
"markdown",
"for",
"the",
"HHVM",
"supported",
"PHP",
"INI",
"settings",
"table"
] |
module HHVM
module UserDocumentation
class IncludeGuidesGeneratedMarkdownFilter
def call(in_text, filename)
out_text = in_text # assume they will be the same
# Symlink to build/guides-generated-markdown
guides_generated_md_dir = 'guides-generated-markdown'
match = /(?<source_dir>.+)/.match(guides_generated_md_dir)
if ! match.nil?
gen_md_dir = match['source_dir']
base = File.expand_path(guides_generated_md_dir, File.dirname(filename))
out_text = ''
in_text.each_line do |line|
full_path = nil
if match = %r,^@@ (?<dir_name>[^/ ]+)/(?<file_name>[^/ ]+\.md) @@$,.match(line)
if match[:dir_name] === gen_md_dir
full_path = File.expand_path(match[:file_name], base)
end
elsif match = %r,^@@ (?<absolute_path>/[^@ ]+\.md) @@$,.match(line)
full_path = match[:absolute_path]
end
if full_path.nil?
out_text << line
else
if ! File.exists? full_path
text = "Missing generated guide: #{full_path}"
STDERR.write(
text.red.bold + "\n"
)
out_text << '<h1 class="warning">' + text + '</h1>'
else
out_text << File.read(full_path)
end
end
end
end
out_text
end
end
end
end
|
[
"module",
"HHVM",
"module",
"UserDocumentation",
"class",
"IncludeGuidesGeneratedMarkdownFilter",
"def",
"call",
"(",
"in_text",
",",
"filename",
")",
"out_text",
"=",
"in_text",
"guides_generated_md_dir",
"=",
"'guides-generated-markdown'",
"match",
"=",
"/",
"(?<source_dir>.+)",
"/",
".",
"match",
"(",
"guides_generated_md_dir",
")",
"if",
"!",
"match",
".",
"nil?",
"gen_md_dir",
"=",
"match",
"[",
"'source_dir'",
"]",
"base",
"=",
"File",
".",
"expand_path",
"(",
"guides_generated_md_dir",
",",
"File",
".",
"dirname",
"(",
"filename",
")",
")",
"out_text",
"=",
"''",
"in_text",
".",
"each_line",
"do",
"|",
"line",
"|",
"full_path",
"=",
"nil",
"if",
"match",
"=",
"%r,",
"^@@ (?<dir_name>[^/ ]+)/(?<file_name>[^/ ]+",
"\\.",
"md) @@$",
",",
".",
"match",
"(",
"line",
")",
"if",
"match",
"[",
":dir_name",
"]",
"===",
"gen_md_dir",
"full_path",
"=",
"File",
".",
"expand_path",
"(",
"match",
"[",
":file_name",
"]",
",",
"base",
")",
"end",
"elsif",
"match",
"=",
"%r,",
"^@@ (?<absolute_path>/[^@ ]+",
"\\.",
"md) @@$",
",",
".",
"match",
"(",
"line",
")",
"full_path",
"=",
"match",
"[",
":absolute_path",
"]",
"end",
"if",
"full_path",
".",
"nil?",
"out_text",
"<<",
"line",
"else",
"if",
"!",
"File",
".",
"exists?",
"full_path",
"text",
"=",
"\"Missing generated guide: #{full_path}\"",
"STDERR",
".",
"write",
"(",
"text",
".",
"red",
".",
"bold",
"+",
"\"\\n\"",
")",
"out_text",
"<<",
"'<h1 class=\"warning\">'",
"+",
"text",
"+",
"'</h1>'",
"else",
"out_text",
"<<",
"File",
".",
"read",
"(",
"full_path",
")",
"end",
"end",
"end",
"end",
"out_text",
"end",
"end",
"end",
"end"
] |
This is not a HTML::Pipeline style filter.
|
[
"This",
"is",
"not",
"a",
"HTML",
"::",
"Pipeline",
"style",
"filter",
"."
] |
[
"# assume they will be the same",
"# Symlink to build/guides-generated-markdown"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 23
| 346
| 89
|
feba72614eea32d13d68b3813ca0d5f550f236d9
|
rafaelvasco/SpriteVortex
|
SpriteVortex/Helpers/GifComponents/Components/ImageDescriptor.cs
|
[
"MIT"
] |
C#
|
ImageDescriptor
|
/// <summary>
/// Describes a single image within a Graphics Interchange Format data
/// stream.
/// See http://www.w3.org/Graphics/GIF/spec-gif89a.txt section 20.
/// </summary>
/// <remarks>
/// Each image in the Data Stream is composed of an Image Descriptor, an
/// optional Local Color Table, and the image data. Each image must fit
/// within the boundaries of the Logical Screen, as defined in the
/// Logical Screen Descriptor.
///
/// The Image Descriptor contains the parameters necessary to process a
/// table based image. The coordinates given in this block refer to
/// coordinates within the Logical Screen, and are given in pixels. This
/// block is a Graphic-Rendering Block, optionally preceded by one or more
/// Control blocks such as the Graphic Control Extension, and may be
/// optionally followed by a Local Color Table; the Image Descriptor is
/// always followed by the image data.
///
/// This block is REQUIRED for an image. Exactly one Image Descriptor must
/// be present per image in the Data Stream. An unlimited number of images
/// may be present per Data Stream.
///
/// The scope of this block is the Table-based Image Data Block that
/// follows it. This block may be modified by the Graphic Control Extension.
/// </remarks>
|
Describes a single image within a Graphics Interchange Format data
stream.
|
[
"Describes",
"a",
"single",
"image",
"within",
"a",
"Graphics",
"Interchange",
"Format",
"data",
"stream",
"."
] |
public class ImageDescriptor : GifComponent
{
#region declarations
private Point _position;
private Size _size;
private bool _hasLocalColourTable;
private bool _isInterlaced;
private bool _isSorted;
private int _localColourTableSizeBits;
#endregion
#region constructor
public ImageDescriptor( Point position,
Size size,
bool hasLocalColourTable,
bool isInterlaced,
bool isSorted,
int localColourTableSizeBits )
{
_position = position;
_size = size;
_hasLocalColourTable = hasLocalColourTable;
_isInterlaced = isInterlaced;
_isSorted = isSorted;
_localColourTableSizeBits = localColourTableSizeBits;
}
#endregion
#region constructor( Stream )
public ImageDescriptor( Stream inputStream ) : this( inputStream, false )
{}
#endregion
#region constructor( Stream, bool )
public ImageDescriptor( Stream inputStream, bool xmlDebugging )
: base( xmlDebugging )
{
int leftPosition = ReadShort( inputStream );
int topPosition = ReadShort( inputStream );
int width = ReadShort( inputStream );
int height = ReadShort( inputStream );
_position = new Point( leftPosition, topPosition );
_size = new Size( width, height );
PackedFields packed = new PackedFields( Read( inputStream ) );
_hasLocalColourTable = packed.GetBit( 0 );
_isInterlaced = packed.GetBit( 1 );
_isSorted = packed.GetBit( 2 );
_localColourTableSizeBits = packed.GetBits( 5, 3 );
if( XmlDebugging )
{
WriteDebugXmlStartElement( "Position" );
WriteDebugXmlAttribute( "X", _position.X );
WriteDebugXmlAttribute( "Y", _position.Y );
WriteDebugXmlEndElement();
WriteDebugXmlStartElement( "Size" );
WriteDebugXmlAttribute( "Width", _size.Width );
WriteDebugXmlAttribute( "Height", _size.Height );
WriteDebugXmlEndElement();
WriteDebugXmlStartElement( "PackedFields" );
WriteDebugXmlAttribute( "ByteRead", ToHex( packed.Byte ) );
WriteDebugXmlAttribute( "HasLocalColourTable",
_hasLocalColourTable );
WriteDebugXmlAttribute( "IsInterlaced", _isInterlaced );
WriteDebugXmlAttribute( "LocalColourTableIsSorted", _isSorted );
WriteDebugXmlAttribute( "LocalColourTableSizeBits",
_localColourTableSizeBits );
WriteDebugXmlEndElement();
WriteDebugXmlFinish();
}
}
#endregion
#region logical properties
#region Position property
public Point Position
{
get { return _position; }
}
#endregion
#region Size property
public Size Size
{
get { return _size; }
}
#endregion
#region HasLocalColourTable property
public bool HasLocalColourTable
{
get { return _hasLocalColourTable;; }
}
#endregion
#region IsInterlaced property
public bool IsInterlaced
{
get { return _isInterlaced; }
}
#endregion
#region IsSorted property
public bool IsSorted
{
get { return _isSorted; }
}
#endregion
#region LocalColourTableSizeBits property
public int LocalColourTableSizeBits
{
get { return _localColourTableSizeBits; }
}
#endregion
#region LocalColourTableSize property
public int LocalColourTableSize
{
get { return 2 << _localColourTableSizeBits; }
}
#endregion
#endregion
#region public WriteToStream method
public override void WriteToStream( Stream outputStream )
{
WriteShort( _position.X, outputStream );
WriteShort( _position.Y, outputStream );
WriteShort( _size.Width, outputStream );
WriteShort( _size.Height, outputStream );
PackedFields packed = new PackedFields();
packed.SetBit( 0, _hasLocalColourTable );
packed.SetBit( 1, _isInterlaced );
packed.SetBit( 2, _isSorted );
packed.SetBits( 5, 3, _localColourTableSizeBits );
WriteByte( packed.Byte, outputStream );
}
#endregion
}
|
[
"public",
"class",
"ImageDescriptor",
":",
"GifComponent",
"{",
"region",
" declarations",
"private",
"Point",
"_position",
";",
"private",
"Size",
"_size",
";",
"private",
"bool",
"_hasLocalColourTable",
";",
"private",
"bool",
"_isInterlaced",
";",
"private",
"bool",
"_isSorted",
";",
"private",
"int",
"_localColourTableSizeBits",
";",
"endregion",
"region",
" constructor",
"public",
"ImageDescriptor",
"(",
"Point",
"position",
",",
"Size",
"size",
",",
"bool",
"hasLocalColourTable",
",",
"bool",
"isInterlaced",
",",
"bool",
"isSorted",
",",
"int",
"localColourTableSizeBits",
")",
"{",
"_position",
"=",
"position",
";",
"_size",
"=",
"size",
";",
"_hasLocalColourTable",
"=",
"hasLocalColourTable",
";",
"_isInterlaced",
"=",
"isInterlaced",
";",
"_isSorted",
"=",
"isSorted",
";",
"_localColourTableSizeBits",
"=",
"localColourTableSizeBits",
";",
"}",
"endregion",
"region",
" constructor( Stream )",
"public",
"ImageDescriptor",
"(",
"Stream",
"inputStream",
")",
":",
"this",
"(",
"inputStream",
",",
"false",
")",
"{",
"}",
"endregion",
"region",
" constructor( Stream, bool )",
"public",
"ImageDescriptor",
"(",
"Stream",
"inputStream",
",",
"bool",
"xmlDebugging",
")",
":",
"base",
"(",
"xmlDebugging",
")",
"{",
"int",
"leftPosition",
"=",
"ReadShort",
"(",
"inputStream",
")",
";",
"int",
"topPosition",
"=",
"ReadShort",
"(",
"inputStream",
")",
";",
"int",
"width",
"=",
"ReadShort",
"(",
"inputStream",
")",
";",
"int",
"height",
"=",
"ReadShort",
"(",
"inputStream",
")",
";",
"_position",
"=",
"new",
"Point",
"(",
"leftPosition",
",",
"topPosition",
")",
";",
"_size",
"=",
"new",
"Size",
"(",
"width",
",",
"height",
")",
";",
"PackedFields",
"packed",
"=",
"new",
"PackedFields",
"(",
"Read",
"(",
"inputStream",
")",
")",
";",
"_hasLocalColourTable",
"=",
"packed",
".",
"GetBit",
"(",
"0",
")",
";",
"_isInterlaced",
"=",
"packed",
".",
"GetBit",
"(",
"1",
")",
";",
"_isSorted",
"=",
"packed",
".",
"GetBit",
"(",
"2",
")",
";",
"_localColourTableSizeBits",
"=",
"packed",
".",
"GetBits",
"(",
"5",
",",
"3",
")",
";",
"if",
"(",
"XmlDebugging",
")",
"{",
"WriteDebugXmlStartElement",
"(",
"\"",
"Position",
"\"",
")",
";",
"WriteDebugXmlAttribute",
"(",
"\"",
"X",
"\"",
",",
"_position",
".",
"X",
")",
";",
"WriteDebugXmlAttribute",
"(",
"\"",
"Y",
"\"",
",",
"_position",
".",
"Y",
")",
";",
"WriteDebugXmlEndElement",
"(",
")",
";",
"WriteDebugXmlStartElement",
"(",
"\"",
"Size",
"\"",
")",
";",
"WriteDebugXmlAttribute",
"(",
"\"",
"Width",
"\"",
",",
"_size",
".",
"Width",
")",
";",
"WriteDebugXmlAttribute",
"(",
"\"",
"Height",
"\"",
",",
"_size",
".",
"Height",
")",
";",
"WriteDebugXmlEndElement",
"(",
")",
";",
"WriteDebugXmlStartElement",
"(",
"\"",
"PackedFields",
"\"",
")",
";",
"WriteDebugXmlAttribute",
"(",
"\"",
"ByteRead",
"\"",
",",
"ToHex",
"(",
"packed",
".",
"Byte",
")",
")",
";",
"WriteDebugXmlAttribute",
"(",
"\"",
"HasLocalColourTable",
"\"",
",",
"_hasLocalColourTable",
")",
";",
"WriteDebugXmlAttribute",
"(",
"\"",
"IsInterlaced",
"\"",
",",
"_isInterlaced",
")",
";",
"WriteDebugXmlAttribute",
"(",
"\"",
"LocalColourTableIsSorted",
"\"",
",",
"_isSorted",
")",
";",
"WriteDebugXmlAttribute",
"(",
"\"",
"LocalColourTableSizeBits",
"\"",
",",
"_localColourTableSizeBits",
")",
";",
"WriteDebugXmlEndElement",
"(",
")",
";",
"WriteDebugXmlFinish",
"(",
")",
";",
"}",
"}",
"endregion",
"region",
" logical properties",
"region",
" Position property",
"public",
"Point",
"Position",
"{",
"get",
"{",
"return",
"_position",
";",
"}",
"}",
"endregion",
"region",
" Size property",
"public",
"Size",
"Size",
"{",
"get",
"{",
"return",
"_size",
";",
"}",
"}",
"endregion",
"region",
" HasLocalColourTable property",
"public",
"bool",
"HasLocalColourTable",
"{",
"get",
"{",
"return",
"_hasLocalColourTable",
";",
";",
"}",
"}",
"endregion",
"region",
" IsInterlaced property",
"public",
"bool",
"IsInterlaced",
"{",
"get",
"{",
"return",
"_isInterlaced",
";",
"}",
"}",
"endregion",
"region",
" IsSorted property",
"public",
"bool",
"IsSorted",
"{",
"get",
"{",
"return",
"_isSorted",
";",
"}",
"}",
"endregion",
"region",
" LocalColourTableSizeBits property",
"public",
"int",
"LocalColourTableSizeBits",
"{",
"get",
"{",
"return",
"_localColourTableSizeBits",
";",
"}",
"}",
"endregion",
"region",
" LocalColourTableSize property",
"public",
"int",
"LocalColourTableSize",
"{",
"get",
"{",
"return",
"2",
"<<",
"_localColourTableSizeBits",
";",
"}",
"}",
"endregion",
"endregion",
"region",
" public WriteToStream method",
"public",
"override",
"void",
"WriteToStream",
"(",
"Stream",
"outputStream",
")",
"{",
"WriteShort",
"(",
"_position",
".",
"X",
",",
"outputStream",
")",
";",
"WriteShort",
"(",
"_position",
".",
"Y",
",",
"outputStream",
")",
";",
"WriteShort",
"(",
"_size",
".",
"Width",
",",
"outputStream",
")",
";",
"WriteShort",
"(",
"_size",
".",
"Height",
",",
"outputStream",
")",
";",
"PackedFields",
"packed",
"=",
"new",
"PackedFields",
"(",
")",
";",
"packed",
".",
"SetBit",
"(",
"0",
",",
"_hasLocalColourTable",
")",
";",
"packed",
".",
"SetBit",
"(",
"1",
",",
"_isInterlaced",
")",
";",
"packed",
".",
"SetBit",
"(",
"2",
",",
"_isSorted",
")",
";",
"packed",
".",
"SetBits",
"(",
"5",
",",
"3",
",",
"_localColourTableSizeBits",
")",
";",
"WriteByte",
"(",
"packed",
".",
"Byte",
",",
"outputStream",
")",
";",
"}",
"endregion",
"}"
] |
Describes a single image within a Graphics Interchange Format data
stream.
|
[
"Describes",
"a",
"single",
"image",
"within",
"a",
"Graphics",
"Interchange",
"Format",
"data",
"stream",
"."
] |
[
"/// <summary>",
"/// Constructor.",
"/// </summary>",
"/// <param name=\"position\">",
"/// Sets the <see cref=\"Position\"/>.",
"/// </param>",
"/// <param name=\"size\">",
"/// Sets the <see cref=\"Size\"/>.",
"/// </param>",
"/// <param name=\"hasLocalColourTable\">",
"/// Sets the <see cref=\"HasLocalColourTable\"/> flag.",
"/// </param>",
"/// <param name=\"isInterlaced\">",
"/// Sets the <see cref=\"IsInterlaced\"/> flag.",
"/// </param>",
"/// <param name=\"isSorted\">",
"/// Sets the <see cref=\"IsSorted\"/> flag.",
"/// </param>",
"/// <param name=\"localColourTableSizeBits\">",
"/// Sets the <see cref=\"LocalColourTableSizeBits\"/>.",
"/// </param>",
"/// <summary>",
"/// Reads and returns an image descriptor from the supplied stream.",
"/// </summary>",
"/// <param name=\"inputStream\">",
"/// The input stream to read.",
"/// </param>",
"/// <summary>",
"/// Reads and returns an image descriptor from the supplied stream.",
"/// </summary>",
"/// <param name=\"inputStream\">",
"/// The input stream to read.",
"/// </param>",
"/// <param name=\"xmlDebugging\">Whether or not to create debug XML</param>",
"// (sub)image position & size",
"/// <summary>",
"/// Gets the position, in pixels, of the top-left corner of the image,",
"/// with respect to the top-left corner of the logical screen.",
"/// Top-left corner of the logical screen is 0,0.",
"/// </summary>",
"/// <summary>",
"/// Gets the size of the image in pixels.",
"/// </summary>",
"/// <summary>",
"/// Gets a boolean value indicating the presence of a Local Color Table ",
"/// immediately following this Image Descriptor.",
"/// </summary>",
"/// <summary>",
"/// Gets a boolean value indicating whether the image is interlaced. An ",
"/// image is interlaced in a four-pass interlace pattern; see Appendix E ",
"/// for details.",
"/// </summary>",
"/// <summary>",
"/// Gets a boolean value indicating whether the Local Color Table is",
"/// sorted. If the flag is set, the Local Color Table is sorted, in",
"/// order of decreasing importance. Typically, the order would be",
"/// decreasing frequency, with most frequent color first. This assists",
"/// a decoder, with fewer available colors, in choosing the best subset",
"/// of colors; the decoder may use an initial segment of the table to",
"/// render the graphic.",
"/// </summary>",
"/// <summary>",
"/// If the Local Color Table Flag is set to 1, the value in this field ",
"/// is used to calculate the number of bytes contained in the Local ",
"/// Color Table. To determine that actual size of the color table, ",
"/// raise 2 to the value of the field + 1. ",
"/// This value should be 0 if there is no Local Color Table specified.",
"/// </summary>",
"/// <summary>",
"/// Gets the actual size of the local colour table.",
"/// </summary>",
"/// <summary>",
"/// Writes this component to the supplied output stream.",
"/// </summary>",
"/// <param name=\"outputStream\">",
"/// The output stream to write to.",
"/// </param>",
"// Position and size of the image in this frame"
] |
[
{
"param": "GifComponent",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "GifComponent",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": [
{
"identifier": "remarks",
"docstring": "Each image in the Data Stream is composed of an Image Descriptor, an\noptional Local Color Table, and the image data. Each image must fit\nwithin the boundaries of the Logical Screen, as defined in the\nLogical Screen Descriptor.\n\nThe Image Descriptor contains the parameters necessary to process a\ntable based image. The coordinates given in this block refer to\ncoordinates within the Logical Screen, and are given in pixels. This\nblock is a Graphic-Rendering Block, optionally preceded by one or more\nControl blocks such as the Graphic Control Extension, and may be\noptionally followed by a Local Color Table; the Image Descriptor is\nalways followed by the image data.\n\nThis block is REQUIRED for an image. Exactly one Image Descriptor must\nbe present per image in the Data Stream. An unlimited number of images\nmay be present per Data Stream.\n\nThe scope of this block is the Table-based Image Data Block that\nfollows it. This block may be modified by the Graphic Control Extension.",
"docstring_tokens": [
"Each",
"image",
"in",
"the",
"Data",
"Stream",
"is",
"composed",
"of",
"an",
"Image",
"Descriptor",
"an",
"optional",
"Local",
"Color",
"Table",
"and",
"the",
"image",
"data",
".",
"Each",
"image",
"must",
"fit",
"within",
"the",
"boundaries",
"of",
"the",
"Logical",
"Screen",
"as",
"defined",
"in",
"the",
"Logical",
"Screen",
"Descriptor",
".",
"The",
"Image",
"Descriptor",
"contains",
"the",
"parameters",
"necessary",
"to",
"process",
"a",
"table",
"based",
"image",
".",
"The",
"coordinates",
"given",
"in",
"this",
"block",
"refer",
"to",
"coordinates",
"within",
"the",
"Logical",
"Screen",
"and",
"are",
"given",
"in",
"pixels",
".",
"This",
"block",
"is",
"a",
"Graphic",
"-",
"Rendering",
"Block",
"optionally",
"preceded",
"by",
"one",
"or",
"more",
"Control",
"blocks",
"such",
"as",
"the",
"Graphic",
"Control",
"Extension",
"and",
"may",
"be",
"optionally",
"followed",
"by",
"a",
"Local",
"Color",
"Table",
";",
"the",
"Image",
"Descriptor",
"is",
"always",
"followed",
"by",
"the",
"image",
"data",
".",
"This",
"block",
"is",
"REQUIRED",
"for",
"an",
"image",
".",
"Exactly",
"one",
"Image",
"Descriptor",
"must",
"be",
"present",
"per",
"image",
"in",
"the",
"Data",
"Stream",
".",
"An",
"unlimited",
"number",
"of",
"images",
"may",
"be",
"present",
"per",
"Data",
"Stream",
".",
"The",
"scope",
"of",
"this",
"block",
"is",
"the",
"Table",
"-",
"based",
"Image",
"Data",
"Block",
"that",
"follows",
"it",
".",
"This",
"block",
"may",
"be",
"modified",
"by",
"the",
"Graphic",
"Control",
"Extension",
"."
]
}
]
}
| false
| 15
| 1,007
| 278
|
c8ecb582bbbe6f1d8e093b7bda84af9fe16d52e5
|
sourcearchive/spring-framework
|
src/org/springframework/aop/framework/autoproxy/target/QuickTargetSourceCreator.java
|
[
"Apache-2.0"
] |
Java
|
QuickTargetSourceCreator
|
/**
* Convenient TargetSourceCreator using bean name prefixes to create one of three
* well-known TargetSource types:
* <li>: CommonsPoolTargetSource
* <li>% ThreadLocalTargetSource
* <li>! PrototypeTargetSource
*
* @author Rod Johnson
* @version $Id: QuickTargetSourceCreator.java,v 1.3 2004/03/18 02:46:16 trisberg Exp $
*/
|
Convenient TargetSourceCreator using bean name prefixes to create one of three
well-known TargetSource types:
: CommonsPoolTargetSource
% ThreadLocalTargetSource
.
@author Rod Johnson
@version $Id: QuickTargetSourceCreator.java,v 1.3 2004/03/18 02:46:16 trisberg Exp $
|
[
"Convenient",
"TargetSourceCreator",
"using",
"bean",
"name",
"prefixes",
"to",
"create",
"one",
"of",
"three",
"well",
"-",
"known",
"TargetSource",
"types",
":",
":",
"CommonsPoolTargetSource",
"%",
"ThreadLocalTargetSource",
".",
"@author",
"Rod",
"Johnson",
"@version",
"$Id",
":",
"QuickTargetSourceCreator",
".",
"java",
"v",
"1",
".",
"3",
"2004",
"/",
"03",
"/",
"18",
"02",
":",
"46",
":",
"16",
"trisberg",
"Exp",
"$"
] |
public class QuickTargetSourceCreator extends AbstractPrototypeTargetSourceCreator {
protected final AbstractPrototypeTargetSource createPrototypeTargetSource(Object bean, String beanName, BeanFactory factory) {
if (beanName.startsWith(":")) {
CommonsPoolTargetSource cpts = new CommonsPoolTargetSource();
cpts.setMaxSize(25);
return cpts;
}
else if (beanName.startsWith("%")) {
ThreadLocalTargetSource tlts = new ThreadLocalTargetSource();
return tlts;
}
else if (beanName.startsWith("!")) {
PrototypeTargetSource pts = new PrototypeTargetSource();
return pts;
}
else {
// No match. Don't create a custom target source.
return null;
}
}
}
|
[
"public",
"class",
"QuickTargetSourceCreator",
"extends",
"AbstractPrototypeTargetSourceCreator",
"{",
"protected",
"final",
"AbstractPrototypeTargetSource",
"createPrototypeTargetSource",
"(",
"Object",
"bean",
",",
"String",
"beanName",
",",
"BeanFactory",
"factory",
")",
"{",
"if",
"(",
"beanName",
".",
"startsWith",
"(",
"\"",
":",
"\"",
")",
")",
"{",
"CommonsPoolTargetSource",
"cpts",
"=",
"new",
"CommonsPoolTargetSource",
"(",
")",
";",
"cpts",
".",
"setMaxSize",
"(",
"25",
")",
";",
"return",
"cpts",
";",
"}",
"else",
"if",
"(",
"beanName",
".",
"startsWith",
"(",
"\"",
"%",
"\"",
")",
")",
"{",
"ThreadLocalTargetSource",
"tlts",
"=",
"new",
"ThreadLocalTargetSource",
"(",
")",
";",
"return",
"tlts",
";",
"}",
"else",
"if",
"(",
"beanName",
".",
"startsWith",
"(",
"\"",
"!",
"\"",
")",
")",
"{",
"PrototypeTargetSource",
"pts",
"=",
"new",
"PrototypeTargetSource",
"(",
")",
";",
"return",
"pts",
";",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"}",
"}"
] |
Convenient TargetSourceCreator using bean name prefixes to create one of three
well-known TargetSource types:
<li>: CommonsPoolTargetSource
<li>% ThreadLocalTargetSource
<li>!
|
[
"Convenient",
"TargetSourceCreator",
"using",
"bean",
"name",
"prefixes",
"to",
"create",
"one",
"of",
"three",
"well",
"-",
"known",
"TargetSource",
"types",
":",
"<li",
">",
":",
"CommonsPoolTargetSource",
"<li",
">",
"%",
"ThreadLocalTargetSource",
"<li",
">",
"!"
] |
[
"// No match. Don't create a custom target source.\r"
] |
[
{
"param": "AbstractPrototypeTargetSourceCreator",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "AbstractPrototypeTargetSourceCreator",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 13
| 166
| 101
|
72536837dac873cacb073afa76207d33849eaa61
|
denza/gocd
|
server/webapp/WEB-INF/rails.new/app/presenters/api_v1/version_representer.rb
|
[
"Apache-2.0"
] |
Ruby
|
ApiV1
|
##########################################################################
# Copyright 2016 ThoughtWorks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##########################################################################
|
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
|
[
"Unless",
"required",
"by",
"applicable",
"law",
"or",
"agreed",
"to",
"in",
"writing",
"software",
"distributed",
"under",
"the",
"License",
"is",
"distributed",
"on",
"an",
"\"",
"AS",
"IS",
"\"",
"BASIS",
"WITHOUT",
"WARRANTIES",
"OR",
"CONDITIONS",
"OF",
"ANY",
"KIND",
"either",
"express",
"or",
"implied",
".",
"See",
"the",
"License",
"for",
"the",
"specific",
"language",
"governing",
"permissions",
"and",
"limitations",
"under",
"the",
"License",
"."
] |
module ApiV1
class VersionRepresenter < ApiV1::BaseRepresenter
alias_method :server_version, :represented
link :self do |opts|
opts[:url_builder].apiv1_version_url
end
link :doc do
'http://api.go.cd/#version'
end
property :version
property :build_number
property :git_sha
property :full_version
property :commit_url
class << self
def representer
@@representer ||= VersionRepresenter.new(version)
end
def version
@@version ||= begin
json = JSON.parse(File.read(Rails.root.join('..', 'server_version.json')), symbolize_names: true)
json[:full_version] = "#{json[:version]} (#{json[:build_number]}-#{json[:git_sha]})"
json[:commit_url] = "https://github.com/gocd/gocd/commit/#{json[:git_sha]}"
OpenStruct.new(json)
end
end
end
end
end
|
[
"module",
"ApiV1",
"class",
"VersionRepresenter",
"<",
"ApiV1",
"::",
"BaseRepresenter",
"alias_method",
":server_version",
",",
":represented",
"link",
":self",
"do",
"|",
"opts",
"|",
"opts",
"[",
":url_builder",
"]",
".",
"apiv1_version_url",
"end",
"link",
":doc",
"do",
"'http://api.go.cd/#version'",
"end",
"property",
":version",
"property",
":build_number",
"property",
":git_sha",
"property",
":full_version",
"property",
":commit_url",
"class",
"<<",
"self",
"def",
"representer",
"@@representer",
"||=",
"VersionRepresenter",
".",
"new",
"(",
"version",
")",
"end",
"def",
"version",
"@@version",
"||=",
"begin",
"json",
"=",
"JSON",
".",
"parse",
"(",
"File",
".",
"read",
"(",
"Rails",
".",
"root",
".",
"join",
"(",
"'..'",
",",
"'server_version.json'",
")",
")",
",",
"symbolize_names",
":",
"true",
")",
"json",
"[",
":full_version",
"]",
"=",
"\"#{json[:version]} (#{json[:build_number]}-#{json[:git_sha]})\"",
"json",
"[",
":commit_url",
"]",
"=",
"\"https://github.com/gocd/gocd/commit/#{json[:git_sha]}\"",
"OpenStruct",
".",
"new",
"(",
"json",
")",
"end",
"end",
"end",
"end",
"end"
] |
Copyright 2016 ThoughtWorks, Inc.
|
[
"Copyright",
"2016",
"ThoughtWorks",
"Inc",
"."
] |
[] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 19
| 231
| 136
|
d0c746f3254ce5400eb92da15d81e3497a3eccf0
|
horatiu665/toybox
|
ToyBox/EnumButtons/Editor/EnumButtonsDrawer.cs
|
[
"MIT"
] |
C#
|
EnumButtonsDrawer
|
/// <summary>
/// Draws a one-line sequence of named buttons, that makes a short enum easy to select.
/// For longer enums consider using <see cref="EnumLongSelectionAttribute"/>
///
/// Inspired from http://www.sharkbombs.com/2015/02/17/unity-editor-enum-flags-as-toggle-buttons/
///
/// made by @horatiu665
/// </summary>
|
Draws a one-line sequence of named buttons, that makes a short enum easy to select.
For longer enums consider using
made by @horatiu665
|
[
"Draws",
"a",
"one",
"-",
"line",
"sequence",
"of",
"named",
"buttons",
"that",
"makes",
"a",
"short",
"enum",
"easy",
"to",
"select",
".",
"For",
"longer",
"enums",
"consider",
"using",
"made",
"by",
"@horatiu665"
] |
[CustomPropertyDrawer(typeof(EnumButtonsAttribute))]
public class EnumButtonsDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
var eba = ((EnumButtonsAttribute)this.attribute);
bool isFlags = eba.isFlags;
if (isFlags)
{
OnGUI_FlagsVersion(position, property, label);
}
else
{
OnGUI_EnumVersion(position, property, label);
}
}
private void OnGUI_EnumVersion(Rect position, SerializedProperty property, GUIContent label)
{
int buttonsIntValue = 0;
int enumLength = property.enumNames.Length;
float buttonWidth = (position.width - EditorGUIUtility.labelWidth) / enumLength;
EditorGUI.LabelField(new Rect(position.x, position.y, EditorGUIUtility.labelWidth, position.height), label);
var obj = property.serializedObject.targetObject;
var ownerType = obj.GetType();
var binding = System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance;
var field = ownerType.GetField(property.name, binding);
var type = field.FieldType;
int[] enumValues = Enum.GetValues(type).Cast<int>().ToArray();
EditorGUI.BeginChangeCheck();
{
for (int i = 0; i < enumLength; i++)
{
var style = ButtonStyle(enumLength, i);
bool buttonWasPressed = false;
if (property.intValue == enumValues[i])
{
buttonWasPressed = true;
}
Rect buttonPos = new Rect(position.x + EditorGUIUtility.labelWidth + buttonWidth * i, position.y, buttonWidth, position.height);
var userPressButton = GUI.Toggle(buttonPos, buttonWasPressed, new GUIContent(property.enumNames[i], property.enumNames[i] + " (" + enumValues[i] + ")"), style);
if (userPressButton && !buttonWasPressed)
{
buttonsIntValue = enumValues[i];
}
}
}
if (EditorGUI.EndChangeCheck())
{
property.intValue = buttonsIntValue;
}
}
private static void OnGUI_FlagsVersion(Rect position, SerializedProperty property, GUIContent label)
{
int buttonsIntValue = 0;
int enumLength = property.enumNames.Length;
bool[] buttonPressed = new bool[enumLength];
float buttonWidth = (position.width - EditorGUIUtility.labelWidth) / enumLength;
EditorGUI.LabelField(new Rect(position.x, position.y, EditorGUIUtility.labelWidth, position.height), label);
var obj = property.serializedObject.targetObject;
var ownerType = obj.GetType();
var binding = System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance;
var field = ownerType.GetField(property.name, binding);
var type = field.FieldType;
int[] enumValues = Enum.GetValues(type).Cast<int>().ToArray();
EditorGUI.BeginChangeCheck();
for (int i = 0; i < enumLength; i++)
{
var style = ButtonStyle(enumLength, i);
bool isPowerOfTwo = Mathf.IsPowerOfTwo(enumValues[i]);
if (enumValues[i] == 0)
{
buttonPressed[i] = property.intValue == 0;
}
else if (isPowerOfTwo)
{
if ((property.intValue & enumValues[i]) == enumValues[i])
{
buttonPressed[i] = true;
}
}
else
{
if ((property.intValue & enumValues[i]) == enumValues[i])
{
buttonPressed[i] = true;
}
}
Rect buttonPos = new Rect(position.x + EditorGUIUtility.labelWidth + buttonWidth * i, position.y, buttonWidth, position.height);
var userPressButton = GUI.Toggle(buttonPos, buttonPressed[i], new GUIContent(property.enumNames[i], property.enumNames[i] + " (" + enumValues[i] + ")"), style);
if (userPressButton)
{
if (enumValues[i] == 0)
{
buttonsIntValue = 0;
property.intValue = 0;
}
else if (isPowerOfTwo)
{
buttonPressed[i] = userPressButton;
buttonsIntValue += enumValues[i];
}
else
{
if (!buttonPressed[i])
{
buttonsIntValue = buttonsIntValue | enumValues[i];
}
}
}
else
{
if (buttonPressed[i])
{
if (!isPowerOfTwo)
{
buttonsIntValue = buttonsIntValue ^ enumValues[i];
}
}
}
}
if (EditorGUI.EndChangeCheck())
{
property.intValue = buttonsIntValue;
}
}
private static GUIStyle ButtonStyle(int enumLength, int i)
{
if (i == 0)
{
return EditorStyles.miniButtonLeft;
}
else if (i == enumLength - 1)
{
return EditorStyles.miniButtonRight;
}
else
{
return EditorStyles.miniButtonMid;
}
}
}
|
[
"[",
"CustomPropertyDrawer",
"(",
"typeof",
"(",
"EnumButtonsAttribute",
")",
")",
"]",
"public",
"class",
"EnumButtonsDrawer",
":",
"PropertyDrawer",
"{",
"public",
"override",
"void",
"OnGUI",
"(",
"Rect",
"position",
",",
"SerializedProperty",
"property",
",",
"GUIContent",
"label",
")",
"{",
"var",
"eba",
"=",
"(",
"(",
"EnumButtonsAttribute",
")",
"this",
".",
"attribute",
")",
";",
"bool",
"isFlags",
"=",
"eba",
".",
"isFlags",
";",
"if",
"(",
"isFlags",
")",
"{",
"OnGUI_FlagsVersion",
"(",
"position",
",",
"property",
",",
"label",
")",
";",
"}",
"else",
"{",
"OnGUI_EnumVersion",
"(",
"position",
",",
"property",
",",
"label",
")",
";",
"}",
"}",
"private",
"void",
"OnGUI_EnumVersion",
"(",
"Rect",
"position",
",",
"SerializedProperty",
"property",
",",
"GUIContent",
"label",
")",
"{",
"int",
"buttonsIntValue",
"=",
"0",
";",
"int",
"enumLength",
"=",
"property",
".",
"enumNames",
".",
"Length",
";",
"float",
"buttonWidth",
"=",
"(",
"position",
".",
"width",
"-",
"EditorGUIUtility",
".",
"labelWidth",
")",
"/",
"enumLength",
";",
"EditorGUI",
".",
"LabelField",
"(",
"new",
"Rect",
"(",
"position",
".",
"x",
",",
"position",
".",
"y",
",",
"EditorGUIUtility",
".",
"labelWidth",
",",
"position",
".",
"height",
")",
",",
"label",
")",
";",
"var",
"obj",
"=",
"property",
".",
"serializedObject",
".",
"targetObject",
";",
"var",
"ownerType",
"=",
"obj",
".",
"GetType",
"(",
")",
";",
"var",
"binding",
"=",
"System",
".",
"Reflection",
".",
"BindingFlags",
".",
"Static",
"|",
"System",
".",
"Reflection",
".",
"BindingFlags",
".",
"Public",
"|",
"System",
".",
"Reflection",
".",
"BindingFlags",
".",
"NonPublic",
"|",
"System",
".",
"Reflection",
".",
"BindingFlags",
".",
"Instance",
";",
"var",
"field",
"=",
"ownerType",
".",
"GetField",
"(",
"property",
".",
"name",
",",
"binding",
")",
";",
"var",
"type",
"=",
"field",
".",
"FieldType",
";",
"int",
"[",
"]",
"enumValues",
"=",
"Enum",
".",
"GetValues",
"(",
"type",
")",
".",
"Cast",
"<",
"int",
">",
"(",
")",
".",
"ToArray",
"(",
")",
";",
"EditorGUI",
".",
"BeginChangeCheck",
"(",
")",
";",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"enumLength",
";",
"i",
"++",
")",
"{",
"var",
"style",
"=",
"ButtonStyle",
"(",
"enumLength",
",",
"i",
")",
";",
"bool",
"buttonWasPressed",
"=",
"false",
";",
"if",
"(",
"property",
".",
"intValue",
"==",
"enumValues",
"[",
"i",
"]",
")",
"{",
"buttonWasPressed",
"=",
"true",
";",
"}",
"Rect",
"buttonPos",
"=",
"new",
"Rect",
"(",
"position",
".",
"x",
"+",
"EditorGUIUtility",
".",
"labelWidth",
"+",
"buttonWidth",
"*",
"i",
",",
"position",
".",
"y",
",",
"buttonWidth",
",",
"position",
".",
"height",
")",
";",
"var",
"userPressButton",
"=",
"GUI",
".",
"Toggle",
"(",
"buttonPos",
",",
"buttonWasPressed",
",",
"new",
"GUIContent",
"(",
"property",
".",
"enumNames",
"[",
"i",
"]",
",",
"property",
".",
"enumNames",
"[",
"i",
"]",
"+",
"\"",
" (",
"\"",
"+",
"enumValues",
"[",
"i",
"]",
"+",
"\"",
")",
"\"",
")",
",",
"style",
")",
";",
"if",
"(",
"userPressButton",
"&&",
"!",
"buttonWasPressed",
")",
"{",
"buttonsIntValue",
"=",
"enumValues",
"[",
"i",
"]",
";",
"}",
"}",
"}",
"if",
"(",
"EditorGUI",
".",
"EndChangeCheck",
"(",
")",
")",
"{",
"property",
".",
"intValue",
"=",
"buttonsIntValue",
";",
"}",
"}",
"private",
"static",
"void",
"OnGUI_FlagsVersion",
"(",
"Rect",
"position",
",",
"SerializedProperty",
"property",
",",
"GUIContent",
"label",
")",
"{",
"int",
"buttonsIntValue",
"=",
"0",
";",
"int",
"enumLength",
"=",
"property",
".",
"enumNames",
".",
"Length",
";",
"bool",
"[",
"]",
"buttonPressed",
"=",
"new",
"bool",
"[",
"enumLength",
"]",
";",
"float",
"buttonWidth",
"=",
"(",
"position",
".",
"width",
"-",
"EditorGUIUtility",
".",
"labelWidth",
")",
"/",
"enumLength",
";",
"EditorGUI",
".",
"LabelField",
"(",
"new",
"Rect",
"(",
"position",
".",
"x",
",",
"position",
".",
"y",
",",
"EditorGUIUtility",
".",
"labelWidth",
",",
"position",
".",
"height",
")",
",",
"label",
")",
";",
"var",
"obj",
"=",
"property",
".",
"serializedObject",
".",
"targetObject",
";",
"var",
"ownerType",
"=",
"obj",
".",
"GetType",
"(",
")",
";",
"var",
"binding",
"=",
"System",
".",
"Reflection",
".",
"BindingFlags",
".",
"Static",
"|",
"System",
".",
"Reflection",
".",
"BindingFlags",
".",
"Public",
"|",
"System",
".",
"Reflection",
".",
"BindingFlags",
".",
"NonPublic",
"|",
"System",
".",
"Reflection",
".",
"BindingFlags",
".",
"Instance",
";",
"var",
"field",
"=",
"ownerType",
".",
"GetField",
"(",
"property",
".",
"name",
",",
"binding",
")",
";",
"var",
"type",
"=",
"field",
".",
"FieldType",
";",
"int",
"[",
"]",
"enumValues",
"=",
"Enum",
".",
"GetValues",
"(",
"type",
")",
".",
"Cast",
"<",
"int",
">",
"(",
")",
".",
"ToArray",
"(",
")",
";",
"EditorGUI",
".",
"BeginChangeCheck",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"enumLength",
";",
"i",
"++",
")",
"{",
"var",
"style",
"=",
"ButtonStyle",
"(",
"enumLength",
",",
"i",
")",
";",
"bool",
"isPowerOfTwo",
"=",
"Mathf",
".",
"IsPowerOfTwo",
"(",
"enumValues",
"[",
"i",
"]",
")",
";",
"if",
"(",
"enumValues",
"[",
"i",
"]",
"==",
"0",
")",
"{",
"buttonPressed",
"[",
"i",
"]",
"=",
"property",
".",
"intValue",
"==",
"0",
";",
"}",
"else",
"if",
"(",
"isPowerOfTwo",
")",
"{",
"if",
"(",
"(",
"property",
".",
"intValue",
"&",
"enumValues",
"[",
"i",
"]",
")",
"==",
"enumValues",
"[",
"i",
"]",
")",
"{",
"buttonPressed",
"[",
"i",
"]",
"=",
"true",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"(",
"property",
".",
"intValue",
"&",
"enumValues",
"[",
"i",
"]",
")",
"==",
"enumValues",
"[",
"i",
"]",
")",
"{",
"buttonPressed",
"[",
"i",
"]",
"=",
"true",
";",
"}",
"}",
"Rect",
"buttonPos",
"=",
"new",
"Rect",
"(",
"position",
".",
"x",
"+",
"EditorGUIUtility",
".",
"labelWidth",
"+",
"buttonWidth",
"*",
"i",
",",
"position",
".",
"y",
",",
"buttonWidth",
",",
"position",
".",
"height",
")",
";",
"var",
"userPressButton",
"=",
"GUI",
".",
"Toggle",
"(",
"buttonPos",
",",
"buttonPressed",
"[",
"i",
"]",
",",
"new",
"GUIContent",
"(",
"property",
".",
"enumNames",
"[",
"i",
"]",
",",
"property",
".",
"enumNames",
"[",
"i",
"]",
"+",
"\"",
" (",
"\"",
"+",
"enumValues",
"[",
"i",
"]",
"+",
"\"",
")",
"\"",
")",
",",
"style",
")",
";",
"if",
"(",
"userPressButton",
")",
"{",
"if",
"(",
"enumValues",
"[",
"i",
"]",
"==",
"0",
")",
"{",
"buttonsIntValue",
"=",
"0",
";",
"property",
".",
"intValue",
"=",
"0",
";",
"}",
"else",
"if",
"(",
"isPowerOfTwo",
")",
"{",
"buttonPressed",
"[",
"i",
"]",
"=",
"userPressButton",
";",
"buttonsIntValue",
"+=",
"enumValues",
"[",
"i",
"]",
";",
"}",
"else",
"{",
"if",
"(",
"!",
"buttonPressed",
"[",
"i",
"]",
")",
"{",
"buttonsIntValue",
"=",
"buttonsIntValue",
"|",
"enumValues",
"[",
"i",
"]",
";",
"}",
"}",
"}",
"else",
"{",
"if",
"(",
"buttonPressed",
"[",
"i",
"]",
")",
"{",
"if",
"(",
"!",
"isPowerOfTwo",
")",
"{",
"buttonsIntValue",
"=",
"buttonsIntValue",
"^",
"enumValues",
"[",
"i",
"]",
";",
"}",
"}",
"}",
"}",
"if",
"(",
"EditorGUI",
".",
"EndChangeCheck",
"(",
")",
")",
"{",
"property",
".",
"intValue",
"=",
"buttonsIntValue",
";",
"}",
"}",
"private",
"static",
"GUIStyle",
"ButtonStyle",
"(",
"int",
"enumLength",
",",
"int",
"i",
")",
"{",
"if",
"(",
"i",
"==",
"0",
")",
"{",
"return",
"EditorStyles",
".",
"miniButtonLeft",
";",
"}",
"else",
"if",
"(",
"i",
"==",
"enumLength",
"-",
"1",
")",
"{",
"return",
"EditorStyles",
".",
"miniButtonRight",
";",
"}",
"else",
"{",
"return",
"EditorStyles",
".",
"miniButtonMid",
";",
"}",
"}",
"}"
] |
Draws a one-line sequence of named buttons, that makes a short enum easy to select.
|
[
"Draws",
"a",
"one",
"-",
"line",
"sequence",
"of",
"named",
"buttons",
"that",
"makes",
"a",
"short",
"enum",
"easy",
"to",
"select",
"."
] |
[
"// Check if the button was pressed. can account for sparse enum values",
"// if not flags, only one button can be on at a time. so if the button was not pressed, but is now, then we change the value. otherwise no change.",
"// we cannot break; because we want to draw the rest of the interface",
"// we use this like in the non-flags version, but we bit operate rather than set value.",
"// Check if the button was pressed ",
"// if is zero, and flags, if button is pressed, no other button can be pressed, and viceversa. clicking it should not do anything if already true.",
"// here we check if value is power of two. then it's just a simple button. but if it's not, then it's a combination of buttons ;)",
"// if not power of two, the button is a combination of other buttons. just check if it is pressed, but don't add stuff directly, but set flags instead.",
"// check if button is pressed",
"// if flags, every button can be on/off independently from each other. so we always set pressed immediately. beware: enum must have consecutive power of two values.",
"// zero was just pressed",
"// not power of two, but button was just made true",
"// button was just made false. it was true before.",
"// XOR makes it opposite hehh, so it will basically flip all the selected flags."
] |
[
{
"param": "PropertyDrawer",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "PropertyDrawer",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 23
| 1,106
| 90
|
8d591751f72a201fbdb421ca7b8d742a4ad8b50b
|
productinfo/maestral-cocoa
|
macOS/Xcode/Maestral/Maestral/app_packages/desktop_notifier/base.py
|
[
"MIT"
] |
Python
|
ReplyField
|
A reply field for interactive notifications
:param title: A title for the field itself. On macOS, this will be the title of a
button to show the field.
:param button_title: The title of the button to send the reply.
:param on_replied: Callback to invoke when the button is pressed. This is called
without any arguments.
|
A reply field for interactive notifications
|
[
"A",
"reply",
"field",
"for",
"interactive",
"notifications"
] |
class ReplyField:
"""
A reply field for interactive notifications
:param title: A title for the field itself. On macOS, this will be the title of a
button to show the field.
:param button_title: The title of the button to send the reply.
:param on_replied: Callback to invoke when the button is pressed. This is called
without any arguments.
"""
def __init__(
self,
title: str = "Reply",
button_title: str = "Send",
on_replied: Optional[Callable[[str], Any]] = None,
) -> None:
self.title = title
self.button_title = button_title
self.on_replied = on_replied
def __repr__(self):
return f"<{self.__class__.__name__}(title='{self.title}', on_replied={self.on_replied})>"
|
[
"class",
"ReplyField",
":",
"def",
"__init__",
"(",
"self",
",",
"title",
":",
"str",
"=",
"\"Reply\"",
",",
"button_title",
":",
"str",
"=",
"\"Send\"",
",",
"on_replied",
":",
"Optional",
"[",
"Callable",
"[",
"[",
"str",
"]",
",",
"Any",
"]",
"]",
"=",
"None",
",",
")",
"->",
"None",
":",
"self",
".",
"title",
"=",
"title",
"self",
".",
"button_title",
"=",
"button_title",
"self",
".",
"on_replied",
"=",
"on_replied",
"def",
"__repr__",
"(",
"self",
")",
":",
"return",
"f\"<{self.__class__.__name__}(title='{self.title}', on_replied={self.on_replied})>\""
] |
A reply field for interactive notifications
|
[
"A",
"reply",
"field",
"for",
"interactive",
"notifications"
] |
[
"\"\"\"\n A reply field for interactive notifications\n\n :param title: A title for the field itself. On macOS, this will be the title of a\n button to show the field.\n :param button_title: The title of the button to send the reply.\n :param on_replied: Callback to invoke when the button is pressed. This is called\n without any arguments.\n \"\"\""
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [
{
"identifier": "title",
"type": null,
"docstring": "A title for the field itself. On macOS, this will be the title of a\nbutton to show the field.",
"docstring_tokens": [
"A",
"title",
"for",
"the",
"field",
"itself",
".",
"On",
"macOS",
"this",
"will",
"be",
"the",
"title",
"of",
"a",
"button",
"to",
"show",
"the",
"field",
"."
],
"default": null,
"is_optional": null
},
{
"identifier": "button_title",
"type": null,
"docstring": "The title of the button to send the reply.",
"docstring_tokens": [
"The",
"title",
"of",
"the",
"button",
"to",
"send",
"the",
"reply",
"."
],
"default": null,
"is_optional": null
},
{
"identifier": "on_replied",
"type": null,
"docstring": "Callback to invoke when the button is pressed. This is called\nwithout any arguments.",
"docstring_tokens": [
"Callback",
"to",
"invoke",
"when",
"the",
"button",
"is",
"pressed",
".",
"This",
"is",
"called",
"without",
"any",
"arguments",
"."
],
"default": null,
"is_optional": null
}
],
"others": []
}
| false
| 14
| 191
| 81
|
7c066d0a82db9855ad502d85ccd16ae589531b64
|
u4pm/angular-archwizard-dist
|
esm2015/lib/components/wizard-navigation-bar.component.js
|
[
"MIT"
] |
JavaScript
|
WizardNavigationBarComponent
|
/**
* The `aw-wizard-navigation-bar` component contains the navigation bar inside a [[WizardComponent]].
* To correctly display the navigation bar, it's required to set the right css classes for the navigation bar,
* otherwise it will look like a normal `ul` component.
*
* ### Syntax
*
* ```html
* <aw-wizard-navigation-bar></aw-wizard-navigation-bar>
* ```
*
* @author Marc Arndt
*/
|
The `aw-wizard-navigation-bar` component contains the navigation bar inside a [[WizardComponent]].
To correctly display the navigation bar, it's required to set the right css classes for the navigation bar,
otherwise it will look like a normal `ul` component.
Syntax
@author Marc Arndt
|
[
"The",
"`",
"aw",
"-",
"wizard",
"-",
"navigation",
"-",
"bar",
"`",
"component",
"contains",
"the",
"navigation",
"bar",
"inside",
"a",
"[[",
"WizardComponent",
"]]",
".",
"To",
"correctly",
"display",
"the",
"navigation",
"bar",
"it",
"'",
"s",
"required",
"to",
"set",
"the",
"right",
"css",
"classes",
"for",
"the",
"navigation",
"bar",
"otherwise",
"it",
"will",
"look",
"like",
"a",
"normal",
"`",
"ul",
"`",
"component",
".",
"Syntax",
"@author",
"Marc",
"Arndt"
] |
class WizardNavigationBarComponent {
/**
* Constructor
*
* @param {?} wizard The state the wizard currently resides in
*/
constructor(wizard) {
this.wizard = wizard;
/**
* The direction in which the wizard steps should be shown in the navigation bar.
* This value can be either `left-to-right` or `right-to-left`
*/
this.direction = 'left-to-right';
}
/**
* Returns all [[WizardStep]]s contained in the wizard
*
* @return {?} An array containing all [[WizardStep]]s
*/
get wizardSteps() {
switch (this.direction) {
case 'right-to-left':
return this.wizard.wizardSteps.slice().reverse();
case 'left-to-right':
default:
return this.wizard.wizardSteps;
}
}
/**
* Returns the number of wizard steps, that need to be displaced in the navigation bar
*
* @return {?} The number of wizard steps to be displayed
*/
get numberOfWizardSteps() {
return this.wizard.wizardSteps.length;
}
/**
* Checks, whether a [[WizardStep]] can be marked as `current` in the navigation bar
*
* @param {?} wizardStep The wizard step to be checked
* @return {?} True if the step can be marked as `current`
*/
isCurrent(wizardStep) {
return wizardStep.selected;
}
/**
* Checks, whether a [[WizardStep]] can be marked as `editing` in the navigation bar
*
* @param {?} wizardStep The wizard step to be checked
* @return {?} True if the step can be marked as `editing`
*/
isEditing(wizardStep) {
return wizardStep.editing;
}
/**
* Checks, whether a [[WizardStep]] can be marked as `done` in the navigation bar
*
* @param {?} wizardStep The wizard step to be checked
* @return {?} True if the step can be marked as `done`
*/
isDone(wizardStep) {
return wizardStep.completed;
}
/**
* Checks, whether a [[WizardStep]] can be marked as `optional` in the navigation bar
*
* @param {?} wizardStep The wizard step to be checked
* @return {?} True if the step can be marked as `optional`
*/
isOptional(wizardStep) {
return wizardStep.optional;
}
/**
* Checks, whether a [[WizardStep]] can be marked as `completed` in the navigation bar.
*
* The `completed` class is only applied to completion steps.
*
* @param {?} wizardStep The wizard step to be checked
* @return {?} True if the step can be marked as `completed`
*/
isCompleted(wizardStep) {
return wizardStep instanceof WizardCompletionStep && this.wizard.completed;
}
/**
* Checks, whether a [[WizardStep]] can be marked as `navigable` in the navigation bar.
* A wizard step can be navigated to if:
* - the step is currently not selected
* - the navigation bar isn't disabled
* - the navigation mode allows navigation to the step
*
* @param {?} wizardStep The wizard step to be checked
* @return {?} True if the step can be marked as navigable
*/
isNavigable(wizardStep) {
return !wizardStep.selected && !this.wizard.disableNavigationBar &&
this.wizard.isNavigable(this.wizard.getIndexOfStep(wizardStep));
}
}
|
[
"class",
"WizardNavigationBarComponent",
"{",
"constructor",
"(",
"wizard",
")",
"{",
"this",
".",
"wizard",
"=",
"wizard",
";",
"this",
".",
"direction",
"=",
"'left-to-right'",
";",
"}",
"get",
"wizardSteps",
"(",
")",
"{",
"switch",
"(",
"this",
".",
"direction",
")",
"{",
"case",
"'right-to-left'",
":",
"return",
"this",
".",
"wizard",
".",
"wizardSteps",
".",
"slice",
"(",
")",
".",
"reverse",
"(",
")",
";",
"case",
"'left-to-right'",
":",
"default",
":",
"return",
"this",
".",
"wizard",
".",
"wizardSteps",
";",
"}",
"}",
"get",
"numberOfWizardSteps",
"(",
")",
"{",
"return",
"this",
".",
"wizard",
".",
"wizardSteps",
".",
"length",
";",
"}",
"isCurrent",
"(",
"wizardStep",
")",
"{",
"return",
"wizardStep",
".",
"selected",
";",
"}",
"isEditing",
"(",
"wizardStep",
")",
"{",
"return",
"wizardStep",
".",
"editing",
";",
"}",
"isDone",
"(",
"wizardStep",
")",
"{",
"return",
"wizardStep",
".",
"completed",
";",
"}",
"isOptional",
"(",
"wizardStep",
")",
"{",
"return",
"wizardStep",
".",
"optional",
";",
"}",
"isCompleted",
"(",
"wizardStep",
")",
"{",
"return",
"wizardStep",
"instanceof",
"WizardCompletionStep",
"&&",
"this",
".",
"wizard",
".",
"completed",
";",
"}",
"isNavigable",
"(",
"wizardStep",
")",
"{",
"return",
"!",
"wizardStep",
".",
"selected",
"&&",
"!",
"this",
".",
"wizard",
".",
"disableNavigationBar",
"&&",
"this",
".",
"wizard",
".",
"isNavigable",
"(",
"this",
".",
"wizard",
".",
"getIndexOfStep",
"(",
"wizardStep",
")",
")",
";",
"}",
"}"
] |
The `aw-wizard-navigation-bar` component contains the navigation bar inside a [[WizardComponent]].
|
[
"The",
"`",
"aw",
"-",
"wizard",
"-",
"navigation",
"-",
"bar",
"`",
"component",
"contains",
"the",
"navigation",
"bar",
"inside",
"a",
"[[",
"WizardComponent",
"]]",
"."
] |
[
"/**\n * Constructor\n *\n * @param {?} wizard The state the wizard currently resides in\n */",
"/**\n * The direction in which the wizard steps should be shown in the navigation bar.\n * This value can be either `left-to-right` or `right-to-left`\n */",
"/**\n * Returns all [[WizardStep]]s contained in the wizard\n *\n * @return {?} An array containing all [[WizardStep]]s\n */",
"/**\n * Returns the number of wizard steps, that need to be displaced in the navigation bar\n *\n * @return {?} The number of wizard steps to be displayed\n */",
"/**\n * Checks, whether a [[WizardStep]] can be marked as `current` in the navigation bar\n *\n * @param {?} wizardStep The wizard step to be checked\n * @return {?} True if the step can be marked as `current`\n */",
"/**\n * Checks, whether a [[WizardStep]] can be marked as `editing` in the navigation bar\n *\n * @param {?} wizardStep The wizard step to be checked\n * @return {?} True if the step can be marked as `editing`\n */",
"/**\n * Checks, whether a [[WizardStep]] can be marked as `done` in the navigation bar\n *\n * @param {?} wizardStep The wizard step to be checked\n * @return {?} True if the step can be marked as `done`\n */",
"/**\n * Checks, whether a [[WizardStep]] can be marked as `optional` in the navigation bar\n *\n * @param {?} wizardStep The wizard step to be checked\n * @return {?} True if the step can be marked as `optional`\n */",
"/**\n * Checks, whether a [[WizardStep]] can be marked as `completed` in the navigation bar.\n *\n * The `completed` class is only applied to completion steps.\n *\n * @param {?} wizardStep The wizard step to be checked\n * @return {?} True if the step can be marked as `completed`\n */",
"/**\n * Checks, whether a [[WizardStep]] can be marked as `navigable` in the navigation bar.\n * A wizard step can be navigated to if:\n * - the step is currently not selected\n * - the navigation bar isn't disabled\n * - the navigation mode allows navigation to the step\n *\n * @param {?} wizardStep The wizard step to be checked\n * @return {?} True if the step can be marked as navigable\n */"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 15
| 782
| 93
|
5dcc88983fb34760a0d01102bfce07ce1402b245
|
RoUS/rubygem-fto
|
lib/fto.rb
|
[
"Apache-2.0"
] |
Ruby
|
FTO
|
#
# = Description
#
# The _FTO_ class is the user interface; all others are for
# developers modifying or extending the +fto+ library.
#
# _FTO_ is a subclass of _String_, so all _String_ methods work on
# an _FTO_ object. _FTO_ provides the additional <i>format()</i>
# method.
#
# In addition to string text, the constructor (<i>FormatText::FTO.new</i>) can
# take more than a single argument. Additional arguments will be
# stored as part of the object and will be available to the
# <i>FormatText::FTO#format()</i> method at runtime.
#
# An _FTO_ object can be created as just a formatting string, or the
# constructor invocation can also include values to be applied by
# the <i>FormatText::FTO#format()</i> method. At runtime the
# <i>format()</i> method can override any argument list provided
# at instantiation, but the latter is not lost.
#
|
Description
The _FTO_ class is the user interface; all others are for
developers modifying or extending the +fto+ library.
_FTO_ is a subclass of _String_, so all _String_ methods work on
an _FTO_ object. _FTO_ provides the additional format()
method.
In addition to string text, the constructor (FormatText::FTO.new) can
take more than a single argument. Additional arguments will be
stored as part of the object and will be available to the
FormatText::FTO#format() method at runtime.
An _FTO_ object can be created as just a formatting string, or the
constructor invocation can also include values to be applied by
the FormatText::FTO#format() method. At runtime the
format() method can override any argument list provided
at instantiation, but the latter is not lost.
|
[
"Description",
"The",
"_FTO_",
"class",
"is",
"the",
"user",
"interface",
";",
"all",
"others",
"are",
"for",
"developers",
"modifying",
"or",
"extending",
"the",
"+",
"fto",
"+",
"library",
".",
"_FTO_",
"is",
"a",
"subclass",
"of",
"_String_",
"so",
"all",
"_String_",
"methods",
"work",
"on",
"an",
"_FTO_",
"object",
".",
"_FTO_",
"provides",
"the",
"additional",
"format",
"()",
"method",
".",
"In",
"addition",
"to",
"string",
"text",
"the",
"constructor",
"(",
"FormatText",
"::",
"FTO",
".",
"new",
")",
"can",
"take",
"more",
"than",
"a",
"single",
"argument",
".",
"Additional",
"arguments",
"will",
"be",
"stored",
"as",
"part",
"of",
"the",
"object",
"and",
"will",
"be",
"available",
"to",
"the",
"FormatText",
"::",
"FTO#format",
"()",
"method",
"at",
"runtime",
".",
"An",
"_FTO_",
"object",
"can",
"be",
"created",
"as",
"just",
"a",
"formatting",
"string",
"or",
"the",
"constructor",
"invocation",
"can",
"also",
"include",
"values",
"to",
"be",
"applied",
"by",
"the",
"FormatText",
"::",
"FTO#format",
"()",
"method",
".",
"At",
"runtime",
"the",
"format",
"()",
"method",
"can",
"override",
"any",
"argument",
"list",
"provided",
"at",
"instantiation",
"but",
"the",
"latter",
"is",
"not",
"lost",
"."
] |
class FTO < String
#
# Class variables
#
# None.
#
#
# Constants
#
#
# Hash of all registered effector objects, keyed by their IDs.
#
@@RegisteredEffectors = {} unless (defined?(@@RegisteredEffectors))
#
# Hash of all currently enabled effectors, keyed by their sort
# key.
#
@@EnabledEffectors = {} unless (defined?(@@EnabledEffectors))
#
# Ordered array of effector keys (used to index
# @@EnabledEffectors)
#
@@EffectorKeys = [] unless (defined?(@@EffectorKeys))
#
# Not yet implemented
# Controls whether the final string is built safely and
# conservatively, or if the output of each effector can alter the
# input to subsequent ones.
#
attr_accessor :safe
# :stopdoc:
#
# We do this in order to call super on String, but since our
# argument list is different, we need to finesse it a little.
# Nobody's business but ours.
#
alias_method(:String_initialize, :initialize) # :nodoc:
# :startdoc:
#
# Debugging class method to access list of registered effectors
#
def self.effectors() # :nodoc:
@@RegisteredEffectors
end # def self.effectors()
#
# Debugging class method to access list of effector keys.
#
def self.eKeys() # :nodoc:
@@EffectorKeys
end # def self.eKeys()
#
# Debugging class method to access regular expression used to find
# effectors.
#
def self.regex() # :nodoc:
@@regex
end # def self.regex()
#
# === Description
# Any argument list is supplied at object instantiation can be
# temporarily overridden when the <i>FormatText::FTO#format()</i> method is
# invoked.
#
# :call-seq:
# new<i>()</i> => <i>FormatText::FTO</i>
# new<i>(fmtString)</i> => <i>FormatText::FTO</i>
# new<i>(fmtString, arg [, ...])</i> => <i>FormatText::FTO</i>
#
# === Arguments
# [<i>fmtString</i>] <i>String</i>. The actual format string containing the effectors.
# [<i>arg</i>] <i>Any</i>. Optional list of one or more arguments to use when applying the effectors.
#
def initialize(text=nil, *args)
String_initialize(text)
@safe = true
@args = args
end # def initialize
#
# === Description
# Remove and destroy all effectors from the list of those registered
# (as a prelude to using a different syntax, for instance).
# <b>THIS IS NOT REVERSIBLE!</b>
#
# :call-seq:
# FTO.clearEffectorList<i>()</i> => <tt>nil</tt>
#
def self.clearEffectorList()
@@RegisteredEffectors.delete_if { |id,e| true }
self.rebuildEffectorList()
nil
end # def self.clearEffectorList()
#
# === Description
# Add an effector description to the list of those which will be
# processed by the <i>FormatText::FTO#format()</i> method.
#
# :call-seq:
# FTO.registerEffector<i>(effectorObj)</i> => <tt>nil</tt>
# FTO.registerEffector<i>(sHash)</i> => <tt>nil</tt>
#
# === Arguments
# [<i>effectorObj</i>] <i>FormatText::Effector</i>. Registers an effector tha has already been created.
# [<i>sHash</i>] <i>Hash</i>. A hash with symbolic keys corresponding to the attributes of the <i>FormatText::Effector</i> class.
#
def self.registerEffector(*args)
if ((args.length == 1) && (args[0].class.name.match(/Effector$/)))
newE = args[0]
else
newE = Effector.new('placeholder')
if ((args.length == 1) && (args[0].class == Hash))
args[0].each do |key,val|
eval("newE.#{key.to_s} = val")
end
else
newE = Effector.new(args)
end
end
key = sprintf('%06d-%s', newE.priority, newE.name)
newE.sortKey = key
@@RegisteredEffectors[newE.id] = newE
self.rebuildEffectorList()
nil
end # def self.registerEffector()
# :stopdoc:
#
# This class method rebuilds the regular expression and the hash
# of enabled effectors. It needs to be invoked any time an
# effector is added, destroyed, enabled, or disabled. It's for
# internal use only.
#
def self.rebuildEffectorList()
enabled = @@RegisteredEffectors.select { |id,e| e.enabled? }
@@EffectorKeys = []
@@EffectorKeys = enabled.collect { |k,e| e.sortKey }.sort
@@EffectorKeys.freeze
@@EnabledEffectors = {}
enabled.each { |k,e| @@EnabledEffectors[e.sortKey] = e }
@@EnabledEffectors.freeze
@@regex = Regexp.new("(#{@@EffectorKeys.collect {|k| @@EnabledEffectors[k].reMatch}.join(')|(')})")
@@regex.freeze
nil
end # def self.rebuildEffectorList()
# :startdoc:
#
# === Description
# Enables the effector with the specified ID (found in the
# effector's <i>id</i> attribute). This is a no-op if the effector is
# already enabled.
#
# :call-seq:
# FTO.enableEffector<i>(eid)</i> => <tt>nil</tt>
#
# === Arguments
# [<i>eid</i>] ID value of the effector to enable (from its <i>id</i> attribute).
#
# === Exceptions
# [<tt>RuntimeError</tt>] If there is no registered effector with the specified ID.
#
def self.enableEffector(id)
if ((e = @@RegisteredEffectors[id]).nil?)
raise RuntimeError, _('No such effector ') + "ID\##{id}"
end
e.enabled = true
self.rebuildEffectorList()
end # def self.enableEffector()
#
# === Description
# Completely removes the effector with the specified ID from the
# FTO system. <b>THIS IS NOT REVERSIBLE!</b>
#
# :call-seq:
# FTO.destroyEffector<i>(eid)</i> => <tt>nil</tt>
#
# === Arguments
# [<i>eid</i>] The value of the <i>id</i> attribute of the effector to destroy.
#
def self.destroyEffector(id)
@@RegisteredEffectors.delete(id)
self.rebuildEffectorList()
end # def self.destroyEffector()
#
# === Description
# Disables the effector with the specified ID (such as from
# <i>FormatText::FTO.findEffectors()</i>). This is a no-op
# if the effector is already disabled.
#
# :call-seq:
# FTO.disableEffector<i>(eid)</i> => <tt>nil</tt>
#
# === Arguments
# [<i>eid</i>] ID value of the effector to disable (from its <i>id</i> attribute).
#
# === Exceptions
# [<tt>RuntimeError</tt>] If there is no registered effector with the specified ID.
#
def self.disableEffector(id)
if ((e = @@RegisteredEffectors[id]).nil?)
raise RuntimeError, _('No such effector ') + "ID\##{id}"
end
e.disable
nil
end # def self.disableEffector()
#
# === Description
# Returns an array of registered effectors whose names (_name_
# attribute) match the specified pattern.
#
# :call-seq:
# FTO.findEffectors<i>(sPatt)</i> => <i>Array</i>
#
# === Arguments
# [<i>sPatt</i>] <i>String</i> or <i>Regexp</i>. If called with a string as its argument, the method will create a <i>Regexp</i> object from it. Creating the <i>Regexp</i> yourself allows you greater control, such as setting case-sensitivity for the match.
#
def self.findEffectors(pattern)
pattern = Regexp.new(pattern) unless (pattern.class == Regexp)
matches = @@RegisteredEffectors.select { |id,e| e.name.match(pattern) }
matches.collect { |id,e| e }
end # def self.findEffector()
#
# === Description
# Process the formatting string, optionally with a runtime
# argument list. The argument list can either be a list of
# values, an array of values, or a <i>FormatText::Context</i>
# object. (The latter is intended only for internal use with
# recursion.)
#
# :call-seq:
# format<i>()</i> => <i>String</i>
# format<i>(arg [, ...])</i> => <i>String</i>
# format<i>(Array)</i> => <i>String</i>
# format<i>(FormatText::Context)</i> => <i>String</i> (<u>internal use only</u>)
#
# === Arguments
# [none] If called with no arguments, any arglist specified at object creation (see the <i>FormatText::FTO.new()</i> method description) will be used.
# [list of arguments] Any list of arguments will completely override any list specified at object creation time.
# [<i>Array</i>] Rather than specifying a list of discrete arguments, you can pass a single array containing them instead. This is useful for argument lists constructed at run-time.
# [<i>FormatText::Context</i>] This is reserved for internal use during recursive operations.
#
def format(*argListp)
argList = argListp.empty? ? @args.clone : argListp
if ((argList.length == 1) && (argList[0].class == Array)) &&
argList = argList[0]
end
#
# It's possible we were passed a Context object so we can
# recurse. If so, use its values for some of these.
#
if ((argList.length == 1) && (argList[0].class == FormatText::Context))
eContext = argList[0]
usedArgs = eContext.usedArgs
argList = eContext.argList
else
usedArgs = []
eContext = Context.new({
:ftoObj => self,
:usedArgs => usedArgs,
:argList => argList
})
end
input = self.to_s
output = input.clone
effector = sMatched = nil
while (m = input.match(@@regex))
#
# Find out which effector was matched. The index in .captures
# will be the same as the index in @effectors.
#
m.captures.length.times do |i|
next if (m.captures[i].nil?)
eContext.effectorObj = effector = @@EnabledEffectors[@@EffectorKeys[i]]
eContext.sMatched = sMatched = m.captures[i]
eContext.reuseArg = false
break
end
#
# Call the workhorse for this descriptor
#
replacement = effector.code.call(eContext)
output.sub!(sMatched, replacement)
input.sub!(sMatched, '')
#
# Mark the item at the front of the argument list as having
# been used, if the effector agrees. Assume that an argument
# was actually used if we're moving it, and that the 'last
# argument used' hasn't changed if the effector has set
# _reuseArg_.
#
unless (eContext.reuseArg)
eContext.shiftArgument(1)
eContext.lastArgUsed = usedArgs.last
end
end
output
end # def format()
end
|
[
"class",
"FTO",
"<",
"String",
"@@RegisteredEffectors",
"=",
"{",
"}",
"unless",
"(",
"defined?",
"(",
"@@RegisteredEffectors",
")",
")",
"@@EnabledEffectors",
"=",
"{",
"}",
"unless",
"(",
"defined?",
"(",
"@@EnabledEffectors",
")",
")",
"@@EffectorKeys",
"=",
"[",
"]",
"unless",
"(",
"defined?",
"(",
"@@EffectorKeys",
")",
")",
"attr_accessor",
":safe",
"alias_method",
"(",
":String_initialize",
",",
":initialize",
")",
"def",
"self",
".",
"effectors",
"(",
")",
"@@RegisteredEffectors",
"end",
"def",
"self",
".",
"eKeys",
"(",
")",
"@@EffectorKeys",
"end",
"def",
"self",
".",
"regex",
"(",
")",
"@@regex",
"end",
"def",
"initialize",
"(",
"text",
"=",
"nil",
",",
"*",
"args",
")",
"String_initialize",
"(",
"text",
")",
"@safe",
"=",
"true",
"@args",
"=",
"args",
"end",
"def",
"self",
".",
"clearEffectorList",
"(",
")",
"@@RegisteredEffectors",
".",
"delete_if",
"{",
"|",
"id",
",",
"e",
"|",
"true",
"}",
"self",
".",
"rebuildEffectorList",
"(",
")",
"nil",
"end",
"def",
"self",
".",
"registerEffector",
"(",
"*",
"args",
")",
"if",
"(",
"(",
"args",
".",
"length",
"==",
"1",
")",
"&&",
"(",
"args",
"[",
"0",
"]",
".",
"class",
".",
"name",
".",
"match",
"(",
"/",
"Effector$",
"/",
")",
")",
")",
"newE",
"=",
"args",
"[",
"0",
"]",
"else",
"newE",
"=",
"Effector",
".",
"new",
"(",
"'placeholder'",
")",
"if",
"(",
"(",
"args",
".",
"length",
"==",
"1",
")",
"&&",
"(",
"args",
"[",
"0",
"]",
".",
"class",
"==",
"Hash",
")",
")",
"args",
"[",
"0",
"]",
".",
"each",
"do",
"|",
"key",
",",
"val",
"|",
"eval",
"(",
"\"newE.#{key.to_s} = val\"",
")",
"end",
"else",
"newE",
"=",
"Effector",
".",
"new",
"(",
"args",
")",
"end",
"end",
"key",
"=",
"sprintf",
"(",
"'%06d-%s'",
",",
"newE",
".",
"priority",
",",
"newE",
".",
"name",
")",
"newE",
".",
"sortKey",
"=",
"key",
"@@RegisteredEffectors",
"[",
"newE",
".",
"id",
"]",
"=",
"newE",
"self",
".",
"rebuildEffectorList",
"(",
")",
"nil",
"end",
"def",
"self",
".",
"rebuildEffectorList",
"(",
")",
"enabled",
"=",
"@@RegisteredEffectors",
".",
"select",
"{",
"|",
"id",
",",
"e",
"|",
"e",
".",
"enabled?",
"}",
"@@EffectorKeys",
"=",
"[",
"]",
"@@EffectorKeys",
"=",
"enabled",
".",
"collect",
"{",
"|",
"k",
",",
"e",
"|",
"e",
".",
"sortKey",
"}",
".",
"sort",
"@@EffectorKeys",
".",
"freeze",
"@@EnabledEffectors",
"=",
"{",
"}",
"enabled",
".",
"each",
"{",
"|",
"k",
",",
"e",
"|",
"@@EnabledEffectors",
"[",
"e",
".",
"sortKey",
"]",
"=",
"e",
"}",
"@@EnabledEffectors",
".",
"freeze",
"@@regex",
"=",
"Regexp",
".",
"new",
"(",
"\"(#{@@EffectorKeys.collect {|k| @@EnabledEffectors[k].reMatch}.join(')|(')})\"",
")",
"@@regex",
".",
"freeze",
"nil",
"end",
"def",
"self",
".",
"enableEffector",
"(",
"id",
")",
"if",
"(",
"(",
"e",
"=",
"@@RegisteredEffectors",
"[",
"id",
"]",
")",
".",
"nil?",
")",
"raise",
"RuntimeError",
",",
"_",
"(",
"'No such effector '",
")",
"+",
"\"ID\\##{id}\"",
"end",
"e",
".",
"enabled",
"=",
"true",
"self",
".",
"rebuildEffectorList",
"(",
")",
"end",
"def",
"self",
".",
"destroyEffector",
"(",
"id",
")",
"@@RegisteredEffectors",
".",
"delete",
"(",
"id",
")",
"self",
".",
"rebuildEffectorList",
"(",
")",
"end",
"def",
"self",
".",
"disableEffector",
"(",
"id",
")",
"if",
"(",
"(",
"e",
"=",
"@@RegisteredEffectors",
"[",
"id",
"]",
")",
".",
"nil?",
")",
"raise",
"RuntimeError",
",",
"_",
"(",
"'No such effector '",
")",
"+",
"\"ID\\##{id}\"",
"end",
"e",
".",
"disable",
"nil",
"end",
"def",
"self",
".",
"findEffectors",
"(",
"pattern",
")",
"pattern",
"=",
"Regexp",
".",
"new",
"(",
"pattern",
")",
"unless",
"(",
"pattern",
".",
"class",
"==",
"Regexp",
")",
"matches",
"=",
"@@RegisteredEffectors",
".",
"select",
"{",
"|",
"id",
",",
"e",
"|",
"e",
".",
"name",
".",
"match",
"(",
"pattern",
")",
"}",
"matches",
".",
"collect",
"{",
"|",
"id",
",",
"e",
"|",
"e",
"}",
"end",
"def",
"format",
"(",
"*",
"argListp",
")",
"argList",
"=",
"argListp",
".",
"empty?",
"?",
"@args",
".",
"clone",
":",
"argListp",
"if",
"(",
"(",
"argList",
".",
"length",
"==",
"1",
")",
"&&",
"(",
"argList",
"[",
"0",
"]",
".",
"class",
"==",
"Array",
")",
")",
"&&",
"argList",
"=",
"argList",
"[",
"0",
"]",
"end",
"if",
"(",
"(",
"argList",
".",
"length",
"==",
"1",
")",
"&&",
"(",
"argList",
"[",
"0",
"]",
".",
"class",
"==",
"FormatText",
"::",
"Context",
")",
")",
"eContext",
"=",
"argList",
"[",
"0",
"]",
"usedArgs",
"=",
"eContext",
".",
"usedArgs",
"argList",
"=",
"eContext",
".",
"argList",
"else",
"usedArgs",
"=",
"[",
"]",
"eContext",
"=",
"Context",
".",
"new",
"(",
"{",
":ftoObj",
"=>",
"self",
",",
":usedArgs",
"=>",
"usedArgs",
",",
":argList",
"=>",
"argList",
"}",
")",
"end",
"input",
"=",
"self",
".",
"to_s",
"output",
"=",
"input",
".",
"clone",
"effector",
"=",
"sMatched",
"=",
"nil",
"while",
"(",
"m",
"=",
"input",
".",
"match",
"(",
"@@regex",
")",
")",
"m",
".",
"captures",
".",
"length",
".",
"times",
"do",
"|",
"i",
"|",
"next",
"if",
"(",
"m",
".",
"captures",
"[",
"i",
"]",
".",
"nil?",
")",
"eContext",
".",
"effectorObj",
"=",
"effector",
"=",
"@@EnabledEffectors",
"[",
"@@EffectorKeys",
"[",
"i",
"]",
"]",
"eContext",
".",
"sMatched",
"=",
"sMatched",
"=",
"m",
".",
"captures",
"[",
"i",
"]",
"eContext",
".",
"reuseArg",
"=",
"false",
"break",
"end",
"replacement",
"=",
"effector",
".",
"code",
".",
"call",
"(",
"eContext",
")",
"output",
".",
"sub!",
"(",
"sMatched",
",",
"replacement",
")",
"input",
".",
"sub!",
"(",
"sMatched",
",",
"''",
")",
"unless",
"(",
"eContext",
".",
"reuseArg",
")",
"eContext",
".",
"shiftArgument",
"(",
"1",
")",
"eContext",
".",
"lastArgUsed",
"=",
"usedArgs",
".",
"last",
"end",
"end",
"output",
"end",
"end"
] |
Description
The _FTO_ class is the user interface; all others are for
developers modifying or extending the +fto+ library.
|
[
"Description",
"The",
"_FTO_",
"class",
"is",
"the",
"user",
"interface",
";",
"all",
"others",
"are",
"for",
"developers",
"modifying",
"or",
"extending",
"the",
"+",
"fto",
"+",
"library",
"."
] |
[
"#",
"# Class variables",
"#",
"# None.",
"#",
"#",
"# Constants",
"#",
"#",
"# Hash of all registered effector objects, keyed by their IDs.",
"#",
"#",
"# Hash of all currently enabled effectors, keyed by their sort",
"# key.",
"#",
"#",
"# Ordered array of effector keys (used to index",
"# @@EnabledEffectors)",
"#",
"#",
"# Not yet implemented",
"# Controls whether the final string is built safely and",
"# conservatively, or if the output of each effector can alter the",
"# input to subsequent ones.",
"#",
"# :stopdoc:",
"#",
"# We do this in order to call super on String, but since our",
"# argument list is different, we need to finesse it a little.",
"# Nobody's business but ours.",
"#",
"# :nodoc:",
"# :startdoc:",
"#",
"# Debugging class method to access list of registered effectors",
"#",
"# :nodoc:",
"# def self.effectors()",
"#",
"# Debugging class method to access list of effector keys.",
"#",
"# :nodoc:",
"# def self.eKeys()",
"#",
"# Debugging class method to access regular expression used to find",
"# effectors.",
"#",
"# :nodoc:",
"# def self.regex()",
"#",
"# === Description",
"# Any argument list is supplied at object instantiation can be",
"# temporarily overridden when the <i>FormatText::FTO#format()</i> method is",
"# invoked.",
"#",
"# :call-seq:",
"# new<i>()</i> => <i>FormatText::FTO</i>",
"# new<i>(fmtString)</i> => <i>FormatText::FTO</i>",
"# new<i>(fmtString, arg [, ...])</i> => <i>FormatText::FTO</i>",
"#",
"# === Arguments",
"# [<i>fmtString</i>] <i>String</i>. The actual format string containing the effectors.",
"# [<i>arg</i>] <i>Any</i>. Optional list of one or more arguments to use when applying the effectors.",
"#",
"# def initialize",
"#",
"# === Description",
"# Remove and destroy all effectors from the list of those registered",
"# (as a prelude to using a different syntax, for instance).",
"# <b>THIS IS NOT REVERSIBLE!</b>",
"#",
"# :call-seq:",
"# FTO.clearEffectorList<i>()</i> => <tt>nil</tt>",
"#",
"# def self.clearEffectorList()",
"#",
"# === Description",
"# Add an effector description to the list of those which will be",
"# processed by the <i>FormatText::FTO#format()</i> method.",
"#",
"# :call-seq:",
"# FTO.registerEffector<i>(effectorObj)</i> => <tt>nil</tt>",
"# FTO.registerEffector<i>(sHash)</i> => <tt>nil</tt>",
"#",
"# === Arguments",
"# [<i>effectorObj</i>] <i>FormatText::Effector</i>. Registers an effector tha has already been created.",
"# [<i>sHash</i>] <i>Hash</i>. A hash with symbolic keys corresponding to the attributes of the <i>FormatText::Effector</i> class.",
"#",
"# def self.registerEffector()",
"# :stopdoc:",
"#",
"# This class method rebuilds the regular expression and the hash",
"# of enabled effectors. It needs to be invoked any time an",
"# effector is added, destroyed, enabled, or disabled. It's for",
"# internal use only.",
"#",
"# def self.rebuildEffectorList()",
"# :startdoc:",
"#",
"# === Description",
"# Enables the effector with the specified ID (found in the",
"# effector's <i>id</i> attribute). This is a no-op if the effector is",
"# already enabled.",
"#",
"# :call-seq:",
"# FTO.enableEffector<i>(eid)</i> => <tt>nil</tt>",
"#",
"# === Arguments",
"# [<i>eid</i>] ID value of the effector to enable (from its <i>id</i> attribute).",
"#",
"# === Exceptions",
"# [<tt>RuntimeError</tt>] If there is no registered effector with the specified ID.",
"#",
"# def self.enableEffector()",
"#",
"# === Description",
"# Completely removes the effector with the specified ID from the",
"# FTO system. <b>THIS IS NOT REVERSIBLE!</b>",
"#",
"# :call-seq:",
"# FTO.destroyEffector<i>(eid)</i> => <tt>nil</tt>",
"#",
"# === Arguments",
"# [<i>eid</i>] The value of the <i>id</i> attribute of the effector to destroy.",
"#",
"# def self.destroyEffector()",
"#",
"# === Description",
"# Disables the effector with the specified ID (such as from",
"# <i>FormatText::FTO.findEffectors()</i>). This is a no-op",
"# if the effector is already disabled.",
"#",
"# :call-seq:",
"# FTO.disableEffector<i>(eid)</i> => <tt>nil</tt>",
"#",
"# === Arguments",
"# [<i>eid</i>] ID value of the effector to disable (from its <i>id</i> attribute).",
"#",
"# === Exceptions",
"# [<tt>RuntimeError</tt>] If there is no registered effector with the specified ID.",
"#",
"# def self.disableEffector()",
"#",
"# === Description",
"# Returns an array of registered effectors whose names (_name_",
"# attribute) match the specified pattern.",
"#",
"# :call-seq:",
"# FTO.findEffectors<i>(sPatt)</i> => <i>Array</i>",
"#",
"# === Arguments",
"# [<i>sPatt</i>] <i>String</i> or <i>Regexp</i>. If called with a string as its argument, the method will create a <i>Regexp</i> object from it. Creating the <i>Regexp</i> yourself allows you greater control, such as setting case-sensitivity for the match.",
"#",
"# def self.findEffector()",
"#",
"# === Description",
"# Process the formatting string, optionally with a runtime",
"# argument list. The argument list can either be a list of",
"# values, an array of values, or a <i>FormatText::Context</i>",
"# object. (The latter is intended only for internal use with",
"# recursion.)",
"#",
"# :call-seq:",
"# format<i>()</i> => <i>String</i>",
"# format<i>(arg [, ...])</i> => <i>String</i>",
"# format<i>(Array)</i> => <i>String</i>",
"# format<i>(FormatText::Context)</i> => <i>String</i> (<u>internal use only</u>)",
"#",
"# === Arguments",
"# [none] If called with no arguments, any arglist specified at object creation (see the <i>FormatText::FTO.new()</i> method description) will be used.",
"# [list of arguments] Any list of arguments will completely override any list specified at object creation time.",
"# [<i>Array</i>] Rather than specifying a list of discrete arguments, you can pass a single array containing them instead. This is useful for argument lists constructed at run-time.",
"# [<i>FormatText::Context</i>] This is reserved for internal use during recursive operations.",
"#",
"#",
"# It's possible we were passed a Context object so we can",
"# recurse. If so, use its values for some of these.",
"#",
"#",
"# Find out which effector was matched. The index in .captures",
"# will be the same as the index in @effectors.",
"#",
"#",
"# Call the workhorse for this descriptor",
"#",
"#",
"# Mark the item at the front of the argument list as having",
"# been used, if the effector agrees. Assume that an argument",
"# was actually used if we're moving it, and that the 'last",
"# argument used' hasn't changed if the effector has set",
"# _reuseArg_.",
"#",
"# def format()"
] |
[
{
"param": "String",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "String",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 17
| 2,918
| 235
|
20afdeec035dd10ef47e45e5f3d1ea3ed3632dbd
|
rin6321910/Github-GameOff-2021
|
Assets/Plugins/Pixel Crushers/Dialogue System/Scripts/MVC/Sequencer/Commands/SequencerCommandZoom2D.cs
|
[
"MIT"
] |
C#
|
SequencerCommandZoom2D
|
/// <summary>
/// Implements sequencer command: Zoom2D([gameobject|speaker|listener[, size[, duration]]])
///
/// Arguments:
/// -# subject:(Optional) The subject; can be speaker, listener, or the name of a game object. Default:
/// speaker.
/// -# size: (Optional) The orthographic camera size to zoom to.
/// -# duration: (Optional) Duration over which to move the camera. Default: immediate.
/// </summary>
|
Implements sequencer command: Zoom2D([gameobject|speaker|listener[, size[, duration]]])
# subject:(Optional) The subject; can be speaker, listener, or the name of a game object. Default:
speaker.
# size: (Optional) The orthographic camera size to zoom to.
# duration: (Optional) Duration over which to move the camera. Default: immediate.
|
[
"Implements",
"sequencer",
"command",
":",
"Zoom2D",
"(",
"[",
"gameobject|speaker|listener",
"[",
"size",
"[",
"duration",
"]]]",
")",
"#",
"subject",
":",
"(",
"Optional",
")",
"The",
"subject",
";",
"can",
"be",
"speaker",
"listener",
"or",
"the",
"name",
"of",
"a",
"game",
"object",
".",
"Default",
":",
"speaker",
".",
"#",
"size",
":",
"(",
"Optional",
")",
"The",
"orthographic",
"camera",
"size",
"to",
"zoom",
"to",
".",
"#",
"duration",
":",
"(",
"Optional",
")",
"Duration",
"over",
"which",
"to",
"move",
"the",
"camera",
".",
"Default",
":",
"immediate",
"."
] |
[AddComponentMenu("")]
public class SequencerCommandZoom2D : SequencerCommand
{
private const float SmoothMoveCutoff = 0.05f;
private bool original;
private Transform subject;
private Vector3 targetPosition;
private Vector3 originalPosition;
private float targetSize;
private float originalSize;
private float duration;
private float startTime;
private float endTime;
public void Start()
{
original = string.Equals(GetParameter(0), "original");
subject = original ? null : GetSubject(0);
targetSize = GetParameterAsFloat(1, 16);
duration = GetParameterAsFloat(2, 0);
if (DialogueDebug.logInfo)
{
if (original)
{
Debug.Log(string.Format("{0}: Sequencer: Zoom2D(original, -, {1}s)", new System.Object[] { DialogueDebug.Prefix, duration }));
}
else
{
Debug.Log(string.Format("{0}: Sequencer: Zoom2D({1}, {2}, {3}s)", new System.Object[] { DialogueDebug.Prefix, Tools.GetGameObjectName(subject), targetSize, duration }));
}
}
if ((subject == null && !original) && DialogueDebug.logWarnings)
{
Debug.LogWarning(string.Format("{0}: Sequencer: Camera subject '{1}' wasn't found.", new System.Object[] { DialogueDebug.Prefix, GetParameter(1) }));
}
sequencer.TakeCameraControl();
if (subject != null || original)
{
if (original)
{
targetPosition = sequencer.originalCameraPosition;
targetSize = sequencer.originalOrthographicSize;
}
else
{
targetPosition = new Vector3(subject.position.x, subject.position.y, sequencer.sequencerCamera.transform.position.z);
}
originalPosition = sequencer.sequencerCamera.transform.position;
originalSize = sequencer.sequencerCamera.orthographicSize;
if (duration > SmoothMoveCutoff)
{
startTime = DialogueTime.time;
endTime = startTime + duration;
}
else
{
Stop();
}
}
else
{
Stop();
}
}
public void Update()
{
if (DialogueTime.time < endTime)
{
float elapsed = (DialogueTime.time - startTime) / duration;
if (sequencer != null && sequencer.sequencerCamera != null)
{
sequencer.sequencerCamera.transform.position = Vector3.Lerp(originalPosition, targetPosition, elapsed);
sequencer.sequencerCamera.orthographicSize = Mathf.Lerp(originalSize, targetSize, elapsed);
}
}
else
{
Stop();
}
}
public void OnDestroy()
{
if (subject != null || original)
{
if (sequencer != null && sequencer.sequencerCamera != null)
{
sequencer.sequencerCamera.transform.position = targetPosition;
sequencer.sequencerCamera.orthographicSize = targetSize;
}
}
}
}
|
[
"[",
"AddComponentMenu",
"(",
"\"",
"\"",
")",
"]",
"public",
"class",
"SequencerCommandZoom2D",
":",
"SequencerCommand",
"{",
"private",
"const",
"float",
"SmoothMoveCutoff",
"=",
"0.05f",
";",
"private",
"bool",
"original",
";",
"private",
"Transform",
"subject",
";",
"private",
"Vector3",
"targetPosition",
";",
"private",
"Vector3",
"originalPosition",
";",
"private",
"float",
"targetSize",
";",
"private",
"float",
"originalSize",
";",
"private",
"float",
"duration",
";",
"private",
"float",
"startTime",
";",
"private",
"float",
"endTime",
";",
"public",
"void",
"Start",
"(",
")",
"{",
"original",
"=",
"string",
".",
"Equals",
"(",
"GetParameter",
"(",
"0",
")",
",",
"\"",
"original",
"\"",
")",
";",
"subject",
"=",
"original",
"?",
"null",
":",
"GetSubject",
"(",
"0",
")",
";",
"targetSize",
"=",
"GetParameterAsFloat",
"(",
"1",
",",
"16",
")",
";",
"duration",
"=",
"GetParameterAsFloat",
"(",
"2",
",",
"0",
")",
";",
"if",
"(",
"DialogueDebug",
".",
"logInfo",
")",
"{",
"if",
"(",
"original",
")",
"{",
"Debug",
".",
"Log",
"(",
"string",
".",
"Format",
"(",
"\"",
"{0}: Sequencer: Zoom2D(original, -, {1}s)",
"\"",
",",
"new",
"System",
".",
"Object",
"[",
"]",
"{",
"DialogueDebug",
".",
"Prefix",
",",
"duration",
"}",
")",
")",
";",
"}",
"else",
"{",
"Debug",
".",
"Log",
"(",
"string",
".",
"Format",
"(",
"\"",
"{0}: Sequencer: Zoom2D({1}, {2}, {3}s)",
"\"",
",",
"new",
"System",
".",
"Object",
"[",
"]",
"{",
"DialogueDebug",
".",
"Prefix",
",",
"Tools",
".",
"GetGameObjectName",
"(",
"subject",
")",
",",
"targetSize",
",",
"duration",
"}",
")",
")",
";",
"}",
"}",
"if",
"(",
"(",
"subject",
"==",
"null",
"&&",
"!",
"original",
")",
"&&",
"DialogueDebug",
".",
"logWarnings",
")",
"{",
"Debug",
".",
"LogWarning",
"(",
"string",
".",
"Format",
"(",
"\"",
"{0}: Sequencer: Camera subject '{1}' wasn't found.",
"\"",
",",
"new",
"System",
".",
"Object",
"[",
"]",
"{",
"DialogueDebug",
".",
"Prefix",
",",
"GetParameter",
"(",
"1",
")",
"}",
")",
")",
";",
"}",
"sequencer",
".",
"TakeCameraControl",
"(",
")",
";",
"if",
"(",
"subject",
"!=",
"null",
"||",
"original",
")",
"{",
"if",
"(",
"original",
")",
"{",
"targetPosition",
"=",
"sequencer",
".",
"originalCameraPosition",
";",
"targetSize",
"=",
"sequencer",
".",
"originalOrthographicSize",
";",
"}",
"else",
"{",
"targetPosition",
"=",
"new",
"Vector3",
"(",
"subject",
".",
"position",
".",
"x",
",",
"subject",
".",
"position",
".",
"y",
",",
"sequencer",
".",
"sequencerCamera",
".",
"transform",
".",
"position",
".",
"z",
")",
";",
"}",
"originalPosition",
"=",
"sequencer",
".",
"sequencerCamera",
".",
"transform",
".",
"position",
";",
"originalSize",
"=",
"sequencer",
".",
"sequencerCamera",
".",
"orthographicSize",
";",
"if",
"(",
"duration",
">",
"SmoothMoveCutoff",
")",
"{",
"startTime",
"=",
"DialogueTime",
".",
"time",
";",
"endTime",
"=",
"startTime",
"+",
"duration",
";",
"}",
"else",
"{",
"Stop",
"(",
")",
";",
"}",
"}",
"else",
"{",
"Stop",
"(",
")",
";",
"}",
"}",
"public",
"void",
"Update",
"(",
")",
"{",
"if",
"(",
"DialogueTime",
".",
"time",
"<",
"endTime",
")",
"{",
"float",
"elapsed",
"=",
"(",
"DialogueTime",
".",
"time",
"-",
"startTime",
")",
"/",
"duration",
";",
"if",
"(",
"sequencer",
"!=",
"null",
"&&",
"sequencer",
".",
"sequencerCamera",
"!=",
"null",
")",
"{",
"sequencer",
".",
"sequencerCamera",
".",
"transform",
".",
"position",
"=",
"Vector3",
".",
"Lerp",
"(",
"originalPosition",
",",
"targetPosition",
",",
"elapsed",
")",
";",
"sequencer",
".",
"sequencerCamera",
".",
"orthographicSize",
"=",
"Mathf",
".",
"Lerp",
"(",
"originalSize",
",",
"targetSize",
",",
"elapsed",
")",
";",
"}",
"}",
"else",
"{",
"Stop",
"(",
")",
";",
"}",
"}",
"public",
"void",
"OnDestroy",
"(",
")",
"{",
"if",
"(",
"subject",
"!=",
"null",
"||",
"original",
")",
"{",
"if",
"(",
"sequencer",
"!=",
"null",
"&&",
"sequencer",
".",
"sequencerCamera",
"!=",
"null",
")",
"{",
"sequencer",
".",
"sequencerCamera",
".",
"transform",
".",
"position",
"=",
"targetPosition",
";",
"sequencer",
".",
"sequencerCamera",
".",
"orthographicSize",
"=",
"targetSize",
";",
"}",
"}",
"}",
"}"
] |
Implements sequencer command: Zoom2D([gameobject|speaker|listener[, size[, duration]]])
|
[
"Implements",
"sequencer",
"command",
":",
"Zoom2D",
"(",
"[",
"gameobject|speaker|listener",
"[",
"size",
"[",
"duration",
"]]]",
")"
] |
[
"// Hide from menu.",
"// Get the values of the parameters:",
"// Log to the console:",
"// Start moving the camera:",
"// If duration is above the cutoff, smoothly move camera toward camera angle:",
"// Keep smoothing for the specified duration:",
"// Final position:"
] |
[
{
"param": "SequencerCommand",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "SequencerCommand",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 21
| 655
| 101
|
6c8d212bc10cc0ead8c5a1bc69a8eac71231988c
|
musfique2/okapi
|
src/main/java/ml/grafos/okapi/graphs/SybilRank.java
|
[
"ECL-2.0",
"Apache-2.0"
] |
Java
|
Initializer
|
/**
* This class is used only to initialize the rank of the vertices. It assumes
* that the trust aggregation computations has occurred in the previous step.
*
* After the initialization it also distributes the rank of every vertex to
* it friends, so that the power iterations start.
*
* @author dl
*
*/
|
This class is used only to initialize the rank of the vertices. It assumes
that the trust aggregation computations has occurred in the previous step.
After the initialization it also distributes the rank of every vertex to
it friends, so that the power iterations start.
@author dl
|
[
"This",
"class",
"is",
"used",
"only",
"to",
"initialize",
"the",
"rank",
"of",
"the",
"vertices",
".",
"It",
"assumes",
"that",
"the",
"trust",
"aggregation",
"computations",
"has",
"occurred",
"in",
"the",
"previous",
"step",
".",
"After",
"the",
"initialization",
"it",
"also",
"distributes",
"the",
"rank",
"of",
"every",
"vertex",
"to",
"it",
"friends",
"so",
"that",
"the",
"power",
"iterations",
"start",
".",
"@author",
"dl"
] |
public static class Initializer
extends AbstractComputation<LongWritable, VertexValue, DoubleWritable,
DoubleWritable, DoubleWritable> {
private double totalTrust;
@Override
public void compute(
Vertex<LongWritable, VertexValue, DoubleWritable> vertex,
Iterable<DoubleWritable> messages) throws IOException {
if (vertex.getValue().isTrusted()) {
vertex.getValue().setRank(
totalTrust/(double)((LongWritable)getAggregatedValue(
AGGREGATOR_NUM_TRUSTED)).get());
} else {
vertex.getValue().setRank(0.0);
}
double degree = computeDegree(vertex);
// Distribute rank to edges proportionally to the edge weights
for (Edge<LongWritable, DoubleWritable> edge : vertex.getEdges()) {
double distRank =
vertex.getValue().getRank()*(edge.getValue().get()/degree);
sendMessage(edge.getTargetVertexId(), new DoubleWritable(distRank));
}
}
@Override
public void preSuperstep() {
String s_totalTrust = getContext().getConfiguration().get(TOTAL_TRUST);
if (s_totalTrust != null) {
totalTrust = Double.parseDouble(s_totalTrust);
} else {
// The default value of the total trust is equal to the number of
// vertices in the graph.
totalTrust = getTotalNumVertices();
}
}
}
|
[
"public",
"static",
"class",
"Initializer",
"extends",
"AbstractComputation",
"<",
"LongWritable",
",",
"VertexValue",
",",
"DoubleWritable",
",",
"DoubleWritable",
",",
"DoubleWritable",
">",
"{",
"private",
"double",
"totalTrust",
";",
"@",
"Override",
"public",
"void",
"compute",
"(",
"Vertex",
"<",
"LongWritable",
",",
"VertexValue",
",",
"DoubleWritable",
">",
"vertex",
",",
"Iterable",
"<",
"DoubleWritable",
">",
"messages",
")",
"throws",
"IOException",
"{",
"if",
"(",
"vertex",
".",
"getValue",
"(",
")",
".",
"isTrusted",
"(",
")",
")",
"{",
"vertex",
".",
"getValue",
"(",
")",
".",
"setRank",
"(",
"totalTrust",
"/",
"(",
"double",
")",
"(",
"(",
"LongWritable",
")",
"getAggregatedValue",
"(",
"AGGREGATOR_NUM_TRUSTED",
")",
")",
".",
"get",
"(",
")",
")",
";",
"}",
"else",
"{",
"vertex",
".",
"getValue",
"(",
")",
".",
"setRank",
"(",
"0.0",
")",
";",
"}",
"double",
"degree",
"=",
"computeDegree",
"(",
"vertex",
")",
";",
"for",
"(",
"Edge",
"<",
"LongWritable",
",",
"DoubleWritable",
">",
"edge",
":",
"vertex",
".",
"getEdges",
"(",
")",
")",
"{",
"double",
"distRank",
"=",
"vertex",
".",
"getValue",
"(",
")",
".",
"getRank",
"(",
")",
"*",
"(",
"edge",
".",
"getValue",
"(",
")",
".",
"get",
"(",
")",
"/",
"degree",
")",
";",
"sendMessage",
"(",
"edge",
".",
"getTargetVertexId",
"(",
")",
",",
"new",
"DoubleWritable",
"(",
"distRank",
")",
")",
";",
"}",
"}",
"@",
"Override",
"public",
"void",
"preSuperstep",
"(",
")",
"{",
"String",
"s_totalTrust",
"=",
"getContext",
"(",
")",
".",
"getConfiguration",
"(",
")",
".",
"get",
"(",
"TOTAL_TRUST",
")",
";",
"if",
"(",
"s_totalTrust",
"!=",
"null",
")",
"{",
"totalTrust",
"=",
"Double",
".",
"parseDouble",
"(",
"s_totalTrust",
")",
";",
"}",
"else",
"{",
"totalTrust",
"=",
"getTotalNumVertices",
"(",
")",
";",
"}",
"}",
"}"
] |
This class is used only to initialize the rank of the vertices.
|
[
"This",
"class",
"is",
"used",
"only",
"to",
"initialize",
"the",
"rank",
"of",
"the",
"vertices",
"."
] |
[
"// Distribute rank to edges proportionally to the edge weights\r",
"// The default value of the total trust is equal to the number of\r",
"// vertices in the graph.\r"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 17
| 302
| 77
|
219cbd34ca30e0919cedf645e42e0820cd57060b
|
sunxuia/leetcode-solution-java
|
src/main/java/q1600/Q1593_SplitAStringIntoTheMaxNumberOfUniqueSubstrings.java
|
[
"MIT"
] |
Java
|
Q1593_SplitAStringIntoTheMaxNumberOfUniqueSubstrings
|
/**
* [Medium] 1593. Split a String Into the Max Number of Unique Substrings
* https://leetcode.com/problems/split-a-string-into-the-max-number-of-unique-substrings/
*
* Given a string s, return the maximum number of unique substrings that the given string can be split into.
*
* You can split string s into any list of non-empty substrings, where the concatenation of the substrings forms the
* original string. However, you must split the substrings such that all of them are unique.
*
* A substring is a contiguous sequence of characters within a string.
*
* Example 1:
*
* Input: s = "ababccc"
* Output: 5
* Explanation: One way to split maximally is ['a', 'b', 'ab', 'c', 'cc']. Splitting like ['a', 'b', 'a', 'b', 'c',
* 'cc'] is not valid as you have 'a' and 'b' multiple times.
*
* Example 2:
*
* Input: s = "aba"
* Output: 2
* Explanation: One way to split maximally is ['a', 'ba'].
*
* Example 3:
*
* Input: s = "aa"
* Output: 1
* Explanation: It is impossible to split the string any further.
*
* Constraints:
*
* 1 <= s.length <= 16
*
*
* s contains only lower case English letters.
*/
|
Given a string s, return the maximum number of unique substrings that the given string can be split into.
You can split string s into any list of non-empty substrings, where the concatenation of the substrings forms the
original string. However, you must split the substrings such that all of them are unique.
A substring is a contiguous sequence of characters within a string.
Example 1.
Example 2.
s = "aba"
Output: 2
Explanation: One way to split maximally is ['a', 'ba'].
Example 3.
s = "aa"
Output: 1
Explanation: It is impossible to split the string any further.
s contains only lower case English letters.
|
[
"Given",
"a",
"string",
"s",
"return",
"the",
"maximum",
"number",
"of",
"unique",
"substrings",
"that",
"the",
"given",
"string",
"can",
"be",
"split",
"into",
".",
"You",
"can",
"split",
"string",
"s",
"into",
"any",
"list",
"of",
"non",
"-",
"empty",
"substrings",
"where",
"the",
"concatenation",
"of",
"the",
"substrings",
"forms",
"the",
"original",
"string",
".",
"However",
"you",
"must",
"split",
"the",
"substrings",
"such",
"that",
"all",
"of",
"them",
"are",
"unique",
".",
"A",
"substring",
"is",
"a",
"contiguous",
"sequence",
"of",
"characters",
"within",
"a",
"string",
".",
"Example",
"1",
".",
"Example",
"2",
".",
"s",
"=",
"\"",
"aba",
"\"",
"Output",
":",
"2",
"Explanation",
":",
"One",
"way",
"to",
"split",
"maximally",
"is",
"[",
"'",
"a",
"'",
"'",
"ba",
"'",
"]",
".",
"Example",
"3",
".",
"s",
"=",
"\"",
"aa",
"\"",
"Output",
":",
"1",
"Explanation",
":",
"It",
"is",
"impossible",
"to",
"split",
"the",
"string",
"any",
"further",
".",
"s",
"contains",
"only",
"lower",
"case",
"English",
"letters",
"."
] |
@RunWith(LeetCodeRunner.class)
public class Q1593_SplitAStringIntoTheMaxNumberOfUniqueSubstrings {
@Answer
public int maxUniqueSplit(String s) {
return dfs(s, new HashSet<>(), 0);
}
private int dfs(String s, Set<String> exists, int start) {
if (start == s.length()) {
return 0;
}
int res = -1;
for (int i = start + 1; i <= s.length(); i++) {
String str = s.substring(start, i);
if (exists.add(str)) {
int len = dfs(s, exists, i);
if (len >= 0) {
res = Math.max(res, 1 + len);
}
exists.remove(str);
}
}
return res;
}
@TestData
public DataExpectation example1 = DataExpectation.create("ababccc").expect(5);
@TestData
public DataExpectation example2 = DataExpectation.create("aba").expect(2);
@TestData
public DataExpectation example3 = DataExpectation.create("aa").expect(1);
@TestData
public DataExpectation normal1 = DataExpectation.create("wwwzfvedwfvhsww").expect(11);
}
|
[
"@",
"RunWith",
"(",
"LeetCodeRunner",
".",
"class",
")",
"public",
"class",
"Q1593_SplitAStringIntoTheMaxNumberOfUniqueSubstrings",
"{",
"@",
"Answer",
"public",
"int",
"maxUniqueSplit",
"(",
"String",
"s",
")",
"{",
"return",
"dfs",
"(",
"s",
",",
"new",
"HashSet",
"<",
">",
"(",
")",
",",
"0",
")",
";",
"}",
"private",
"int",
"dfs",
"(",
"String",
"s",
",",
"Set",
"<",
"String",
">",
"exists",
",",
"int",
"start",
")",
"{",
"if",
"(",
"start",
"==",
"s",
".",
"length",
"(",
")",
")",
"{",
"return",
"0",
";",
"}",
"int",
"res",
"=",
"-",
"1",
";",
"for",
"(",
"int",
"i",
"=",
"start",
"+",
"1",
";",
"i",
"<=",
"s",
".",
"length",
"(",
")",
";",
"i",
"++",
")",
"{",
"String",
"str",
"=",
"s",
".",
"substring",
"(",
"start",
",",
"i",
")",
";",
"if",
"(",
"exists",
".",
"add",
"(",
"str",
")",
")",
"{",
"int",
"len",
"=",
"dfs",
"(",
"s",
",",
"exists",
",",
"i",
")",
";",
"if",
"(",
"len",
">=",
"0",
")",
"{",
"res",
"=",
"Math",
".",
"max",
"(",
"res",
",",
"1",
"+",
"len",
")",
";",
"}",
"exists",
".",
"remove",
"(",
"str",
")",
";",
"}",
"}",
"return",
"res",
";",
"}",
"@",
"TestData",
"public",
"DataExpectation",
"example1",
"=",
"DataExpectation",
".",
"create",
"(",
"\"",
"ababccc",
"\"",
")",
".",
"expect",
"(",
"5",
")",
";",
"@",
"TestData",
"public",
"DataExpectation",
"example2",
"=",
"DataExpectation",
".",
"create",
"(",
"\"",
"aba",
"\"",
")",
".",
"expect",
"(",
"2",
")",
";",
"@",
"TestData",
"public",
"DataExpectation",
"example3",
"=",
"DataExpectation",
".",
"create",
"(",
"\"",
"aa",
"\"",
")",
".",
"expect",
"(",
"1",
")",
";",
"@",
"TestData",
"public",
"DataExpectation",
"normal1",
"=",
"DataExpectation",
".",
"create",
"(",
"\"",
"wwwzfvedwfvhsww",
"\"",
")",
".",
"expect",
"(",
"11",
")",
";",
"}"
] |
[Medium] 1593.
|
[
"[",
"Medium",
"]",
"1593",
"."
] |
[] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 16
| 281
| 315
|
155426c8b656e8eb6fe1b4efca246784241f228e
|
GoodAI/BrainSimulator
|
Sources/Modules/BasicNodes/Module/DiscreteRL/MyDiscreteQLearningNode.cs
|
[
"Apache-2.0"
] |
C#
|
MyVariableUpdateTask
|
/// <summary>
/// <ul>
/// <li> Checks which variables should be contained in the decision space.</li>
/// <li> For each dimension of GlobalDataInput checks if there were multiple values,
/// if yes, it is identified as a variable and added into the DS. </li>
/// <li> Also, inputs are rescaled by the value of RescaleVariables.</li>
/// </ul>
/// </summary>
|
Checks which variables should be contained in the decision space. For each dimension of GlobalDataInput checks if there were multiple values,
if yes, it is identified as a variable and added into the DS. Also, inputs are rescaled by the value of RescaleVariables.
|
[
"Checks",
"which",
"variables",
"should",
"be",
"contained",
"in",
"the",
"decision",
"space",
".",
"For",
"each",
"dimension",
"of",
"GlobalDataInput",
"checks",
"if",
"there",
"were",
"multiple",
"values",
"if",
"yes",
"it",
"is",
"identified",
"as",
"a",
"variable",
"and",
"added",
"into",
"the",
"DS",
".",
"Also",
"inputs",
"are",
"rescaled",
"by",
"the",
"value",
"of",
"RescaleVariables",
"."
] |
[Description("Monitor changes of inputs"), MyTaskInfo(OneShot = false)]
public class MyVariableUpdateTask : MyTask<MyDiscreteQLearningNode>
{
private bool warnedNegative = false;
public override void Init(int nGPU)
{
}
public override void Execute()
{
float[] inputs = this.RescaleAllInputs();
Owner.Rds.VarManager.MonitorAllInputValues(inputs, null);
int[] s_tt = Owner.Rds.VarManager.GetCurrentState();
if (s_tt.Count() != Owner.CurrentStateOutput.Count)
{
MyLog.WARNING.WriteLine("Unexpected size of current state");
}
else
{
for (int i = 0; i < s_tt.Count(); i++)
{
Owner.CurrentStateOutput.Host[i] = s_tt[i];
}
Owner.CurrentStateOutput.SafeCopyToDevice();
}
}
private float[] RescaleAllInputs()
{
Owner.GlobalDataInput.SafeCopyToHost();
float[] inputs = new float[Owner.GlobalDataInput.Count];
for (int i = 0; i < Owner.GlobalDataInput.Count; i++)
{
Owner.GlobalDataInput.Host[i] *= Owner.RescaleVariables;
inputs[i] = Owner.GlobalDataInput.Host[i];
if (inputs[i] < 0)
{
if (!warnedNegative)
{
MyLog.DEBUG.WriteLine("WARNING: negative value on input detected, all negative values will be set to 0");
warnedNegative = true;
}
inputs[i] = 0;
}
}
return inputs;
}
}
|
[
"[",
"Description",
"(",
"\"",
"Monitor changes of inputs",
"\"",
")",
",",
"MyTaskInfo",
"(",
"OneShot",
"=",
"false",
")",
"]",
"public",
"class",
"MyVariableUpdateTask",
":",
"MyTask",
"<",
"MyDiscreteQLearningNode",
">",
"{",
"private",
"bool",
"warnedNegative",
"=",
"false",
";",
"public",
"override",
"void",
"Init",
"(",
"int",
"nGPU",
")",
"{",
"}",
"public",
"override",
"void",
"Execute",
"(",
")",
"{",
"float",
"[",
"]",
"inputs",
"=",
"this",
".",
"RescaleAllInputs",
"(",
")",
";",
"Owner",
".",
"Rds",
".",
"VarManager",
".",
"MonitorAllInputValues",
"(",
"inputs",
",",
"null",
")",
";",
"int",
"[",
"]",
"s_tt",
"=",
"Owner",
".",
"Rds",
".",
"VarManager",
".",
"GetCurrentState",
"(",
")",
";",
"if",
"(",
"s_tt",
".",
"Count",
"(",
")",
"!=",
"Owner",
".",
"CurrentStateOutput",
".",
"Count",
")",
"{",
"MyLog",
".",
"WARNING",
".",
"WriteLine",
"(",
"\"",
"Unexpected size of current state",
"\"",
")",
";",
"}",
"else",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"s_tt",
".",
"Count",
"(",
")",
";",
"i",
"++",
")",
"{",
"Owner",
".",
"CurrentStateOutput",
".",
"Host",
"[",
"i",
"]",
"=",
"s_tt",
"[",
"i",
"]",
";",
"}",
"Owner",
".",
"CurrentStateOutput",
".",
"SafeCopyToDevice",
"(",
")",
";",
"}",
"}",
"private",
"float",
"[",
"]",
"RescaleAllInputs",
"(",
")",
"{",
"Owner",
".",
"GlobalDataInput",
".",
"SafeCopyToHost",
"(",
")",
";",
"float",
"[",
"]",
"inputs",
"=",
"new",
"float",
"[",
"Owner",
".",
"GlobalDataInput",
".",
"Count",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"Owner",
".",
"GlobalDataInput",
".",
"Count",
";",
"i",
"++",
")",
"{",
"Owner",
".",
"GlobalDataInput",
".",
"Host",
"[",
"i",
"]",
"*=",
"Owner",
".",
"RescaleVariables",
";",
"inputs",
"[",
"i",
"]",
"=",
"Owner",
".",
"GlobalDataInput",
".",
"Host",
"[",
"i",
"]",
";",
"if",
"(",
"inputs",
"[",
"i",
"]",
"<",
"0",
")",
"{",
"if",
"(",
"!",
"warnedNegative",
")",
"{",
"MyLog",
".",
"DEBUG",
".",
"WriteLine",
"(",
"\"",
"WARNING: negative value on input detected, all negative values will be set to 0",
"\"",
")",
";",
"warnedNegative",
"=",
"true",
";",
"}",
"inputs",
"[",
"i",
"]",
"=",
"0",
";",
"}",
"}",
"return",
"inputs",
";",
"}",
"}"
] |
[] |
[] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 16
| 342
| 99
|
|
120402717281e6e39f6a53ce7882c4c21ce0fff7
|
jhundley9109/rsync
|
index.js
|
[
"MIT"
] |
JavaScript
|
Rsync
|
/**
* Rsync is a wrapper class to configure and execute an `rsync` command
* in a fluent and convenient way.
*
* A new command can be set up by creating a new `Rsync` instance of
* obtaining one through the `build` method.
*
* @example
* // using the constructor
* var rsync = new Rsync()
* .source('/path/to/source')
* .destination('myserver:destination/');
*
* // using the build method with options
* var rsync = Rsync.build({
* source: '/path/to/source',
* destination: 'myserver:destination/'
* });
*
* Executing the command can be done using the `execute` method. The command
* is executed as a child process and three callbacks can be registered. See
* the `execute` method for more details.
*
* @example
* rsync.execute((error, code, cmd) => {
* // function called when the child process is finished
* }, stdoutChunk => {
* // function called when a chunk of text is received on stdout
* }, stderrChunk => {
* // function called when a chunk of text is received on stderr
* });
*
* @author Mattijs Hoitink <[email protected]>
* @copyright Copyright (c) 2013, Mattijs Hoitink
* <[email protected]>
* @license The MIT License
*
* @constructor
* @param {Object} config Configuration settings for the Rsync wrapper.
*/
|
Rsync is a wrapper class to configure and execute an `rsync` command
in a fluent and convenient way.
A new command can be set up by creating a new `Rsync` instance of
obtaining one through the `build` method.
@example
using the constructor
var rsync = new Rsync()
.source('/path/to/source')
.destination('myserver:destination/').
using the build method with options
var rsync = Rsync.build({
source: '/path/to/source',
destination: 'myserver:destination/'
}).
Executing the command can be done using the `execute` method. The command
is executed as a child process and three callbacks can be registered. See
the `execute` method for more details.
@example
rsync.execute((error, code, cmd) => {
function called when the child process is finished
}, stdoutChunk => {
function called when a chunk of text is received on stdout
}, stderrChunk => {
function called when a chunk of text is received on stderr
}).
@author Mattijs Hoitink
@copyright Copyright (c) 2013, Mattijs Hoitink
@license The MIT License
@constructor
@param {Object} config Configuration settings for the Rsync wrapper.
|
[
"Rsync",
"is",
"a",
"wrapper",
"class",
"to",
"configure",
"and",
"execute",
"an",
"`",
"rsync",
"`",
"command",
"in",
"a",
"fluent",
"and",
"convenient",
"way",
".",
"A",
"new",
"command",
"can",
"be",
"set",
"up",
"by",
"creating",
"a",
"new",
"`",
"Rsync",
"`",
"instance",
"of",
"obtaining",
"one",
"through",
"the",
"`",
"build",
"`",
"method",
".",
"@example",
"using",
"the",
"constructor",
"var",
"rsync",
"=",
"new",
"Rsync",
"()",
".",
"source",
"(",
"'",
"/",
"path",
"/",
"to",
"/",
"source",
"'",
")",
".",
"destination",
"(",
"'",
"myserver",
":",
"destination",
"/",
"'",
")",
".",
"using",
"the",
"build",
"method",
"with",
"options",
"var",
"rsync",
"=",
"Rsync",
".",
"build",
"(",
"{",
"source",
":",
"'",
"/",
"path",
"/",
"to",
"/",
"source",
"'",
"destination",
":",
"'",
"myserver",
":",
"destination",
"/",
"'",
"}",
")",
".",
"Executing",
"the",
"command",
"can",
"be",
"done",
"using",
"the",
"`",
"execute",
"`",
"method",
".",
"The",
"command",
"is",
"executed",
"as",
"a",
"child",
"process",
"and",
"three",
"callbacks",
"can",
"be",
"registered",
".",
"See",
"the",
"`",
"execute",
"`",
"method",
"for",
"more",
"details",
".",
"@example",
"rsync",
".",
"execute",
"((",
"error",
"code",
"cmd",
")",
"=",
">",
"{",
"function",
"called",
"when",
"the",
"child",
"process",
"is",
"finished",
"}",
"stdoutChunk",
"=",
">",
"{",
"function",
"called",
"when",
"a",
"chunk",
"of",
"text",
"is",
"received",
"on",
"stdout",
"}",
"stderrChunk",
"=",
">",
"{",
"function",
"called",
"when",
"a",
"chunk",
"of",
"text",
"is",
"received",
"on",
"stderr",
"}",
")",
".",
"@author",
"Mattijs",
"Hoitink",
"@copyright",
"Copyright",
"(",
"c",
")",
"2013",
"Mattijs",
"Hoitink",
"@license",
"The",
"MIT",
"License",
"@constructor",
"@param",
"{",
"Object",
"}",
"config",
"Configuration",
"settings",
"for",
"the",
"Rsync",
"wrapper",
"."
] |
class Rsync {
constructor ({ executable = which('rsync'), stderr = process.stderr, stdout = process.stdout, stdin = process.stdin } = {}) {
// executable
this._executable = executable;
// source(s) and destination
this._sources = [];
this._destination = '';
// ordered list of file patterns to include/exclude
this._patterns = [];
// options
this._options = new Proxy(Object.create(null), {
get (target, prop) {
prop = stripLeadingDashes(prop);
return target[prop];
},
set (target, prop, value) {
prop = stripLeadingDashes(prop);
target[prop] = value;
return true;
},
deleteProperty (target, prop) {
prop = stripLeadingDashes(prop);
delete target[prop];
return true;
},
has (target, prop) {
prop = stripLeadingDashes(prop);
return prop in target;
}
});
// output callbacks
this._outputHandlers = {
stdout: noop,
stderr: noop
};
this._cwd = process.cwd();
// Allow child_process.spawn env overriding
this._env = process.env;
this._stderr = stderr;
this._stdout = stdout;
this._stdin = stdin;
}
/**
* Set an option.
* @param {string} option - Option name
* @param {*} [value] - Whatever value
* @return {Rsync}
*/
set (option, value) {
if (Array.isArray(option)) {
option.forEach(optionArr => {
this._options[optionArr[0]] = optionArr[1];
});
} else {
this._options[option] = value;
}
return this;
}
/**
* Unset an option.
* @param {string} option - Option name
* @return {Rsync}
*/
unset (option) {
if (option) {
delete this._options[option];
}
return this;
}
/**
* Sets an Array of flags or a string of flags to `true`
* @param {string|...string|string[]|...string[]} flags - Flags to set to
* `true`
* @returns {Rsync}
* @example
* rsync.setFlags('avz')
* // equivalent to:
* rsync.setFlags(['a', 'v', 'z'])
* // and:
* rsync.setFlags('a', 'v', 'z')
*/
setFlags (...flags) {
parseFlags(...flags).forEach(flag => {
this.set(flag);
});
return this;
}
/**
* Sets an Array of flags or a string of flags to `false`
* @param {string|...string|string[]|...string[]} flags - Flags to set to
* `false`
* @returns {Rsync}
* @example
* rsync.unsetFlags('avz')
* // equivalent to:
* rsync.unsetFlags(['a', 'v', 'z'])
* // and:
* rsync.unsetFlags('a', 'v', 'z')
*/
unsetFlags (...flags) {
parseFlags(...flags).forEach(flag => {
this.unset(flag);
});
return this;
}
/**
* Check if an option is set.
* @param {string} option
* @return {boolean}
*/
isSet (option) {
return option in this._options;
}
/**
* Get an option by name.
* @param {string} name - Option name
* @return {*}
*/
option (name) {
return this._options[name];
}
/**
* Register a list of file patterns to include/exclude in the transfer.
* Patterns can be registered as an array of Strings or Objects.
*
* When registering a pattern as a string it must be prefixed with a `+` or
* `-` sign to signal include or exclude for the pattern. The sign will be
* stripped of and the pattern will be added to the ordered pattern list.
*
* When registering the pattern as an Object it must contain the `action` and
* `pattern` keys where `action` contains the `+` or `-` sign and the
* `pattern` key contains the file pattern, without the `+` or `-` sign.
*
* @example
* // on an existing rsync object
* rsync.patterns(['-docs', { action: '+', pattern: '/subdir/*.py' }]);
*
* // using Rsync.build for a new rsync object
* rsync = Rsync.build({
* ...
* patterns: [ '-docs', { action: '+', pattern: '/subdir/*.py' }]
* ...
* })
*
* @param {Array} patterns
* @return {Rsync}
*/
patterns (...patterns) {
patterns.forEach(pattern => {
if (Array.isArray(pattern)) {
return this.patterns(...pattern);
}
let action = '?';
if (typeof pattern === 'string') {
action = pattern.charAt(0);
pattern = pattern.substring(1);
} else if (typeof pattern === 'object' && 'action' in pattern &&
'pattern' in pattern) {
action = pattern.action;
pattern = pattern.pattern;
}
// Check if the pattern is an include or exclude
if (action === '-') {
this.exclude(pattern);
} else {
this.include(pattern);
}
});
return this;
}
/**
* Exclude a file pattern from transfer. The pattern will be appended to the
* ordered list of patterns for the rsync command.
*
* @param {...string|...string[]} patterns
* @return {Rsync}
*/
exclude (...patterns) {
patterns.forEach(pattern => {
if (Array.isArray(pattern)) {
return this.exclude(...pattern);
}
this._patterns.push({
action: '-',
pattern
});
});
return this;
}
/**
* Include a file pattern for transfer. The pattern will be appended to the
* ordered list of patterns for the rsync command.
*
* @param {string|Array} patterns
* @return {Rsync}
*/
include (...patterns) {
patterns.forEach(pattern => {
if (Array.isArray(pattern)) {
return this.include(...pattern);
}
this._patterns.push({
action: '+',
pattern
});
});
return this;
}
/**
* Get the command that is going to be executed.
* @return {string}
*/
command () {
return `${this.executable()} ${this.args().join(' ')}`;
}
/**
* Get the arguments for the rsync command.
* @return {Array}
*/
args () {
// Gathered arguments
let args = [];
// Add options. Short options (one letter) without values are gathered
// together. Long options have a value but can also be a single letter.
let short = [];
let long = [];
// Split long and short options
Object.keys(this._options).forEach(key => {
const value = this._options[key];
if (key.length === 1 && typeof value === 'undefined') {
short = short.concat(key);
} else {
long =
Array.isArray(value)
? long.concat(value.map(
val => buildOption(key, val, escapeShellArg)))
: long.concat(
buildOption(key, value, escapeShellArg));
}
});
// Add combined short options if any are present
if (short.length) {
args = args.concat(`-${short.join('')}`);
}
// Add long options if any are present
if (long.length) {
args = args.concat(long);
}
// Add includes/excludes in order
args =
args.concat(this._patterns.map(({ action, pattern }) => buildOption(action ===
'-'
? 'exclude'
: 'include', pattern)));
// Add sources
if (this.source().length) {
args = args.concat(this.source().map(source => unixify(source, false)));
}
// Add destination
if (this.destination()) {
args = args.concat(unixify(this.destination(), false));
}
return args;
}
/**
* Get and set rsync process cwd directory.
*
* @param {string} [cwd] Directory path relative to current process directory.
* @return {string} Return current _cwd.
*/
cwd (cwd) {
if (cwd) {
this._cwd = path.posix.resolve(cwd);
}
return this._cwd;
}
/**
* Get and set rsync process environment variables
*
* @param {string} [env] Environment variables
* @return {string} Return current _env.
*/
env (env) {
if (env) {
this._env = env;
}
return this._env;
}
/**
* Register an output handlers for the commands stdout and stderr streams.
* These functions will be called once data is streamed on one of the output
* buffers when the command is executed using `execute`.
*
* Only one callback function can be registered for each output stream.
* Previously registered callbacks will be overridden.
*
* @param {Function} stdout - Callback Function for stdout `data` event
* @param {Function} stderr - Callback Function for stderr `data` event
* @return {Rsync}
*/
output (stdout, stderr) {
// Check for single argument so the method can be used with Rsync.build
if (arguments.length === 1 && Array.isArray(stdout)) {
[stderr, stdout] = stdout;
}
if (typeof stdout === 'function') {
this._outputHandlers.stdout = stdout;
}
if (typeof stderr === 'function') {
this._outputHandlers.stderr = stderr;
}
return this;
}
/**
* Execute the rsync command.
*
* The callback function is called with an Error object (or null when there
* was none), the exit code from the executed command and the executed
* command as a string.
*
* When stdoutHandler and stderrHandler functions are provided they will be
* used to stream data from stdout and stderr directly without buffering.
*
* @param {Object} [opts] Options
* @param {Function} [opts.stdoutHandler] Called on each chunk received from
* stdout
* @param {Function} [opts.stderrHandler] - Called on each chunk received from
* stdout
* @param {Function} [callback] - Node-style callback. If present, return the
* `ChildProcess` object, otherwise return a `Promise`.
* @returns {Promise<void>|ChildProcess}
*/
execute (opts = {}) {
// Register output handlers
this.output(
opts.stdoutHandler || this._outputHandlers.stdout,
opts.stderrHandler || this._outputHandlers.stderr
);
const promise = new Promise((resolve, reject) => {
// use shell: true because spawn screws up quotes without it
const cmdProc = spawn(this.executable(), this.args(), {
cwd: this._cwd,
env: this._env,
shell: true
});
cmdProc.stdout.on('data', this._outputHandlers.stdout);
cmdProc.stderr.on('data', this._outputHandlers.stderr);
cmdProc.on('error', reject);
cmdProc.on('close', code => {
if (code) {
let errorObj = new Error(`rsync exited with code ${code}`);
errorObj.code = code;
return reject(errorObj);
}
resolve(code);
});
}).catch(err => {
return Promise.reject(err);
});
return promise;
}
/**
* @deprecated
*/
// flags () {
// throw new Error('flags() is deprecated; use setFlags() or unsetFlags() instead');
// }
flags(flags) {
this.setFlags(flags);
}
}
|
[
"class",
"Rsync",
"{",
"constructor",
"(",
"{",
"executable",
"=",
"which",
"(",
"'rsync'",
")",
",",
"stderr",
"=",
"process",
".",
"stderr",
",",
"stdout",
"=",
"process",
".",
"stdout",
",",
"stdin",
"=",
"process",
".",
"stdin",
"}",
"=",
"{",
"}",
")",
"{",
"this",
".",
"_executable",
"=",
"executable",
";",
"this",
".",
"_sources",
"=",
"[",
"]",
";",
"this",
".",
"_destination",
"=",
"''",
";",
"this",
".",
"_patterns",
"=",
"[",
"]",
";",
"this",
".",
"_options",
"=",
"new",
"Proxy",
"(",
"Object",
".",
"create",
"(",
"null",
")",
",",
"{",
"get",
"(",
"target",
",",
"prop",
")",
"{",
"prop",
"=",
"stripLeadingDashes",
"(",
"prop",
")",
";",
"return",
"target",
"[",
"prop",
"]",
";",
"}",
",",
"set",
"(",
"target",
",",
"prop",
",",
"value",
")",
"{",
"prop",
"=",
"stripLeadingDashes",
"(",
"prop",
")",
";",
"target",
"[",
"prop",
"]",
"=",
"value",
";",
"return",
"true",
";",
"}",
",",
"deleteProperty",
"(",
"target",
",",
"prop",
")",
"{",
"prop",
"=",
"stripLeadingDashes",
"(",
"prop",
")",
";",
"delete",
"target",
"[",
"prop",
"]",
";",
"return",
"true",
";",
"}",
",",
"has",
"(",
"target",
",",
"prop",
")",
"{",
"prop",
"=",
"stripLeadingDashes",
"(",
"prop",
")",
";",
"return",
"prop",
"in",
"target",
";",
"}",
"}",
")",
";",
"this",
".",
"_outputHandlers",
"=",
"{",
"stdout",
":",
"noop",
",",
"stderr",
":",
"noop",
"}",
";",
"this",
".",
"_cwd",
"=",
"process",
".",
"cwd",
"(",
")",
";",
"this",
".",
"_env",
"=",
"process",
".",
"env",
";",
"this",
".",
"_stderr",
"=",
"stderr",
";",
"this",
".",
"_stdout",
"=",
"stdout",
";",
"this",
".",
"_stdin",
"=",
"stdin",
";",
"}",
"set",
"(",
"option",
",",
"value",
")",
"{",
"if",
"(",
"Array",
".",
"isArray",
"(",
"option",
")",
")",
"{",
"option",
".",
"forEach",
"(",
"optionArr",
"=>",
"{",
"this",
".",
"_options",
"[",
"optionArr",
"[",
"0",
"]",
"]",
"=",
"optionArr",
"[",
"1",
"]",
";",
"}",
")",
";",
"}",
"else",
"{",
"this",
".",
"_options",
"[",
"option",
"]",
"=",
"value",
";",
"}",
"return",
"this",
";",
"}",
"unset",
"(",
"option",
")",
"{",
"if",
"(",
"option",
")",
"{",
"delete",
"this",
".",
"_options",
"[",
"option",
"]",
";",
"}",
"return",
"this",
";",
"}",
"setFlags",
"(",
"...",
"flags",
")",
"{",
"parseFlags",
"(",
"...",
"flags",
")",
".",
"forEach",
"(",
"flag",
"=>",
"{",
"this",
".",
"set",
"(",
"flag",
")",
";",
"}",
")",
";",
"return",
"this",
";",
"}",
"unsetFlags",
"(",
"...",
"flags",
")",
"{",
"parseFlags",
"(",
"...",
"flags",
")",
".",
"forEach",
"(",
"flag",
"=>",
"{",
"this",
".",
"unset",
"(",
"flag",
")",
";",
"}",
")",
";",
"return",
"this",
";",
"}",
"isSet",
"(",
"option",
")",
"{",
"return",
"option",
"in",
"this",
".",
"_options",
";",
"}",
"option",
"(",
"name",
")",
"{",
"return",
"this",
".",
"_options",
"[",
"name",
"]",
";",
"}",
"patterns",
"(",
"...",
"patterns",
")",
"{",
"patterns",
".",
"forEach",
"(",
"pattern",
"=>",
"{",
"if",
"(",
"Array",
".",
"isArray",
"(",
"pattern",
")",
")",
"{",
"return",
"this",
".",
"patterns",
"(",
"...",
"pattern",
")",
";",
"}",
"let",
"action",
"=",
"'?'",
";",
"if",
"(",
"typeof",
"pattern",
"===",
"'string'",
")",
"{",
"action",
"=",
"pattern",
".",
"charAt",
"(",
"0",
")",
";",
"pattern",
"=",
"pattern",
".",
"substring",
"(",
"1",
")",
";",
"}",
"else",
"if",
"(",
"typeof",
"pattern",
"===",
"'object'",
"&&",
"'action'",
"in",
"pattern",
"&&",
"'pattern'",
"in",
"pattern",
")",
"{",
"action",
"=",
"pattern",
".",
"action",
";",
"pattern",
"=",
"pattern",
".",
"pattern",
";",
"}",
"if",
"(",
"action",
"===",
"'-'",
")",
"{",
"this",
".",
"exclude",
"(",
"pattern",
")",
";",
"}",
"else",
"{",
"this",
".",
"include",
"(",
"pattern",
")",
";",
"}",
"}",
")",
";",
"return",
"this",
";",
"}",
"exclude",
"(",
"...",
"patterns",
")",
"{",
"patterns",
".",
"forEach",
"(",
"pattern",
"=>",
"{",
"if",
"(",
"Array",
".",
"isArray",
"(",
"pattern",
")",
")",
"{",
"return",
"this",
".",
"exclude",
"(",
"...",
"pattern",
")",
";",
"}",
"this",
".",
"_patterns",
".",
"push",
"(",
"{",
"action",
":",
"'-'",
",",
"pattern",
"}",
")",
";",
"}",
")",
";",
"return",
"this",
";",
"}",
"include",
"(",
"...",
"patterns",
")",
"{",
"patterns",
".",
"forEach",
"(",
"pattern",
"=>",
"{",
"if",
"(",
"Array",
".",
"isArray",
"(",
"pattern",
")",
")",
"{",
"return",
"this",
".",
"include",
"(",
"...",
"pattern",
")",
";",
"}",
"this",
".",
"_patterns",
".",
"push",
"(",
"{",
"action",
":",
"'+'",
",",
"pattern",
"}",
")",
";",
"}",
")",
";",
"return",
"this",
";",
"}",
"command",
"(",
")",
"{",
"return",
"`",
"${",
"this",
".",
"executable",
"(",
")",
"}",
"${",
"this",
".",
"args",
"(",
")",
".",
"join",
"(",
"' '",
")",
"}",
"`",
";",
"}",
"args",
"(",
")",
"{",
"let",
"args",
"=",
"[",
"]",
";",
"let",
"short",
"=",
"[",
"]",
";",
"let",
"long",
"=",
"[",
"]",
";",
"Object",
".",
"keys",
"(",
"this",
".",
"_options",
")",
".",
"forEach",
"(",
"key",
"=>",
"{",
"const",
"value",
"=",
"this",
".",
"_options",
"[",
"key",
"]",
";",
"if",
"(",
"key",
".",
"length",
"===",
"1",
"&&",
"typeof",
"value",
"===",
"'undefined'",
")",
"{",
"short",
"=",
"short",
".",
"concat",
"(",
"key",
")",
";",
"}",
"else",
"{",
"long",
"=",
"Array",
".",
"isArray",
"(",
"value",
")",
"?",
"long",
".",
"concat",
"(",
"value",
".",
"map",
"(",
"val",
"=>",
"buildOption",
"(",
"key",
",",
"val",
",",
"escapeShellArg",
")",
")",
")",
":",
"long",
".",
"concat",
"(",
"buildOption",
"(",
"key",
",",
"value",
",",
"escapeShellArg",
")",
")",
";",
"}",
"}",
")",
";",
"if",
"(",
"short",
".",
"length",
")",
"{",
"args",
"=",
"args",
".",
"concat",
"(",
"`",
"${",
"short",
".",
"join",
"(",
"''",
")",
"}",
"`",
")",
";",
"}",
"if",
"(",
"long",
".",
"length",
")",
"{",
"args",
"=",
"args",
".",
"concat",
"(",
"long",
")",
";",
"}",
"args",
"=",
"args",
".",
"concat",
"(",
"this",
".",
"_patterns",
".",
"map",
"(",
"(",
"{",
"action",
",",
"pattern",
"}",
")",
"=>",
"buildOption",
"(",
"action",
"===",
"'-'",
"?",
"'exclude'",
":",
"'include'",
",",
"pattern",
")",
")",
")",
";",
"if",
"(",
"this",
".",
"source",
"(",
")",
".",
"length",
")",
"{",
"args",
"=",
"args",
".",
"concat",
"(",
"this",
".",
"source",
"(",
")",
".",
"map",
"(",
"source",
"=>",
"unixify",
"(",
"source",
",",
"false",
")",
")",
")",
";",
"}",
"if",
"(",
"this",
".",
"destination",
"(",
")",
")",
"{",
"args",
"=",
"args",
".",
"concat",
"(",
"unixify",
"(",
"this",
".",
"destination",
"(",
")",
",",
"false",
")",
")",
";",
"}",
"return",
"args",
";",
"}",
"cwd",
"(",
"cwd",
")",
"{",
"if",
"(",
"cwd",
")",
"{",
"this",
".",
"_cwd",
"=",
"path",
".",
"posix",
".",
"resolve",
"(",
"cwd",
")",
";",
"}",
"return",
"this",
".",
"_cwd",
";",
"}",
"env",
"(",
"env",
")",
"{",
"if",
"(",
"env",
")",
"{",
"this",
".",
"_env",
"=",
"env",
";",
"}",
"return",
"this",
".",
"_env",
";",
"}",
"output",
"(",
"stdout",
",",
"stderr",
")",
"{",
"if",
"(",
"arguments",
".",
"length",
"===",
"1",
"&&",
"Array",
".",
"isArray",
"(",
"stdout",
")",
")",
"{",
"[",
"stderr",
",",
"stdout",
"]",
"=",
"stdout",
";",
"}",
"if",
"(",
"typeof",
"stdout",
"===",
"'function'",
")",
"{",
"this",
".",
"_outputHandlers",
".",
"stdout",
"=",
"stdout",
";",
"}",
"if",
"(",
"typeof",
"stderr",
"===",
"'function'",
")",
"{",
"this",
".",
"_outputHandlers",
".",
"stderr",
"=",
"stderr",
";",
"}",
"return",
"this",
";",
"}",
"execute",
"(",
"opts",
"=",
"{",
"}",
")",
"{",
"this",
".",
"output",
"(",
"opts",
".",
"stdoutHandler",
"||",
"this",
".",
"_outputHandlers",
".",
"stdout",
",",
"opts",
".",
"stderrHandler",
"||",
"this",
".",
"_outputHandlers",
".",
"stderr",
")",
";",
"const",
"promise",
"=",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"const",
"cmdProc",
"=",
"spawn",
"(",
"this",
".",
"executable",
"(",
")",
",",
"this",
".",
"args",
"(",
")",
",",
"{",
"cwd",
":",
"this",
".",
"_cwd",
",",
"env",
":",
"this",
".",
"_env",
",",
"shell",
":",
"true",
"}",
")",
";",
"cmdProc",
".",
"stdout",
".",
"on",
"(",
"'data'",
",",
"this",
".",
"_outputHandlers",
".",
"stdout",
")",
";",
"cmdProc",
".",
"stderr",
".",
"on",
"(",
"'data'",
",",
"this",
".",
"_outputHandlers",
".",
"stderr",
")",
";",
"cmdProc",
".",
"on",
"(",
"'error'",
",",
"reject",
")",
";",
"cmdProc",
".",
"on",
"(",
"'close'",
",",
"code",
"=>",
"{",
"if",
"(",
"code",
")",
"{",
"let",
"errorObj",
"=",
"new",
"Error",
"(",
"`",
"${",
"code",
"}",
"`",
")",
";",
"errorObj",
".",
"code",
"=",
"code",
";",
"return",
"reject",
"(",
"errorObj",
")",
";",
"}",
"resolve",
"(",
"code",
")",
";",
"}",
")",
";",
"}",
")",
".",
"catch",
"(",
"err",
"=>",
"{",
"return",
"Promise",
".",
"reject",
"(",
"err",
")",
";",
"}",
")",
";",
"return",
"promise",
";",
"}",
"flags",
"(",
"flags",
")",
"{",
"this",
".",
"setFlags",
"(",
"flags",
")",
";",
"}",
"}"
] |
Rsync is a wrapper class to configure and execute an `rsync` command
in a fluent and convenient way.
|
[
"Rsync",
"is",
"a",
"wrapper",
"class",
"to",
"configure",
"and",
"execute",
"an",
"`",
"rsync",
"`",
"command",
"in",
"a",
"fluent",
"and",
"convenient",
"way",
"."
] |
[
"// executable",
"// source(s) and destination",
"// ordered list of file patterns to include/exclude",
"// options",
"// output callbacks",
"// Allow child_process.spawn env overriding",
"/**\n * Set an option.\n * @param {string} option - Option name\n * @param {*} [value] - Whatever value\n * @return {Rsync}\n */",
"/**\n * Unset an option.\n * @param {string} option - Option name\n * @return {Rsync}\n */",
"/**\n * Sets an Array of flags or a string of flags to `true`\n * @param {string|...string|string[]|...string[]} flags - Flags to set to\n * `true`\n * @returns {Rsync}\n * @example\n * rsync.setFlags('avz')\n * // equivalent to:\n * rsync.setFlags(['a', 'v', 'z'])\n * // and:\n * rsync.setFlags('a', 'v', 'z')\n */",
"/**\n * Sets an Array of flags or a string of flags to `false`\n * @param {string|...string|string[]|...string[]} flags - Flags to set to\n * `false`\n * @returns {Rsync}\n * @example\n * rsync.unsetFlags('avz')\n * // equivalent to:\n * rsync.unsetFlags(['a', 'v', 'z'])\n * // and:\n * rsync.unsetFlags('a', 'v', 'z')\n */",
"/**\n * Check if an option is set.\n * @param {string} option\n * @return {boolean}\n */",
"/**\n * Get an option by name.\n * @param {string} name - Option name\n * @return {*}\n */",
"/**\n * Register a list of file patterns to include/exclude in the transfer.\n * Patterns can be registered as an array of Strings or Objects.\n *\n * When registering a pattern as a string it must be prefixed with a `+` or\n * `-` sign to signal include or exclude for the pattern. The sign will be\n * stripped of and the pattern will be added to the ordered pattern list.\n *\n * When registering the pattern as an Object it must contain the `action` and\n * `pattern` keys where `action` contains the `+` or `-` sign and the\n * `pattern` key contains the file pattern, without the `+` or `-` sign.\n *\n * @example\n * // on an existing rsync object\n * rsync.patterns(['-docs', { action: '+', pattern: '/subdir/*.py' }]);\n *\n * // using Rsync.build for a new rsync object\n * rsync = Rsync.build({\n * ...\n * patterns: [ '-docs', { action: '+', pattern: '/subdir/*.py' }]\n * ...\n * })\n *\n * @param {Array} patterns\n * @return {Rsync}\n */",
"// Check if the pattern is an include or exclude",
"/**\n * Exclude a file pattern from transfer. The pattern will be appended to the\n * ordered list of patterns for the rsync command.\n *\n * @param {...string|...string[]} patterns\n * @return {Rsync}\n */",
"/**\n * Include a file pattern for transfer. The pattern will be appended to the\n * ordered list of patterns for the rsync command.\n *\n * @param {string|Array} patterns\n * @return {Rsync}\n */",
"/**\n * Get the command that is going to be executed.\n * @return {string}\n */",
"/**\n * Get the arguments for the rsync command.\n * @return {Array}\n */",
"// Gathered arguments",
"// Add options. Short options (one letter) without values are gathered",
"// together. Long options have a value but can also be a single letter.",
"// Split long and short options",
"// Add combined short options if any are present",
"// Add long options if any are present",
"// Add includes/excludes in order",
"// Add sources",
"// Add destination",
"/**\n * Get and set rsync process cwd directory.\n *\n * @param {string} [cwd] Directory path relative to current process directory.\n * @return {string} Return current _cwd.\n */",
"/**\n * Get and set rsync process environment variables\n *\n * @param {string} [env] Environment variables\n * @return {string} Return current _env.\n */",
"/**\n * Register an output handlers for the commands stdout and stderr streams.\n * These functions will be called once data is streamed on one of the output\n * buffers when the command is executed using `execute`.\n *\n * Only one callback function can be registered for each output stream.\n * Previously registered callbacks will be overridden.\n *\n * @param {Function} stdout - Callback Function for stdout `data` event\n * @param {Function} stderr - Callback Function for stderr `data` event\n * @return {Rsync}\n */",
"// Check for single argument so the method can be used with Rsync.build",
"/**\n * Execute the rsync command.\n *\n * The callback function is called with an Error object (or null when there\n * was none), the exit code from the executed command and the executed\n * command as a string.\n *\n * When stdoutHandler and stderrHandler functions are provided they will be\n * used to stream data from stdout and stderr directly without buffering.\n *\n * @param {Object} [opts] Options\n * @param {Function} [opts.stdoutHandler] Called on each chunk received from\n * stdout\n * @param {Function} [opts.stderrHandler] - Called on each chunk received from\n * stdout\n * @param {Function} [callback] - Node-style callback. If present, return the\n * `ChildProcess` object, otherwise return a `Promise`.\n * @returns {Promise<void>|ChildProcess}\n */",
"// Register output handlers",
"// use shell: true because spawn screws up quotes without it",
"/**\n * @deprecated\n */",
"// flags () {",
"// throw new Error('flags() is deprecated; use setFlags() or unsetFlags() instead');",
"// }"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 26
| 2,689
| 348
|
37762c5ad3a16bf313df79991b2c4c3ab55febb3
|
Guillergood/CogniMobileApp
|
app/src/main/java/ugr/gbv/cognimobile/qr_reader/ReadQR.java
|
[
"MIT"
] |
Java
|
ReadQR
|
/**
* Class to read a QR
* Retrieved from AWARE
*
* @see <a href="https://github.com/denzilferreira/aware-client/blob/master/aware-phone/src/main/java/com/aware/phone/ui/Aware_QRCode.java">https://github.com/denzilferreira/aware-client/blob/master/aware-phone/src/main/java/com/aware/phone/ui/Aware_QRCode.java</a>
* Created by denzil on 27/10/15.
*/
|
Class to read a QR
Retrieved from AWARE
|
[
"Class",
"to",
"read",
"a",
"QR",
"Retrieved",
"from",
"AWARE"
] |
public class ReadQR extends Activity implements ZBarScannerView.ResultHandler {
private ZBarScannerView mScannerView;
public static final String ACTIVITY_LINK_ACTION = "activityToLink";
public static final String INTENT_ACTION_LABEL = "action";
public static final String INTENT_LINK_LABEL = "link";
private static final int LINK_CODE = 2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mScannerView = new ZBarScannerView(this);
LinearLayout main = new LinearLayout(this);
main.setOrientation(LinearLayout.VERTICAL);
main.setBackgroundColor(getResources().getColor(R.color.black,getTheme()));
MaterialButton button = new MaterialButton(this);
button.setText(R.string.enter_link);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
button.setLayoutParams(layoutParams);
button.setOnClickListener(v -> goToActivityWrittenLink());
ListView list = new ListView(this);
list.setId(android.R.id.list);
list.setVisibility(View.GONE);
button.setId(View.generateViewId());
button.setVisibility(View.VISIBLE);
main.addView(button);
main.addView(mScannerView);
main.addView(list);
setContentView(main);
}
@Override
protected void onResume() {
super.onResume();
mScannerView.setResultHandler(this);
mScannerView.startCamera();
}
@Override
protected void onPause() {
super.onPause();
mScannerView.stopCamera();
mScannerView.stopCameraPreview();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
//Zbar QRCode handler
@Override
public void handleResult(Result result) {
if(result.getContents() != null){
Intent data = getIntent();
if(!result.getContents().equals(INTENT_LINK_LABEL)) {
data.putExtra(INTENT_LINK_LABEL, result.getContents());
setResult(RESULT_OK, data);
}
else{
setResult(RESULT_CANCELED);
}
}
else{
setResult(RESULT_CANCELED);
}
finish();
}
private void goToActivityWrittenLink() {
Intent intent = new Intent(this, WriteTestLink.class);
startActivityForResult(intent, LINK_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == LINK_CODE) {
Result result = new Result();
if (resultCode == RESULT_OK && data != null) {
result.setContents(data.getStringExtra(INTENT_LINK_LABEL));
}
else{
result.setContents(INTENT_LINK_LABEL);
}
handleResult(result);
}
finish();
}
}
|
[
"public",
"class",
"ReadQR",
"extends",
"Activity",
"implements",
"ZBarScannerView",
".",
"ResultHandler",
"{",
"private",
"ZBarScannerView",
"mScannerView",
";",
"public",
"static",
"final",
"String",
"ACTIVITY_LINK_ACTION",
"=",
"\"",
"activityToLink",
"\"",
";",
"public",
"static",
"final",
"String",
"INTENT_ACTION_LABEL",
"=",
"\"",
"action",
"\"",
";",
"public",
"static",
"final",
"String",
"INTENT_LINK_LABEL",
"=",
"\"",
"link",
"\"",
";",
"private",
"static",
"final",
"int",
"LINK_CODE",
"=",
"2",
";",
"@",
"Override",
"protected",
"void",
"onCreate",
"(",
"Bundle",
"savedInstanceState",
")",
"{",
"super",
".",
"onCreate",
"(",
"savedInstanceState",
")",
";",
"mScannerView",
"=",
"new",
"ZBarScannerView",
"(",
"this",
")",
";",
"LinearLayout",
"main",
"=",
"new",
"LinearLayout",
"(",
"this",
")",
";",
"main",
".",
"setOrientation",
"(",
"LinearLayout",
".",
"VERTICAL",
")",
";",
"main",
".",
"setBackgroundColor",
"(",
"getResources",
"(",
")",
".",
"getColor",
"(",
"R",
".",
"color",
".",
"black",
",",
"getTheme",
"(",
")",
")",
")",
";",
"MaterialButton",
"button",
"=",
"new",
"MaterialButton",
"(",
"this",
")",
";",
"button",
".",
"setText",
"(",
"R",
".",
"string",
".",
"enter_link",
")",
";",
"LinearLayout",
".",
"LayoutParams",
"layoutParams",
"=",
"new",
"LinearLayout",
".",
"LayoutParams",
"(",
"ViewGroup",
".",
"LayoutParams",
".",
"MATCH_PARENT",
",",
"ViewGroup",
".",
"LayoutParams",
".",
"WRAP_CONTENT",
")",
";",
"button",
".",
"setLayoutParams",
"(",
"layoutParams",
")",
";",
"button",
".",
"setOnClickListener",
"(",
"v",
"->",
"goToActivityWrittenLink",
"(",
")",
")",
";",
"ListView",
"list",
"=",
"new",
"ListView",
"(",
"this",
")",
";",
"list",
".",
"setId",
"(",
"android",
".",
"R",
".",
"id",
".",
"list",
")",
";",
"list",
".",
"setVisibility",
"(",
"View",
".",
"GONE",
")",
";",
"button",
".",
"setId",
"(",
"View",
".",
"generateViewId",
"(",
")",
")",
";",
"button",
".",
"setVisibility",
"(",
"View",
".",
"VISIBLE",
")",
";",
"main",
".",
"addView",
"(",
"button",
")",
";",
"main",
".",
"addView",
"(",
"mScannerView",
")",
";",
"main",
".",
"addView",
"(",
"list",
")",
";",
"setContentView",
"(",
"main",
")",
";",
"}",
"@",
"Override",
"protected",
"void",
"onResume",
"(",
")",
"{",
"super",
".",
"onResume",
"(",
")",
";",
"mScannerView",
".",
"setResultHandler",
"(",
"this",
")",
";",
"mScannerView",
".",
"startCamera",
"(",
")",
";",
"}",
"@",
"Override",
"protected",
"void",
"onPause",
"(",
")",
"{",
"super",
".",
"onPause",
"(",
")",
";",
"mScannerView",
".",
"stopCamera",
"(",
")",
";",
"mScannerView",
".",
"stopCameraPreview",
"(",
")",
";",
"}",
"@",
"Override",
"protected",
"void",
"onDestroy",
"(",
")",
"{",
"super",
".",
"onDestroy",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"void",
"handleResult",
"(",
"Result",
"result",
")",
"{",
"if",
"(",
"result",
".",
"getContents",
"(",
")",
"!=",
"null",
")",
"{",
"Intent",
"data",
"=",
"getIntent",
"(",
")",
";",
"if",
"(",
"!",
"result",
".",
"getContents",
"(",
")",
".",
"equals",
"(",
"INTENT_LINK_LABEL",
")",
")",
"{",
"data",
".",
"putExtra",
"(",
"INTENT_LINK_LABEL",
",",
"result",
".",
"getContents",
"(",
")",
")",
";",
"setResult",
"(",
"RESULT_OK",
",",
"data",
")",
";",
"}",
"else",
"{",
"setResult",
"(",
"RESULT_CANCELED",
")",
";",
"}",
"}",
"else",
"{",
"setResult",
"(",
"RESULT_CANCELED",
")",
";",
"}",
"finish",
"(",
")",
";",
"}",
"private",
"void",
"goToActivityWrittenLink",
"(",
")",
"{",
"Intent",
"intent",
"=",
"new",
"Intent",
"(",
"this",
",",
"WriteTestLink",
".",
"class",
")",
";",
"startActivityForResult",
"(",
"intent",
",",
"LINK_CODE",
")",
";",
"}",
"@",
"Override",
"protected",
"void",
"onActivityResult",
"(",
"int",
"requestCode",
",",
"int",
"resultCode",
",",
"Intent",
"data",
")",
"{",
"if",
"(",
"requestCode",
"==",
"LINK_CODE",
")",
"{",
"Result",
"result",
"=",
"new",
"Result",
"(",
")",
";",
"if",
"(",
"resultCode",
"==",
"RESULT_OK",
"&&",
"data",
"!=",
"null",
")",
"{",
"result",
".",
"setContents",
"(",
"data",
".",
"getStringExtra",
"(",
"INTENT_LINK_LABEL",
")",
")",
";",
"}",
"else",
"{",
"result",
".",
"setContents",
"(",
"INTENT_LINK_LABEL",
")",
";",
"}",
"handleResult",
"(",
"result",
")",
";",
"}",
"finish",
"(",
")",
";",
"}",
"}"
] |
Class to read a QR
Retrieved from AWARE
|
[
"Class",
"to",
"read",
"a",
"QR",
"Retrieved",
"from",
"AWARE"
] |
[
"//Zbar QRCode handler"
] |
[
{
"param": "Activity",
"type": null
},
{
"param": "ZBarScannerView.ResultHandler",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "Activity",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "ZBarScannerView.ResultHandler",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 14
| 545
| 108
|
8d5144c9cebca38ebaed9adc6c98b9a4974fb10d
|
chetan/jeweler
|
lib/jeweler/rubyforge_tasks.rb
|
[
"MIT"
] |
Ruby
|
RubyforgeTasks
|
# Rake tasks for putting a Jeweler gem on Rubyforge.
#
# Jeweler::Tasks.new needs to be used before this.
#
# Basic usage:
#
# Jeweler::RubyforgeTasks.new
#
# Easy enough, right?
#
# There are a few options you can tweak:
#
# * project: the rubyforge project to operate on. This defaults to whatever you specified in your gemspec. Defaults to your gem name.
# * remote_doc_path: the place to upload docs to on Rubyforge under /var/www/gforge-projects/#{project}/
#
# See also http://wiki.github.com/technicalpickles/jeweler/rubyforge
|
Rake tasks for putting a Jeweler gem on Rubyforge.
Jeweler::Tasks.new needs to be used before this.
Basic usage.
There are a few options you can tweak.
the rubyforge project to operate on. This defaults to whatever you specified in your gemspec. Defaults to your gem name.
remote_doc_path: the place to upload docs to on Rubyforge under /var/www/gforge-projects/#{project}
|
[
"Rake",
"tasks",
"for",
"putting",
"a",
"Jeweler",
"gem",
"on",
"Rubyforge",
".",
"Jeweler",
"::",
"Tasks",
".",
"new",
"needs",
"to",
"be",
"used",
"before",
"this",
".",
"Basic",
"usage",
".",
"There",
"are",
"a",
"few",
"options",
"you",
"can",
"tweak",
".",
"the",
"rubyforge",
"project",
"to",
"operate",
"on",
".",
"This",
"defaults",
"to",
"whatever",
"you",
"specified",
"in",
"your",
"gemspec",
".",
"Defaults",
"to",
"your",
"gem",
"name",
".",
"remote_doc_path",
":",
"the",
"place",
"to",
"upload",
"docs",
"to",
"on",
"Rubyforge",
"under",
"/",
"var",
"/",
"www",
"/",
"gforge",
"-",
"projects",
"/",
"#",
"{",
"project",
"}"
] |
class RubyforgeTasks < ::Rake::TaskLib
# The RubyForge project to interact with. Defaults to whatever is in your jeweler gemspec.
attr_accessor :project
# The path to upload docs to. It is relative to /var/www/gforge-projects/#{project}/, and defaults to your gemspec's name
attr_accessor :remote_doc_path
# Task to be used for generating documentation, before they are uploaded. Defaults to rdoc.
attr_accessor :doc_task
attr_accessor :jeweler
def initialize
yield self if block_given?
$stderr.puts "Releasing gems to Rubyforge is deprecated. See details at http://wiki.github.com/technicalpickles/jeweler/migrating-from-releasing-gems-to-rubyforge"
define
end
def jeweler
@jeweler ||= Rake.application.jeweler
end
def remote_doc_path
@remote_doc_path ||= jeweler.gemspec.name
end
def project
@project ||= jeweler.gemspec.rubyforge_project
end
def define
namespace :rubyforge do
namespace :release do
desc "Release the current gem version to RubyForge."
task :gem do
$stderr.puts "DEPRECATION: Releasing gems to RubyForge is deprecated. You should see about releasing to Gemcutter instead: http://wiki.github.com/technicalpickles/jeweler/gemcutter"
end
if publish_documentation?
desc "Publish docs to RubyForge."
task :docs => doc_task do
config = YAML.load(
File.read(File.expand_path('~/.rubyforge/user-config.yml'))
)
host = "#{config['username']}@rubyforge.org"
remote_dir = "/var/www/gforge-projects/#{project}/#{remote_doc_path}"
local_dir = case self.doc_task.to_sym
when :rdoc then 'rdoc'
when :yardoc then 'doc'
when 'doc:app'.to_sym then 'doc/app'
else
raise "Unsure what to run to generate documentation. Please set doc_task and re-run."
end
sh %{rsync --archive --verbose --delete #{local_dir}/ #{host}:#{remote_dir}}
end
end
end
if publish_documentation?
desc "Release RDoc documentation to RubyForge"
task :release => "rubyforge:release:docs"
end
end
task :release => 'rubyforge:release'
end
def publish_documentation?
! (doc_task == false || doc_task == :none)
end
end
|
[
"class",
"RubyforgeTasks",
"<",
"::",
"Rake",
"::",
"TaskLib",
"attr_accessor",
":project",
"attr_accessor",
":remote_doc_path",
"attr_accessor",
":doc_task",
"attr_accessor",
":jeweler",
"def",
"initialize",
"yield",
"self",
"if",
"block_given?",
"$stderr",
".",
"puts",
"\"Releasing gems to Rubyforge is deprecated. See details at http://wiki.github.com/technicalpickles/jeweler/migrating-from-releasing-gems-to-rubyforge\"",
"define",
"end",
"def",
"jeweler",
"@jeweler",
"||=",
"Rake",
".",
"application",
".",
"jeweler",
"end",
"def",
"remote_doc_path",
"@remote_doc_path",
"||=",
"jeweler",
".",
"gemspec",
".",
"name",
"end",
"def",
"project",
"@project",
"||=",
"jeweler",
".",
"gemspec",
".",
"rubyforge_project",
"end",
"def",
"define",
"namespace",
":rubyforge",
"do",
"namespace",
":release",
"do",
"desc",
"\"Release the current gem version to RubyForge.\"",
"task",
":gem",
"do",
"$stderr",
".",
"puts",
"\"DEPRECATION: Releasing gems to RubyForge is deprecated. You should see about releasing to Gemcutter instead: http://wiki.github.com/technicalpickles/jeweler/gemcutter\"",
"end",
"if",
"publish_documentation?",
"desc",
"\"Publish docs to RubyForge.\"",
"task",
":docs",
"=>",
"doc_task",
"do",
"config",
"=",
"YAML",
".",
"load",
"(",
"File",
".",
"read",
"(",
"File",
".",
"expand_path",
"(",
"'~/.rubyforge/user-config.yml'",
")",
")",
")",
"host",
"=",
"\"#{config['username']}@rubyforge.org\"",
"remote_dir",
"=",
"\"/var/www/gforge-projects/#{project}/#{remote_doc_path}\"",
"local_dir",
"=",
"case",
"self",
".",
"doc_task",
".",
"to_sym",
"when",
":rdoc",
"then",
"'rdoc'",
"when",
":yardoc",
"then",
"'doc'",
"when",
"'doc:app'",
".",
"to_sym",
"then",
"'doc/app'",
"else",
"raise",
"\"Unsure what to run to generate documentation. Please set doc_task and re-run.\"",
"end",
"sh",
"%{rsync --archive --verbose --delete #{local_dir}/ #{host}:#{remote_dir}}",
"end",
"end",
"end",
"if",
"publish_documentation?",
"desc",
"\"Release RDoc documentation to RubyForge\"",
"task",
":release",
"=>",
"\"rubyforge:release:docs\"",
"end",
"end",
"task",
":release",
"=>",
"'rubyforge:release'",
"end",
"def",
"publish_documentation?",
"!",
"(",
"doc_task",
"==",
"false",
"||",
"doc_task",
"==",
":none",
")",
"end",
"end"
] |
Rake tasks for putting a Jeweler gem on Rubyforge.
|
[
"Rake",
"tasks",
"for",
"putting",
"a",
"Jeweler",
"gem",
"on",
"Rubyforge",
"."
] |
[
"# The RubyForge project to interact with. Defaults to whatever is in your jeweler gemspec.",
"# The path to upload docs to. It is relative to /var/www/gforge-projects/#{project}/, and defaults to your gemspec's name",
"# Task to be used for generating documentation, before they are uploaded. Defaults to rdoc."
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 24
| 576
| 141
|
112aa7a0e8fd301463bc3823d1478f146bcca67f
|
mellester/vue-services
|
src/creators/editpagecreator.js
|
[
"MIT"
] |
JavaScript
|
EditPageCreator
|
/**
* @typedef {import('./basecreator').BaseCreator} BaseCreator
* @typedef {import('../services/error').ErrorService} ErrorService
* @typedef {import('../services/translator').TranslatorService} TranslatorService
* @typedef {import('../services/router').RouterService} RouterService
* @typedef {import('vue').CreateElement} CreateElement
* @typedef {import('vue').VNode} VNode
* @typedef {import('vue').Component} Component
*
* @typedef {Object} EditPageCSSClasses
* @property {String[]} container
*/
|
@typedef {Object} EditPageCSSClasses
@property {String[]} container
|
[
"@typedef",
"{",
"Object",
"}",
"EditPageCSSClasses",
"@property",
"{",
"String",
"[]",
"}",
"container"
] |
class EditPageCreator {
/**
* @param {BaseCreator} baseCreator
* @param {ErrorService} errorService
* @param {TranslatorService} translatorService
*/
constructor(baseCreator, errorService, translatorService, routerService) {
/** @type {CreateElement} */
this._h;
this._errorService = errorService;
this._translatorService = translatorService;
this._baseCreator = baseCreator;
this._routerService = routerService;
}
// prettier-ignore
/** @param {CreateElement} h */
set h(h) { this._h = h; }
/**
* Generate an edit page
* @param {Component} form the form to create stuff with
* @param {()=>Object<string,any} getter the getter to get the instance from the store
* @param {String} subject the subject for which to create something for
* @param {Function} updateAction the action to send the updated model to the backend
* @param {Function} [destroyAction] the optional destroyAction, will attach a destroy button with this action
* @param {Function} [showAction] the optional showAction, will get data from the server if given
* @param {String|String[]} [titleItemProperty] the optional titleItemProperty, will show title based on the given property. If nothing is given then the creator will try to resolve a title
* @param {EditPageCSSClasses} [cssClasses] the optional css classes to override the basic classes
*/
create(form, getter, subject, updateAction, destroyAction, showAction, titleItemProperty, cssClasses) {
// define pageCreator here, cause this context get's lost in the return object
const pageCreator = this;
return {
name: `edit-${subject}`,
computed: {
item() {
const item = getter();
if (item) this.editable = JSON.parse(JSON.stringify(item));
return item;
},
},
data() {
return {editable: {}};
},
render(h) {
// TODO :: notFoundMessage should be clear
if (!this.item) return h('div', ['Dit is nog niet gevonden']);
const containerChildren = [
pageCreator.createEditPageTitle(this.item, titleItemProperty),
pageCreator.createForm(form, this.editable, updateAction),
];
if (destroyAction) {
// TODO :: move to method, when there are more b-links
// TODO :: uses Bootstrap-Vue element
containerChildren.push(
h(
'b-link',
{
class: 'text-danger',
on: {click: destroyAction},
},
[`${pageCreator._translatorService.getCapitalizedSingular(subject)} verwijderen`]
)
);
}
return pageCreator._baseCreator.container(
containerChildren,
cssClasses ? cssClasses.container : undefined
);
},
mounted() {
pageCreator.checkQuery(this.editable);
if (showAction) showAction();
},
};
}
/**
* @param {Object<string,any>} item the item for which to show the title
* @param {String|String[]} [titleItemProperty] the optional titleItemProperty, will show title based on the given property. If nothing is given then the creator will try to resolve a title
*/
createEditPageTitle(item, titleItemProperty) {
const title = this.createTitleFromItemProperties(item, titleItemProperty);
if (!title) return this._baseCreator.titleRow('Aanpassen');
return this._baseCreator.titleRow(title + ' aanpassen');
}
/**
* @param {Object<string,any>} item the item for which to show the title
* @param {String|String[]} [titleItemProperty] the optional titleItemProperty, will show title based on the given property. If nothing is given then the creator will try to resolve a title
*/
createTitleFromItemProperties(item, titleItemProperty) {
// if titleItemProperty is given, create title based on that
if (titleItemProperty) {
if (Array.isArray(titleItemProperty)) {
return titleItemProperty.map(prop => item[prop]).join(' ');
}
return item[titleItemProperty];
}
// if titleItemProperty is not given, try to resolve it with the most common properties
if (item.firstname) return `${item.firstname} ${item.lastname}`;
return item.name || item.title;
}
/**
* @param {Component} form
* @param {Object<string,any>} editable
* @param {(item:Object<string,any) => void} action
*/
createForm(form, editable, action) {
return this._h('div', {class: 'row mt-3'}, [
this._baseCreator.col([
this._h(form, {
props: {
editable,
errors: this._errorService.getErrors(),
},
on: {submit: () => action(editable)},
}),
]),
]);
}
/** @param {Object<string,any>} editable */
checkQuery(editable) {
const query = this._routerService.query;
if (!Object.keys(query).length) return;
for (const key in query) {
if (editable[key]) {
editable[key] = query[key];
}
}
}
}
|
[
"class",
"EditPageCreator",
"{",
"constructor",
"(",
"baseCreator",
",",
"errorService",
",",
"translatorService",
",",
"routerService",
")",
"{",
"this",
".",
"_h",
";",
"this",
".",
"_errorService",
"=",
"errorService",
";",
"this",
".",
"_translatorService",
"=",
"translatorService",
";",
"this",
".",
"_baseCreator",
"=",
"baseCreator",
";",
"this",
".",
"_routerService",
"=",
"routerService",
";",
"}",
"set",
"h",
"(",
"h",
")",
"{",
"this",
".",
"_h",
"=",
"h",
";",
"}",
"create",
"(",
"form",
",",
"getter",
",",
"subject",
",",
"updateAction",
",",
"destroyAction",
",",
"showAction",
",",
"titleItemProperty",
",",
"cssClasses",
")",
"{",
"const",
"pageCreator",
"=",
"this",
";",
"return",
"{",
"name",
":",
"`",
"${",
"subject",
"}",
"`",
",",
"computed",
":",
"{",
"item",
"(",
")",
"{",
"const",
"item",
"=",
"getter",
"(",
")",
";",
"if",
"(",
"item",
")",
"this",
".",
"editable",
"=",
"JSON",
".",
"parse",
"(",
"JSON",
".",
"stringify",
"(",
"item",
")",
")",
";",
"return",
"item",
";",
"}",
",",
"}",
",",
"data",
"(",
")",
"{",
"return",
"{",
"editable",
":",
"{",
"}",
"}",
";",
"}",
",",
"render",
"(",
"h",
")",
"{",
"if",
"(",
"!",
"this",
".",
"item",
")",
"return",
"h",
"(",
"'div'",
",",
"[",
"'Dit is nog niet gevonden'",
"]",
")",
";",
"const",
"containerChildren",
"=",
"[",
"pageCreator",
".",
"createEditPageTitle",
"(",
"this",
".",
"item",
",",
"titleItemProperty",
")",
",",
"pageCreator",
".",
"createForm",
"(",
"form",
",",
"this",
".",
"editable",
",",
"updateAction",
")",
",",
"]",
";",
"if",
"(",
"destroyAction",
")",
"{",
"containerChildren",
".",
"push",
"(",
"h",
"(",
"'b-link'",
",",
"{",
"class",
":",
"'text-danger'",
",",
"on",
":",
"{",
"click",
":",
"destroyAction",
"}",
",",
"}",
",",
"[",
"`",
"${",
"pageCreator",
".",
"_translatorService",
".",
"getCapitalizedSingular",
"(",
"subject",
")",
"}",
"`",
"]",
")",
")",
";",
"}",
"return",
"pageCreator",
".",
"_baseCreator",
".",
"container",
"(",
"containerChildren",
",",
"cssClasses",
"?",
"cssClasses",
".",
"container",
":",
"undefined",
")",
";",
"}",
",",
"mounted",
"(",
")",
"{",
"pageCreator",
".",
"checkQuery",
"(",
"this",
".",
"editable",
")",
";",
"if",
"(",
"showAction",
")",
"showAction",
"(",
")",
";",
"}",
",",
"}",
";",
"}",
"createEditPageTitle",
"(",
"item",
",",
"titleItemProperty",
")",
"{",
"const",
"title",
"=",
"this",
".",
"createTitleFromItemProperties",
"(",
"item",
",",
"titleItemProperty",
")",
";",
"if",
"(",
"!",
"title",
")",
"return",
"this",
".",
"_baseCreator",
".",
"titleRow",
"(",
"'Aanpassen'",
")",
";",
"return",
"this",
".",
"_baseCreator",
".",
"titleRow",
"(",
"title",
"+",
"' aanpassen'",
")",
";",
"}",
"createTitleFromItemProperties",
"(",
"item",
",",
"titleItemProperty",
")",
"{",
"if",
"(",
"titleItemProperty",
")",
"{",
"if",
"(",
"Array",
".",
"isArray",
"(",
"titleItemProperty",
")",
")",
"{",
"return",
"titleItemProperty",
".",
"map",
"(",
"prop",
"=>",
"item",
"[",
"prop",
"]",
")",
".",
"join",
"(",
"' '",
")",
";",
"}",
"return",
"item",
"[",
"titleItemProperty",
"]",
";",
"}",
"if",
"(",
"item",
".",
"firstname",
")",
"return",
"`",
"${",
"item",
".",
"firstname",
"}",
"${",
"item",
".",
"lastname",
"}",
"`",
";",
"return",
"item",
".",
"name",
"||",
"item",
".",
"title",
";",
"}",
"createForm",
"(",
"form",
",",
"editable",
",",
"action",
")",
"{",
"return",
"this",
".",
"_h",
"(",
"'div'",
",",
"{",
"class",
":",
"'row mt-3'",
"}",
",",
"[",
"this",
".",
"_baseCreator",
".",
"col",
"(",
"[",
"this",
".",
"_h",
"(",
"form",
",",
"{",
"props",
":",
"{",
"editable",
",",
"errors",
":",
"this",
".",
"_errorService",
".",
"getErrors",
"(",
")",
",",
"}",
",",
"on",
":",
"{",
"submit",
":",
"(",
")",
"=>",
"action",
"(",
"editable",
")",
"}",
",",
"}",
")",
",",
"]",
")",
",",
"]",
")",
";",
"}",
"checkQuery",
"(",
"editable",
")",
"{",
"const",
"query",
"=",
"this",
".",
"_routerService",
".",
"query",
";",
"if",
"(",
"!",
"Object",
".",
"keys",
"(",
"query",
")",
".",
"length",
")",
"return",
";",
"for",
"(",
"const",
"key",
"in",
"query",
")",
"{",
"if",
"(",
"editable",
"[",
"key",
"]",
")",
"{",
"editable",
"[",
"key",
"]",
"=",
"query",
"[",
"key",
"]",
";",
"}",
"}",
"}",
"}"
] |
@typedef {import('./basecreator').BaseCreator} BaseCreator
@typedef {import('../services/error').ErrorService} ErrorService
@typedef {import('../services/translator').TranslatorService} TranslatorService
@typedef {import('../services/router').RouterService} RouterService
@typedef {import('vue').CreateElement} CreateElement
@typedef {import('vue').VNode} VNode
@typedef {import('vue').Component} Component
|
[
"@typedef",
"{",
"import",
"(",
"'",
".",
"/",
"basecreator",
"'",
")",
".",
"BaseCreator",
"}",
"BaseCreator",
"@typedef",
"{",
"import",
"(",
"'",
"..",
"/",
"services",
"/",
"error",
"'",
")",
".",
"ErrorService",
"}",
"ErrorService",
"@typedef",
"{",
"import",
"(",
"'",
"..",
"/",
"services",
"/",
"translator",
"'",
")",
".",
"TranslatorService",
"}",
"TranslatorService",
"@typedef",
"{",
"import",
"(",
"'",
"..",
"/",
"services",
"/",
"router",
"'",
")",
".",
"RouterService",
"}",
"RouterService",
"@typedef",
"{",
"import",
"(",
"'",
"vue",
"'",
")",
".",
"CreateElement",
"}",
"CreateElement",
"@typedef",
"{",
"import",
"(",
"'",
"vue",
"'",
")",
".",
"VNode",
"}",
"VNode",
"@typedef",
"{",
"import",
"(",
"'",
"vue",
"'",
")",
".",
"Component",
"}",
"Component"
] |
[
"/**\n * @param {BaseCreator} baseCreator\n * @param {ErrorService} errorService\n * @param {TranslatorService} translatorService\n */",
"/** @type {CreateElement} */",
"// prettier-ignore",
"/** @param {CreateElement} h */",
"/**\n * Generate an edit page\n * @param {Component} form the form to create stuff with\n * @param {()=>Object<string,any} getter the getter to get the instance from the store\n * @param {String} subject the subject for which to create something for\n * @param {Function} updateAction the action to send the updated model to the backend\n * @param {Function} [destroyAction] the optional destroyAction, will attach a destroy button with this action\n * @param {Function} [showAction] the optional showAction, will get data from the server if given\n * @param {String|String[]} [titleItemProperty] the optional titleItemProperty, will show title based on the given property. If nothing is given then the creator will try to resolve a title\n * @param {EditPageCSSClasses} [cssClasses] the optional css classes to override the basic classes\n */",
"// define pageCreator here, cause this context get's lost in the return object",
"// TODO :: notFoundMessage should be clear",
"// TODO :: move to method, when there are more b-links",
"// TODO :: uses Bootstrap-Vue element",
"/**\n * @param {Object<string,any>} item the item for which to show the title\n * @param {String|String[]} [titleItemProperty] the optional titleItemProperty, will show title based on the given property. If nothing is given then the creator will try to resolve a title\n */",
"/**\n * @param {Object<string,any>} item the item for which to show the title\n * @param {String|String[]} [titleItemProperty] the optional titleItemProperty, will show title based on the given property. If nothing is given then the creator will try to resolve a title\n */",
"// if titleItemProperty is given, create title based on that",
"// if titleItemProperty is not given, try to resolve it with the most common properties",
"/**\n * @param {Component} form\n * @param {Object<string,any>} editable\n * @param {(item:Object<string,any) => void} action\n */",
"/** @param {Object<string,any>} editable */"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 22
| 1,177
| 123
|
e238afb781cc72e6890a047849010be34fc179a7
|
dotnetframeworknewbie/YAFNET
|
yafsrc/Lucene.Net/Lucene.Net/Index/IndexFileNames.cs
|
[
"Apache-2.0"
] |
C#
|
IndexFileNames
|
/// <summary>
/// This class contains useful constants representing filenames and extensions
/// used by lucene, as well as convenience methods for querying whether a file
/// name matches an extension (<see cref="MatchesExtension(string, string)"/>),
/// as well as generating file names from a segment name,
/// generation and extension
/// (<see cref="FileNameFromGeneration(string, string, long)"/>,
/// <see cref="SegmentFileName(string, string, string)"/>).
///
/// <para/><b>NOTE</b>: extensions used by codecs are not
/// listed here. You must interact with the <see cref="Codecs.Codec"/>
/// directly.
/// <para/>
/// @lucene.internal
/// </summary>
|
This class contains useful constants representing filenames and extensions
used by lucene, as well as convenience methods for querying whether a file
name matches an extension (),
as well as generating file names from a segment name,
generation and extension
(,
).
NOTE
directly.
|
[
"This",
"class",
"contains",
"useful",
"constants",
"representing",
"filenames",
"and",
"extensions",
"used",
"by",
"lucene",
"as",
"well",
"as",
"convenience",
"methods",
"for",
"querying",
"whether",
"a",
"file",
"name",
"matches",
"an",
"extension",
"()",
"as",
"well",
"as",
"generating",
"file",
"names",
"from",
"a",
"segment",
"name",
"generation",
"and",
"extension",
"(",
")",
".",
"NOTE",
"directly",
"."
] |
public sealed class IndexFileNames
{
private IndexFileNames()
{
}
public static readonly string SEGMENTS = "segments";
public static readonly string GEN_EXTENSION = "gen";
public static readonly string SEGMENTS_GEN = "segments." + GEN_EXTENSION;
public static readonly string COMPOUND_FILE_EXTENSION = "cfs";
public static readonly string COMPOUND_FILE_ENTRIES_EXTENSION = "cfe";
public static readonly string[] INDEX_EXTENSIONS = new string[] {
COMPOUND_FILE_EXTENSION,
COMPOUND_FILE_ENTRIES_EXTENSION,
GEN_EXTENSION
};
public static string FileNameFromGeneration(string @base, string ext, long gen)
{
if (gen == -1)
{
return null;
}
else if (gen == 0)
{
return SegmentFileName(@base, "", ext);
}
else
{
Debug.Assert(gen > 0);
StringBuilder res = (new StringBuilder(@base.Length + 6 + ext.Length))
.Append(@base).Append('_').Append(gen.ToString(Character.MaxRadix));
if (ext.Length > 0)
{
res.Append('.').Append(ext);
}
return res.ToString();
}
}
public static string SegmentFileName(string segmentName, string segmentSuffix, string ext)
{
if (ext.Length > 0 || segmentSuffix.Length > 0)
{
Debug.Assert(!ext.StartsWith(".", StringComparison.Ordinal));
StringBuilder sb = new StringBuilder(segmentName.Length + 2 + segmentSuffix.Length + ext.Length);
sb.Append(segmentName);
if (segmentSuffix.Length > 0)
{
sb.Append('_').Append(segmentSuffix);
}
if (ext.Length > 0)
{
sb.Append('.').Append(ext);
}
return sb.ToString();
}
else
{
return segmentName;
}
}
public static bool MatchesExtension(string filename, string ext)
{
return filename.EndsWith("." + ext, StringComparison.Ordinal);
}
private static int IndexOfSegmentName(string filename)
{
int idx = filename.IndexOf('_', 1);
if (idx == -1)
{
idx = filename.IndexOf('.');
}
return idx;
}
public static string StripSegmentName(string filename)
{
int idx = IndexOfSegmentName(filename);
if (idx != -1)
{
filename = filename.Substring(idx);
}
return filename;
}
public static string ParseSegmentName(string filename)
{
int idx = IndexOfSegmentName(filename);
if (idx != -1)
{
filename = filename.Substring(0, idx);
}
return filename;
}
public static string StripExtension(string filename)
{
int idx = filename.IndexOf('.');
if (idx != -1)
{
filename = filename.Substring(0, idx);
}
return filename;
}
public static string GetExtension(string filename)
{
int idx = filename.IndexOf('.');
if (idx == -1)
{
return null;
}
else
{
return filename.Substring(idx + 1, filename.Length - (idx + 1));
}
}
public static readonly Regex CODEC_FILE_PATTERN = new Regex("_[a-z0-9]+(_.*)?\\..*", RegexOptions.Compiled);
}
|
[
"public",
"sealed",
"class",
"IndexFileNames",
"{",
"private",
"IndexFileNames",
"(",
")",
"{",
"}",
"public",
"static",
"readonly",
"string",
"SEGMENTS",
"=",
"\"",
"segments",
"\"",
";",
"public",
"static",
"readonly",
"string",
"GEN_EXTENSION",
"=",
"\"",
"gen",
"\"",
";",
"public",
"static",
"readonly",
"string",
"SEGMENTS_GEN",
"=",
"\"",
"segments.",
"\"",
"+",
"GEN_EXTENSION",
";",
"public",
"static",
"readonly",
"string",
"COMPOUND_FILE_EXTENSION",
"=",
"\"",
"cfs",
"\"",
";",
"public",
"static",
"readonly",
"string",
"COMPOUND_FILE_ENTRIES_EXTENSION",
"=",
"\"",
"cfe",
"\"",
";",
"public",
"static",
"readonly",
"string",
"[",
"]",
"INDEX_EXTENSIONS",
"=",
"new",
"string",
"[",
"]",
"{",
"COMPOUND_FILE_EXTENSION",
",",
"COMPOUND_FILE_ENTRIES_EXTENSION",
",",
"GEN_EXTENSION",
"}",
";",
"public",
"static",
"string",
"FileNameFromGeneration",
"(",
"string",
"@base",
",",
"string",
"ext",
",",
"long",
"gen",
")",
"{",
"if",
"(",
"gen",
"==",
"-",
"1",
")",
"{",
"return",
"null",
";",
"}",
"else",
"if",
"(",
"gen",
"==",
"0",
")",
"{",
"return",
"SegmentFileName",
"(",
"@base",
",",
"\"",
"\"",
",",
"ext",
")",
";",
"}",
"else",
"{",
"Debug",
".",
"Assert",
"(",
"gen",
">",
"0",
")",
";",
"StringBuilder",
"res",
"=",
"(",
"new",
"StringBuilder",
"(",
"@base",
".",
"Length",
"+",
"6",
"+",
"ext",
".",
"Length",
")",
")",
".",
"Append",
"(",
"@base",
")",
".",
"Append",
"(",
"'",
"_",
"'",
")",
".",
"Append",
"(",
"gen",
".",
"ToString",
"(",
"Character",
".",
"MaxRadix",
")",
")",
";",
"if",
"(",
"ext",
".",
"Length",
">",
"0",
")",
"{",
"res",
".",
"Append",
"(",
"'",
".",
"'",
")",
".",
"Append",
"(",
"ext",
")",
";",
"}",
"return",
"res",
".",
"ToString",
"(",
")",
";",
"}",
"}",
"public",
"static",
"string",
"SegmentFileName",
"(",
"string",
"segmentName",
",",
"string",
"segmentSuffix",
",",
"string",
"ext",
")",
"{",
"if",
"(",
"ext",
".",
"Length",
">",
"0",
"||",
"segmentSuffix",
".",
"Length",
">",
"0",
")",
"{",
"Debug",
".",
"Assert",
"(",
"!",
"ext",
".",
"StartsWith",
"(",
"\"",
".",
"\"",
",",
"StringComparison",
".",
"Ordinal",
")",
")",
";",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
"segmentName",
".",
"Length",
"+",
"2",
"+",
"segmentSuffix",
".",
"Length",
"+",
"ext",
".",
"Length",
")",
";",
"sb",
".",
"Append",
"(",
"segmentName",
")",
";",
"if",
"(",
"segmentSuffix",
".",
"Length",
">",
"0",
")",
"{",
"sb",
".",
"Append",
"(",
"'",
"_",
"'",
")",
".",
"Append",
"(",
"segmentSuffix",
")",
";",
"}",
"if",
"(",
"ext",
".",
"Length",
">",
"0",
")",
"{",
"sb",
".",
"Append",
"(",
"'",
".",
"'",
")",
".",
"Append",
"(",
"ext",
")",
";",
"}",
"return",
"sb",
".",
"ToString",
"(",
")",
";",
"}",
"else",
"{",
"return",
"segmentName",
";",
"}",
"}",
"public",
"static",
"bool",
"MatchesExtension",
"(",
"string",
"filename",
",",
"string",
"ext",
")",
"{",
"return",
"filename",
".",
"EndsWith",
"(",
"\"",
".",
"\"",
"+",
"ext",
",",
"StringComparison",
".",
"Ordinal",
")",
";",
"}",
"private",
"static",
"int",
"IndexOfSegmentName",
"(",
"string",
"filename",
")",
"{",
"int",
"idx",
"=",
"filename",
".",
"IndexOf",
"(",
"'",
"_",
"'",
",",
"1",
")",
";",
"if",
"(",
"idx",
"==",
"-",
"1",
")",
"{",
"idx",
"=",
"filename",
".",
"IndexOf",
"(",
"'",
".",
"'",
")",
";",
"}",
"return",
"idx",
";",
"}",
"public",
"static",
"string",
"StripSegmentName",
"(",
"string",
"filename",
")",
"{",
"int",
"idx",
"=",
"IndexOfSegmentName",
"(",
"filename",
")",
";",
"if",
"(",
"idx",
"!=",
"-",
"1",
")",
"{",
"filename",
"=",
"filename",
".",
"Substring",
"(",
"idx",
")",
";",
"}",
"return",
"filename",
";",
"}",
"public",
"static",
"string",
"ParseSegmentName",
"(",
"string",
"filename",
")",
"{",
"int",
"idx",
"=",
"IndexOfSegmentName",
"(",
"filename",
")",
";",
"if",
"(",
"idx",
"!=",
"-",
"1",
")",
"{",
"filename",
"=",
"filename",
".",
"Substring",
"(",
"0",
",",
"idx",
")",
";",
"}",
"return",
"filename",
";",
"}",
"public",
"static",
"string",
"StripExtension",
"(",
"string",
"filename",
")",
"{",
"int",
"idx",
"=",
"filename",
".",
"IndexOf",
"(",
"'",
".",
"'",
")",
";",
"if",
"(",
"idx",
"!=",
"-",
"1",
")",
"{",
"filename",
"=",
"filename",
".",
"Substring",
"(",
"0",
",",
"idx",
")",
";",
"}",
"return",
"filename",
";",
"}",
"public",
"static",
"string",
"GetExtension",
"(",
"string",
"filename",
")",
"{",
"int",
"idx",
"=",
"filename",
".",
"IndexOf",
"(",
"'",
".",
"'",
")",
";",
"if",
"(",
"idx",
"==",
"-",
"1",
")",
"{",
"return",
"null",
";",
"}",
"else",
"{",
"return",
"filename",
".",
"Substring",
"(",
"idx",
"+",
"1",
",",
"filename",
".",
"Length",
"-",
"(",
"idx",
"+",
"1",
")",
")",
";",
"}",
"}",
"public",
"static",
"readonly",
"Regex",
"CODEC_FILE_PATTERN",
"=",
"new",
"Regex",
"(",
"\"",
"_[a-z0-9]+(_.*)?",
"\\\\",
"..*",
"\"",
",",
"RegexOptions",
".",
"Compiled",
")",
";",
"}"
] |
This class contains useful constants representing filenames and extensions
used by lucene, as well as convenience methods for querying whether a file
name matches an extension (),
as well as generating file names from a segment name,
generation and extension
(,
).
|
[
"This",
"class",
"contains",
"useful",
"constants",
"representing",
"filenames",
"and",
"extensions",
"used",
"by",
"lucene",
"as",
"well",
"as",
"convenience",
"methods",
"for",
"querying",
"whether",
"a",
"file",
"name",
"matches",
"an",
"extension",
"()",
"as",
"well",
"as",
"generating",
"file",
"names",
"from",
"a",
"segment",
"name",
"generation",
"and",
"extension",
"(",
")",
"."
] |
[
"/// <summary>",
"/// No instance </summary>",
"/// <summary>",
"/// Name of the index segment file </summary>",
"/// <summary>",
"/// Extension of gen file </summary>",
"/// <summary>",
"/// Name of the generation reference file name </summary>",
"/// <summary>",
"/// Extension of compound file </summary>",
"/// <summary>",
"/// Extension of compound file entries </summary>",
"/// <summary>",
"/// This array contains all filename extensions used by",
"/// Lucene's index files, with one exception, namely the",
"/// extension made up from <c>.s</c> + a number.",
"/// Also note that Lucene's <c>segments_N</c> files",
"/// do not have any filename extension.",
"/// </summary>",
"/// <summary>",
"/// Computes the full file name from base, extension and generation. If the",
"/// generation is -1, the file name is <c>null</c>. If it's 0, the file name is",
"/// <base>.<ext>. If it's > 0, the file name is",
"/// <base>_<gen>.<ext>.",
"/// <para/>",
"/// <b>NOTE:</b> .<ext> is added to the name only if <c>ext</c> is",
"/// not an empty string.",
"/// </summary>",
"/// <param name=\"base\"> main part of the file name </param>",
"/// <param name=\"ext\"> extension of the filename </param>",
"/// <param name=\"gen\"> generation </param>",
"// The '6' part in the length is: 1 for '.', 1 for '_' and 4 as estimate",
"// to the gen length as string (hopefully an upper limit so SB won't",
"// expand in the middle.",
"/// <summary>",
"/// Returns a file name that includes the given segment name, your own custom",
"/// name and extension. The format of the filename is:",
"/// <segmentName>(_<name>)(.<ext>).",
"/// <para/>",
"/// <b>NOTE:</b> .<ext> is added to the result file name only if",
"/// <code>ext</code> is not empty.",
"/// <para/>",
"/// <b>NOTE:</b> _<segmentSuffix> is added to the result file name only if",
"/// it's not the empty string",
"/// <para/>",
"/// <b>NOTE:</b> all custom files should be named using this method, or",
"/// otherwise some structures may fail to handle them properly (such as if they",
"/// are added to compound files).",
"/// </summary>",
"/// <summary>",
"/// Returns <c>true</c> if the given filename ends with the given extension. One",
"/// should provide a <i>pure</i> extension, without '.'.",
"/// </summary>",
"// It doesn't make a difference whether we allocate a StringBuilder ourself",
"// or not, since there's only 1 '+' operator.",
"/// <summary>",
"/// Locates the boundary of the segment name, or -1 </summary>",
"// If it is a .del file, there's an '_' after the first character",
"// If it's not, strip everything that's before the '.'",
"/// <summary>",
"/// Strips the segment name out of the given file name. If you used",
"/// <see cref=\"SegmentFileName\"/> or <see cref=\"FileNameFromGeneration\"/> to create your",
"/// files, then this method simply removes whatever comes before the first '.',",
"/// or the second '_' (excluding both).",
"/// </summary>",
"/// <returns> the filename with the segment name removed, or the given filename",
"/// if it does not contain a '.' and '_'. </returns>",
"/// <summary>",
"/// Parses the segment name out of the given file name.",
"/// </summary>",
"/// <returns> the segment name only, or filename",
"/// if it does not contain a '.' and '_'. </returns>",
"/// <summary>",
"/// Removes the extension (anything after the first '.'),",
"/// otherwise returns the original filename.",
"/// </summary>",
"/// <summary>",
"/// Return the extension (anything after the first '.'),",
"/// or null if there is no '.' in the file name.",
"/// </summary>",
"/// <summary>",
"/// All files created by codecs much match this pattern (checked in",
"/// <see cref=\"SegmentInfo\"/>).",
"/// </summary>"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 24
| 705
| 152
|
00b74b9c225068189dbe27d60300bf6db7730bec
|
stefan-zobel/math-jampack
|
src/main/java/gov/nist/math/jampack/Z.java
|
[
"Apache-2.0"
] |
Java
|
Z
|
/**
* Z is a mutable complex variable class. It is designed to perform complex
* arithmetic without creating a new Z at each operation. Specifically, binary
* operations have the form c.op(a,b), in which a, b, and c need not be
* different. The method places the complex number a.op.b in c. The method also
* returns a pointer to c. Thus the class supports two styles of programming.
* For example to compute e = a*b + c*d you can write
*
* <p>
* z1.times(a,b) <br>
* z2.times(c,d) <br>
* e.plus(z1,z2)
* <p>
* or
* <p>
* e.plus(z1.times(a,b), z2.times(a,b))
* <p>
*
* Since objects of class Z are mutable, the use of the assignment operator "="
* with these objects is deprecated. Use {@code eq}.
* <p>
*
* The functions are reasonably resistant to overflow and underflow. But the
* more complicated ones could almost certainly be improved.
*
* @version Pre-alpha, 1999-02-24
* @author G. W. Stewart
*/
|
Z is a mutable complex variable class. It is designed to perform complex
arithmetic without creating a new Z at each operation. Specifically, binary
operations have the form c.op(a,b), in which a, b, and c need not be
different. The method places the complex number a.op.b in c. The method also
returns a pointer to c. Thus the class supports two styles of programming.
For example to compute e = a*b + c*d you can write
Since objects of class Z are mutable, the use of the assignment operator "="
with these objects is deprecated. Use eq.
The functions are reasonably resistant to overflow and underflow. But the
more complicated ones could almost certainly be improved.
|
[
"Z",
"is",
"a",
"mutable",
"complex",
"variable",
"class",
".",
"It",
"is",
"designed",
"to",
"perform",
"complex",
"arithmetic",
"without",
"creating",
"a",
"new",
"Z",
"at",
"each",
"operation",
".",
"Specifically",
"binary",
"operations",
"have",
"the",
"form",
"c",
".",
"op",
"(",
"a",
"b",
")",
"in",
"which",
"a",
"b",
"and",
"c",
"need",
"not",
"be",
"different",
".",
"The",
"method",
"places",
"the",
"complex",
"number",
"a",
".",
"op",
".",
"b",
"in",
"c",
".",
"The",
"method",
"also",
"returns",
"a",
"pointer",
"to",
"c",
".",
"Thus",
"the",
"class",
"supports",
"two",
"styles",
"of",
"programming",
".",
"For",
"example",
"to",
"compute",
"e",
"=",
"a",
"*",
"b",
"+",
"c",
"*",
"d",
"you",
"can",
"write",
"Since",
"objects",
"of",
"class",
"Z",
"are",
"mutable",
"the",
"use",
"of",
"the",
"assignment",
"operator",
"\"",
"=",
"\"",
"with",
"these",
"objects",
"is",
"deprecated",
".",
"Use",
"eq",
".",
"The",
"functions",
"are",
"reasonably",
"resistant",
"to",
"overflow",
"and",
"underflow",
".",
"But",
"the",
"more",
"complicated",
"ones",
"could",
"almost",
"certainly",
"be",
"improved",
"."
] |
public final class Z {
/** Complex 1. */
public static final Z ONE = new Z(1.0, 0.0);
/** Complex 0. */
public static final Z ZERO = new Z(0.0, 0.0);
/** Imaginary unit. */
public static final Z I = new Z(0.0, 1.0);
/** The real part of Z. */
public double re;
/** The imaginary part of Z. */
public double im;
/**
* Creates a Z and initializes it to zero.
*/
public Z() {
re = 0.0;
im = 0.0;
}
/**
* Creates a Z and initializes its real and imaginary parts.
*
* @param x a double
* @param y a double
*/
public Z(double x, double y) {
re = x;
im = y;
}
/**
* Creates a Z and initializes its real part.
*
* @param x a double
*/
public Z(double x) {
re = x;
im = 0.0;
}
/**
* Creates a Z and initializes it to another Z.
*
* @param a a Z
*/
public Z(Z a) {
re = a.re;
im = a.im;
}
/**
* Tests two Z's for equality.
*
* @param z1
* a Z
* @param z2
* a Z
* @return true if z1=z2, otherwise false
*/
public boolean isEqual(Z z1, Z z2) {
if (z1.re == z2.re && z1.im == z2.im) {
return true;
} else {
return false;
}
}
/**
* Resets the real and imaginary parts of a Z to those of another Z.
*
* @param a
* a Z
* @return this = a;
*/
public Z eq(Z a) {
re = a.re;
im = a.im;
return this;
}
/**
* Resets the real and imaginary parts of a Z.
*
* @param a
* a double
* @param b
* a double
* @return this = a + ib
*/
public Z eq(double a, double b) {
re = a;
im = b;
return this;
}
/**
* Interchanges the real and imaginary parts of two Z's.
*
* @param a
* a Z
* @return this = a, with a set to the original value of this.
*/
public Z exch(Z a) {
double t = re;
re = a.re;
a.re = t;
t = im;
im = a.im;
a.im = t;
return this;
}
/**
* Computes the 1-norm of a Z
*
* @param z a complex number
* @return the 1-norm
*/
public static double abs1(Z z) {
return Math.abs(z.re) + Math.abs(z.im);
}
/**
* Computes the absolute value of a Z.
*
* @param z
* a Z
* @return the absolute value of Z
*/
public static double abs(Z z) {
double are, aim, rho;
are = Math.abs(z.re);
aim = Math.abs(z.im);
if (are + aim == 0.0)
return 0.0;
if (are >= aim) {
rho = aim / are;
return are * Math.sqrt(1 + rho * rho);
} else {
rho = are / aim;
return aim * Math.sqrt(1 + rho * rho);
}
}
/**
* Computes the conjugate of a Z.
*
* @param a
* a Z
* @return this = conj(a);
*/
public Z conj(Z a) {
re = a.re;
im = -a.im;
return this;
}
/**
* Computes unary minus of a Z.
*
* @param a
* a Z
* @return this = -a;
*/
public Z minus(Z a) {
re = -a.re;
im = -a.im;
return this;
}
/**
* Computes the sum of two Z's.
*
* @param a
* a Z
* @param b
* a Z
* @return this = a + b
*/
public Z plus(Z a, Z b) {
re = a.re + b.re;
im = a.im + b.im;
return this;
}
/**
* Computes the difference of two Z's.
*
* @param a
* a Z
* @param b
* a Z
* @return this = a - b
*/
public Z minus(Z a, Z b) {
re = a.re - b.re;
im = a.im - b.im;
return this;
}
/**
* Computes the product of two Z's.
*
* @param a
* a Z
* @param b
* a Z
* @return this = ab
*/
public Z times(Z a, Z b) {
double tre = a.re * b.re - a.im * b.im;
im = a.im * b.re + a.re * b.im;
re = tre;
return this;
}
/**
* Computes the product of a double and a Z.
*
* @param a
* a double
* @param b
* a Z
* @return this = ab
*/
public Z times(double a, Z b) {
re = a * b.re;
im = a * b.im;
return this;
}
/**
* Computes the quotient of two Z's. Throws a ZException if the denominator
* is zero.
*
* @param a
* a Z
* @param b
* a Z
* @return this = a/b
* @throws ZException
* Thrown if b is zero.
*/
public Z div(Z a, Z b) throws ZException {
double avi, t, tre, tim;
avi = abs(b);
if (avi == 0.0) {
throw new ZException("Divide by zero.");
}
avi = 1.0 / avi;
tre = b.re * avi;
tim = -b.im * avi;
t = (a.re * tre - a.im * tim) * avi;
im = (a.im * tre + a.re * tim) * avi;
re = t;
return this;
}
/**
* Computes the quotient of a Z and a double. Throws a ZException if the
* denominator is zero.
*
* @param a
* a Z
* @param b
* a double
* @return this = a/b
* @throws ZException
* Thrown if b is zero.
*/
public Z div(Z a, double b) throws ZException {
if (b == 0.0) {
throw new ZException("Divide by zero.");
}
re = a.re / b;
im = a.im / b;
return this;
}
/**
* Computes the principal value of the square root of a Z.
*
* @param a a Z
* @return principal value of the square root of z
*/
public Z sqrt(Z a) {
double t, tre, tim;
t = Z.abs(a);
if (Math.abs(a.re) <= Math.abs(a.im)) {
// No cancellation in these formulas
tre = Math.sqrt(0.5 * (t + a.re));
tim = Math.sqrt(0.5 * (t - a.re));
} else {
// Stable computation of the above formulas
if (a.re > 0) {
tre = t + a.re;
tim = Math.abs(a.im) * Math.sqrt(0.5 / tre);
tre = Math.sqrt(0.5 * tre);
} else {
tim = t - a.re;
tre = Math.abs(a.im) * Math.sqrt(0.5 / tim);
tim = Math.sqrt(0.5 * tim);
}
}
if (a.im < 0.0)
tim = -tim;
re = tre;
im = tim;
return this;
}
}
|
[
"public",
"final",
"class",
"Z",
"{",
"/** Complex 1. */",
"public",
"static",
"final",
"Z",
"ONE",
"=",
"new",
"Z",
"(",
"1.0",
",",
"0.0",
")",
";",
"/** Complex 0. */",
"public",
"static",
"final",
"Z",
"ZERO",
"=",
"new",
"Z",
"(",
"0.0",
",",
"0.0",
")",
";",
"/** Imaginary unit. */",
"public",
"static",
"final",
"Z",
"I",
"=",
"new",
"Z",
"(",
"0.0",
",",
"1.0",
")",
";",
"/** The real part of Z. */",
"public",
"double",
"re",
";",
"/** The imaginary part of Z. */",
"public",
"double",
"im",
";",
"/**\n * Creates a Z and initializes it to zero.\n */",
"public",
"Z",
"(",
")",
"{",
"re",
"=",
"0.0",
";",
"im",
"=",
"0.0",
";",
"}",
"/**\n * Creates a Z and initializes its real and imaginary parts.\n * \n * @param x a double\n * @param y a double\n */",
"public",
"Z",
"(",
"double",
"x",
",",
"double",
"y",
")",
"{",
"re",
"=",
"x",
";",
"im",
"=",
"y",
";",
"}",
"/**\n * Creates a Z and initializes its real part.\n * \n * @param x a double\n */",
"public",
"Z",
"(",
"double",
"x",
")",
"{",
"re",
"=",
"x",
";",
"im",
"=",
"0.0",
";",
"}",
"/**\n * Creates a Z and initializes it to another Z.\n * \n * @param a a Z\n */",
"public",
"Z",
"(",
"Z",
"a",
")",
"{",
"re",
"=",
"a",
".",
"re",
";",
"im",
"=",
"a",
".",
"im",
";",
"}",
"/**\n * Tests two Z's for equality.\n * \n * @param z1\n * a Z\n * @param z2\n * a Z\n * @return true if z1=z2, otherwise false\n */",
"public",
"boolean",
"isEqual",
"(",
"Z",
"z1",
",",
"Z",
"z2",
")",
"{",
"if",
"(",
"z1",
".",
"re",
"==",
"z2",
".",
"re",
"&&",
"z1",
".",
"im",
"==",
"z2",
".",
"im",
")",
"{",
"return",
"true",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}",
"/**\n * Resets the real and imaginary parts of a Z to those of another Z.\n * \n * @param a\n * a Z\n * @return this = a;\n */",
"public",
"Z",
"eq",
"(",
"Z",
"a",
")",
"{",
"re",
"=",
"a",
".",
"re",
";",
"im",
"=",
"a",
".",
"im",
";",
"return",
"this",
";",
"}",
"/**\n * Resets the real and imaginary parts of a Z.\n * \n * @param a\n * a double\n * @param b\n * a double\n * @return this = a + ib\n */",
"public",
"Z",
"eq",
"(",
"double",
"a",
",",
"double",
"b",
")",
"{",
"re",
"=",
"a",
";",
"im",
"=",
"b",
";",
"return",
"this",
";",
"}",
"/**\n * Interchanges the real and imaginary parts of two Z's.\n * \n * @param a\n * a Z\n * @return this = a, with a set to the original value of this.\n */",
"public",
"Z",
"exch",
"(",
"Z",
"a",
")",
"{",
"double",
"t",
"=",
"re",
";",
"re",
"=",
"a",
".",
"re",
";",
"a",
".",
"re",
"=",
"t",
";",
"t",
"=",
"im",
";",
"im",
"=",
"a",
".",
"im",
";",
"a",
".",
"im",
"=",
"t",
";",
"return",
"this",
";",
"}",
"/**\n * Computes the 1-norm of a Z\n * \n * @param z a complex number\n * @return the 1-norm\n */",
"public",
"static",
"double",
"abs1",
"(",
"Z",
"z",
")",
"{",
"return",
"Math",
".",
"abs",
"(",
"z",
".",
"re",
")",
"+",
"Math",
".",
"abs",
"(",
"z",
".",
"im",
")",
";",
"}",
"/**\n * Computes the absolute value of a Z.\n * \n * @param z\n * a Z\n * @return the absolute value of Z\n */",
"public",
"static",
"double",
"abs",
"(",
"Z",
"z",
")",
"{",
"double",
"are",
",",
"aim",
",",
"rho",
";",
"are",
"=",
"Math",
".",
"abs",
"(",
"z",
".",
"re",
")",
";",
"aim",
"=",
"Math",
".",
"abs",
"(",
"z",
".",
"im",
")",
";",
"if",
"(",
"are",
"+",
"aim",
"==",
"0.0",
")",
"return",
"0.0",
";",
"if",
"(",
"are",
">=",
"aim",
")",
"{",
"rho",
"=",
"aim",
"/",
"are",
";",
"return",
"are",
"*",
"Math",
".",
"sqrt",
"(",
"1",
"+",
"rho",
"*",
"rho",
")",
";",
"}",
"else",
"{",
"rho",
"=",
"are",
"/",
"aim",
";",
"return",
"aim",
"*",
"Math",
".",
"sqrt",
"(",
"1",
"+",
"rho",
"*",
"rho",
")",
";",
"}",
"}",
"/**\n * Computes the conjugate of a Z.\n * \n * @param a\n * a Z\n * @return this = conj(a);\n */",
"public",
"Z",
"conj",
"(",
"Z",
"a",
")",
"{",
"re",
"=",
"a",
".",
"re",
";",
"im",
"=",
"-",
"a",
".",
"im",
";",
"return",
"this",
";",
"}",
"/**\n * Computes unary minus of a Z.\n * \n * @param a\n * a Z\n * @return this = -a;\n */",
"public",
"Z",
"minus",
"(",
"Z",
"a",
")",
"{",
"re",
"=",
"-",
"a",
".",
"re",
";",
"im",
"=",
"-",
"a",
".",
"im",
";",
"return",
"this",
";",
"}",
"/**\n * Computes the sum of two Z's.\n * \n * @param a\n * a Z\n * @param b\n * a Z\n * @return this = a + b\n */",
"public",
"Z",
"plus",
"(",
"Z",
"a",
",",
"Z",
"b",
")",
"{",
"re",
"=",
"a",
".",
"re",
"+",
"b",
".",
"re",
";",
"im",
"=",
"a",
".",
"im",
"+",
"b",
".",
"im",
";",
"return",
"this",
";",
"}",
"/**\n * Computes the difference of two Z's.\n * \n * @param a\n * a Z\n * @param b\n * a Z\n * @return this = a - b\n */",
"public",
"Z",
"minus",
"(",
"Z",
"a",
",",
"Z",
"b",
")",
"{",
"re",
"=",
"a",
".",
"re",
"-",
"b",
".",
"re",
";",
"im",
"=",
"a",
".",
"im",
"-",
"b",
".",
"im",
";",
"return",
"this",
";",
"}",
"/**\n * Computes the product of two Z's.\n * \n * @param a\n * a Z\n * @param b\n * a Z\n * @return this = ab\n */",
"public",
"Z",
"times",
"(",
"Z",
"a",
",",
"Z",
"b",
")",
"{",
"double",
"tre",
"=",
"a",
".",
"re",
"*",
"b",
".",
"re",
"-",
"a",
".",
"im",
"*",
"b",
".",
"im",
";",
"im",
"=",
"a",
".",
"im",
"*",
"b",
".",
"re",
"+",
"a",
".",
"re",
"*",
"b",
".",
"im",
";",
"re",
"=",
"tre",
";",
"return",
"this",
";",
"}",
"/**\n * Computes the product of a double and a Z.\n * \n * @param a\n * a double\n * @param b\n * a Z\n * @return this = ab\n */",
"public",
"Z",
"times",
"(",
"double",
"a",
",",
"Z",
"b",
")",
"{",
"re",
"=",
"a",
"*",
"b",
".",
"re",
";",
"im",
"=",
"a",
"*",
"b",
".",
"im",
";",
"return",
"this",
";",
"}",
"/**\n * Computes the quotient of two Z's. Throws a ZException if the denominator\n * is zero.\n * \n * @param a\n * a Z\n * @param b\n * a Z\n * @return this = a/b\n * @throws ZException\n * Thrown if b is zero.\n */",
"public",
"Z",
"div",
"(",
"Z",
"a",
",",
"Z",
"b",
")",
"throws",
"ZException",
"{",
"double",
"avi",
",",
"t",
",",
"tre",
",",
"tim",
";",
"avi",
"=",
"abs",
"(",
"b",
")",
";",
"if",
"(",
"avi",
"==",
"0.0",
")",
"{",
"throw",
"new",
"ZException",
"(",
"\"",
"Divide by zero.",
"\"",
")",
";",
"}",
"avi",
"=",
"1.0",
"/",
"avi",
";",
"tre",
"=",
"b",
".",
"re",
"*",
"avi",
";",
"tim",
"=",
"-",
"b",
".",
"im",
"*",
"avi",
";",
"t",
"=",
"(",
"a",
".",
"re",
"*",
"tre",
"-",
"a",
".",
"im",
"*",
"tim",
")",
"*",
"avi",
";",
"im",
"=",
"(",
"a",
".",
"im",
"*",
"tre",
"+",
"a",
".",
"re",
"*",
"tim",
")",
"*",
"avi",
";",
"re",
"=",
"t",
";",
"return",
"this",
";",
"}",
"/**\n * Computes the quotient of a Z and a double. Throws a ZException if the\n * denominator is zero.\n * \n * @param a\n * a Z\n * @param b\n * a double\n * @return this = a/b\n * @throws ZException\n * Thrown if b is zero.\n */",
"public",
"Z",
"div",
"(",
"Z",
"a",
",",
"double",
"b",
")",
"throws",
"ZException",
"{",
"if",
"(",
"b",
"==",
"0.0",
")",
"{",
"throw",
"new",
"ZException",
"(",
"\"",
"Divide by zero.",
"\"",
")",
";",
"}",
"re",
"=",
"a",
".",
"re",
"/",
"b",
";",
"im",
"=",
"a",
".",
"im",
"/",
"b",
";",
"return",
"this",
";",
"}",
"/**\n * Computes the principal value of the square root of a Z.\n * \n * @param a a Z\n * @return principal value of the square root of z\n */",
"public",
"Z",
"sqrt",
"(",
"Z",
"a",
")",
"{",
"double",
"t",
",",
"tre",
",",
"tim",
";",
"t",
"=",
"Z",
".",
"abs",
"(",
"a",
")",
";",
"if",
"(",
"Math",
".",
"abs",
"(",
"a",
".",
"re",
")",
"<=",
"Math",
".",
"abs",
"(",
"a",
".",
"im",
")",
")",
"{",
"tre",
"=",
"Math",
".",
"sqrt",
"(",
"0.5",
"*",
"(",
"t",
"+",
"a",
".",
"re",
")",
")",
";",
"tim",
"=",
"Math",
".",
"sqrt",
"(",
"0.5",
"*",
"(",
"t",
"-",
"a",
".",
"re",
")",
")",
";",
"}",
"else",
"{",
"if",
"(",
"a",
".",
"re",
">",
"0",
")",
"{",
"tre",
"=",
"t",
"+",
"a",
".",
"re",
";",
"tim",
"=",
"Math",
".",
"abs",
"(",
"a",
".",
"im",
")",
"*",
"Math",
".",
"sqrt",
"(",
"0.5",
"/",
"tre",
")",
";",
"tre",
"=",
"Math",
".",
"sqrt",
"(",
"0.5",
"*",
"tre",
")",
";",
"}",
"else",
"{",
"tim",
"=",
"t",
"-",
"a",
".",
"re",
";",
"tre",
"=",
"Math",
".",
"abs",
"(",
"a",
".",
"im",
")",
"*",
"Math",
".",
"sqrt",
"(",
"0.5",
"/",
"tim",
")",
";",
"tim",
"=",
"Math",
".",
"sqrt",
"(",
"0.5",
"*",
"tim",
")",
";",
"}",
"}",
"if",
"(",
"a",
".",
"im",
"<",
"0.0",
")",
"tim",
"=",
"-",
"tim",
";",
"re",
"=",
"tre",
";",
"im",
"=",
"tim",
";",
"return",
"this",
";",
"}",
"}"
] |
Z is a mutable complex variable class.
|
[
"Z",
"is",
"a",
"mutable",
"complex",
"variable",
"class",
"."
] |
[
"// No cancellation in these formulas",
"// Stable computation of the above formulas"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 15
| 1,966
| 259
|
555068091de12453996c1dbc46d9793313956112
|
cs233/fliplot
|
src/core/Signal.js
|
[
"Apache-2.0"
] |
JavaScript
|
Signal
|
/**
* Value change type builds up the wave list of the signal. Each element describes a value change of
* a signal.
*
* @typedef {Object} valueChange_t
* @property {number} time Simulation time in the unit of the simulation timePrecision.
* @property {string} bin The raw value in binary form. Each character represents a bit in the
* bitvector. All other (optional) value format is derived from this.
* @property {string} [hex] A derived value from raw bin. Optional: calculated only when the user
* wants to see hex values. Each hex digit will be X and Z if there is an X or Z bit value in
* its region.
* @property {number} [u30] Fixed point float number. First character (s/u) note signed and unsigned
* format. The number of bits used to represent the fraction value (the number of bits below the
* decimal point) This means, that u0 means that the whole bitvector represents a fixed point
* unsigned integer. Note, that the full word length is defined at signal level. Derived,
* optional as above. Note, that if any X or Z located in the raw binary format, this value
* will be NaN.
* @property {number} [float] Single point float number. Derived, optional as above.
* @property {number} [double] Double point float number. Derived, optional as above.
*/
|
Value change type builds up the wave list of the signal. Each element describes a value change of
a signal.
@typedef {Object} valueChange_t
@property {number} time Simulation time in the unit of the simulation timePrecision.
@property {string} bin The raw value in binary form. Each character represents a bit in the
bitvector. All other (optional) value format is derived from this.
@property {string} [hex] A derived value from raw bin. Optional: calculated only when the user
wants to see hex values. Each hex digit will be X and Z if there is an X or Z bit value in
its region.
@property {number} [u30] Fixed point float number. First character (s/u) note signed and unsigned
format. The number of bits used to represent the fraction value (the number of bits below the
decimal point) This means, that u0 means that the whole bitvector represents a fixed point
unsigned integer. Note, that the full word length is defined at signal level. Derived,
optional as above. Note, that if any X or Z located in the raw binary format, this value
will be NaN.
@property {number} [float] Single point float number. Derived, optional as above.
@property {number} [double] Double point float number. Derived, optional as above.
|
[
"Value",
"change",
"type",
"builds",
"up",
"the",
"wave",
"list",
"of",
"the",
"signal",
".",
"Each",
"element",
"describes",
"a",
"value",
"change",
"of",
"a",
"signal",
".",
"@typedef",
"{",
"Object",
"}",
"valueChange_t",
"@property",
"{",
"number",
"}",
"time",
"Simulation",
"time",
"in",
"the",
"unit",
"of",
"the",
"simulation",
"timePrecision",
".",
"@property",
"{",
"string",
"}",
"bin",
"The",
"raw",
"value",
"in",
"binary",
"form",
".",
"Each",
"character",
"represents",
"a",
"bit",
"in",
"the",
"bitvector",
".",
"All",
"other",
"(",
"optional",
")",
"value",
"format",
"is",
"derived",
"from",
"this",
".",
"@property",
"{",
"string",
"}",
"[",
"hex",
"]",
"A",
"derived",
"value",
"from",
"raw",
"bin",
".",
"Optional",
":",
"calculated",
"only",
"when",
"the",
"user",
"wants",
"to",
"see",
"hex",
"values",
".",
"Each",
"hex",
"digit",
"will",
"be",
"X",
"and",
"Z",
"if",
"there",
"is",
"an",
"X",
"or",
"Z",
"bit",
"value",
"in",
"its",
"region",
".",
"@property",
"{",
"number",
"}",
"[",
"u30",
"]",
"Fixed",
"point",
"float",
"number",
".",
"First",
"character",
"(",
"s",
"/",
"u",
")",
"note",
"signed",
"and",
"unsigned",
"format",
".",
"The",
"number",
"of",
"bits",
"used",
"to",
"represent",
"the",
"fraction",
"value",
"(",
"the",
"number",
"of",
"bits",
"below",
"the",
"decimal",
"point",
")",
"This",
"means",
"that",
"u0",
"means",
"that",
"the",
"whole",
"bitvector",
"represents",
"a",
"fixed",
"point",
"unsigned",
"integer",
".",
"Note",
"that",
"the",
"full",
"word",
"length",
"is",
"defined",
"at",
"signal",
"level",
".",
"Derived",
"optional",
"as",
"above",
".",
"Note",
"that",
"if",
"any",
"X",
"or",
"Z",
"located",
"in",
"the",
"raw",
"binary",
"format",
"this",
"value",
"will",
"be",
"NaN",
".",
"@property",
"{",
"number",
"}",
"[",
"float",
"]",
"Single",
"point",
"float",
"number",
".",
"Derived",
"optional",
"as",
"above",
".",
"@property",
"{",
"number",
"}",
"[",
"double",
"]",
"Double",
"point",
"float",
"number",
".",
"Derived",
"optional",
"as",
"above",
"."
] |
class Signal {
constructor(sig) {
/** @type {string[]} */
this.references = sig.references;
/** @type {string} */
this.vcdid = sig.vcdid;
/** @type {string} */
this.type = sig.type;
/** @type {valueChange_t[]} */
this.wave = sig.wave;
/** @type {number} */
this.width = sig.width;
}
cloneRange(from, to = -1) {
if (to < 0) {
to = from;
}
const ret = new Signal(this);
ret.wave = [];
ret.width = to - from + 1;
return ret;
}
/**
* @param {number} time
*/
getChangeIndexAt(time) {
var idx = binarySearch(this.wave, time, (time, wave) => {
return time - wave.time;
})
if (idx < 0) {
idx = -idx - 2;
}
return idx;
}
/**
*
* @param {number} time
* @param {number} def
*/
getValueAt(time, radix, def = '- NA -') {
const idx = this.getChangeIndexAt(time);
return this.getValueAtI(idx, radix, def);
}
/**
* @param {number} i
* @param {number} def
*/
getValueAtI(i, radix = 'bin', def) {
if (i < 0) {
if (def !== undefined) {
return def;
}
throw 'Negative index';
}
if (i >= this.wave.length) {
i = this.wave.length - 1;
}
if (this.wave[i][radix] === undefined) {
this.wave[i][radix] = bin2radix(this.wave[i].bin, radix);
}
return this.wave[i][radix];
}
/**
* @param {int} i
*/
getTimeAtI(i) {
if (i < 0) {
throw 'Negative index';
}
if (i < this.wave.length) {
return this.wave[i].time;
}
if (i == this.wave.length) {
return simDB.now;
}
else {
throw 'Index is too great';
}
}
}
|
[
"class",
"Signal",
"{",
"constructor",
"(",
"sig",
")",
"{",
"this",
".",
"references",
"=",
"sig",
".",
"references",
";",
"this",
".",
"vcdid",
"=",
"sig",
".",
"vcdid",
";",
"this",
".",
"type",
"=",
"sig",
".",
"type",
";",
"this",
".",
"wave",
"=",
"sig",
".",
"wave",
";",
"this",
".",
"width",
"=",
"sig",
".",
"width",
";",
"}",
"cloneRange",
"(",
"from",
",",
"to",
"=",
"-",
"1",
")",
"{",
"if",
"(",
"to",
"<",
"0",
")",
"{",
"to",
"=",
"from",
";",
"}",
"const",
"ret",
"=",
"new",
"Signal",
"(",
"this",
")",
";",
"ret",
".",
"wave",
"=",
"[",
"]",
";",
"ret",
".",
"width",
"=",
"to",
"-",
"from",
"+",
"1",
";",
"return",
"ret",
";",
"}",
"getChangeIndexAt",
"(",
"time",
")",
"{",
"var",
"idx",
"=",
"binarySearch",
"(",
"this",
".",
"wave",
",",
"time",
",",
"(",
"time",
",",
"wave",
")",
"=>",
"{",
"return",
"time",
"-",
"wave",
".",
"time",
";",
"}",
")",
"if",
"(",
"idx",
"<",
"0",
")",
"{",
"idx",
"=",
"-",
"idx",
"-",
"2",
";",
"}",
"return",
"idx",
";",
"}",
"getValueAt",
"(",
"time",
",",
"radix",
",",
"def",
"=",
"'- NA -'",
")",
"{",
"const",
"idx",
"=",
"this",
".",
"getChangeIndexAt",
"(",
"time",
")",
";",
"return",
"this",
".",
"getValueAtI",
"(",
"idx",
",",
"radix",
",",
"def",
")",
";",
"}",
"getValueAtI",
"(",
"i",
",",
"radix",
"=",
"'bin'",
",",
"def",
")",
"{",
"if",
"(",
"i",
"<",
"0",
")",
"{",
"if",
"(",
"def",
"!==",
"undefined",
")",
"{",
"return",
"def",
";",
"}",
"throw",
"'Negative index'",
";",
"}",
"if",
"(",
"i",
">=",
"this",
".",
"wave",
".",
"length",
")",
"{",
"i",
"=",
"this",
".",
"wave",
".",
"length",
"-",
"1",
";",
"}",
"if",
"(",
"this",
".",
"wave",
"[",
"i",
"]",
"[",
"radix",
"]",
"===",
"undefined",
")",
"{",
"this",
".",
"wave",
"[",
"i",
"]",
"[",
"radix",
"]",
"=",
"bin2radix",
"(",
"this",
".",
"wave",
"[",
"i",
"]",
".",
"bin",
",",
"radix",
")",
";",
"}",
"return",
"this",
".",
"wave",
"[",
"i",
"]",
"[",
"radix",
"]",
";",
"}",
"getTimeAtI",
"(",
"i",
")",
"{",
"if",
"(",
"i",
"<",
"0",
")",
"{",
"throw",
"'Negative index'",
";",
"}",
"if",
"(",
"i",
"<",
"this",
".",
"wave",
".",
"length",
")",
"{",
"return",
"this",
".",
"wave",
"[",
"i",
"]",
".",
"time",
";",
"}",
"if",
"(",
"i",
"==",
"this",
".",
"wave",
".",
"length",
")",
"{",
"return",
"simDB",
".",
"now",
";",
"}",
"else",
"{",
"throw",
"'Index is too great'",
";",
"}",
"}",
"}"
] |
Value change type builds up the wave list of the signal.
|
[
"Value",
"change",
"type",
"builds",
"up",
"the",
"wave",
"list",
"of",
"the",
"signal",
"."
] |
[
"/** @type {string[]} */",
"/** @type {string} */",
"/** @type {string} */",
"/** @type {valueChange_t[]} */",
"/** @type {number} */",
"/**\n * @param {number} time\n */",
"/**\n *\n * @param {number} time\n * @param {number} def\n */",
"/**\n * @param {number} i\n * @param {number} def\n */",
"/**\n * @param {int} i\n */"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 14
| 525
| 312
|
36ce542d2bbda82cb01e28ddea6efb5626b33417
|
hendrik-schulte/unity-binary-serialization
|
SaveLoad.cs
|
[
"MIT"
] |
C#
|
SaveLoad
|
/// <summary>
/// This class offers different saving and loading options using BinaryFormater.
/// Adapted from this: http://answers.unity3d.com/questions/8480/how-to-scrip-a-saveload-game-option.html
/// and this: http://stackoverflow.com/questions/129389/how-do-you-do-a-deep-copy-an-object-in-net-c-specifically
/// </summary>
|
This class offers different saving and loading options using BinaryFormater.
|
[
"This",
"class",
"offers",
"different",
"saving",
"and",
"loading",
"options",
"using",
"BinaryFormater",
"."
] |
public class SaveLoad
{
public static string DefaultPath()
{
#if UNITY_WEBGL && !UNITY_EDITOR
return Application.persistentDataPath + "/Save/";
#else
return Application.dataPath + "/Save/";
#endif
}
public static void Save(string fileName, Object data)
{
Directory.CreateDirectory(DefaultPath());
string directory = Path.GetDirectoryName(fileName);
if (directory.Length > 0)
{
Directory.CreateDirectory(DefaultPath() + directory);
}
Stream stream = File.Open(DefaultPath() + fileName, FileMode.Create);
BinaryFormatter bformatter = new BinaryFormatter();
bformatter.Binder = new VersionDeserializationBinder();
bformatter.Serialize(stream, data);
stream.Close();
}
public static T Load<T>(string fileName) where T : new()
{
T data = new T();
string path = DefaultPath() + fileName;
try
{
if (!File.Exists(path))
throw new FileNotFoundException();
Stream stream = File.Open(path, FileMode.Open);
BinaryFormatter bformatter = new BinaryFormatter();
bformatter.Binder = new VersionDeserializationBinder();
data = (T) bformatter.Deserialize(stream);
stream.Close();
}
catch (FileNotFoundException)
{
Debug.LogError("ERROR: Coudn't find file at path: " + path);
}
catch (DirectoryNotFoundException)
{
Debug.LogError("ERROR: Coudn't find directory at path: " + path);
}
if (data is IFile)
{
(data as IFile).SetPath(fileName, Path.GetFileNameWithoutExtension(DefaultPath() + fileName));
}
return data;
}
public static T LoadFromPath<T>(string pathAndFileName) where T : new()
{
T data = new T();
Stream stream = File.Open(pathAndFileName, FileMode.Open);
BinaryFormatter bformatter = new BinaryFormatter();
bformatter.Binder = new VersionDeserializationBinder();
data = (T) bformatter.Deserialize(stream);
stream.Close();
return data;
}
public static T DeepClone<T>(T obj)
{
using (var ms = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(ms, obj);
ms.Position = 0;
return (T) formatter.Deserialize(ms);
}
}
public static List<T> LoadList<T>(string directory, string extention) where T : new()
{
var result = new List<T>();
foreach (var file in GetFilesByExtention(directory, extention))
{
result.Add(Load<T>(file));
}
return result;
}
public static List<string> GetFilesByExtention(string directory, string extention)
{
var result = new List<string>();
string path = DefaultPath();
string[] files;
try
{
if (!Directory.Exists(path + directory))
throw new DirectoryNotFoundException();
files = Directory.GetFiles(path + directory, "*." + extention);
}
catch (DirectoryNotFoundException)
{
Debug.Log("Warning: The directory '" + path + directory + "' to load from does not exist.");
files = new string[0];
}
foreach (var file in files)
{
result.Add(file.Substring(path.Length, file.Length - path.Length));
}
return result;
}
public static byte[] SerializeToByteArray(Object data)
{
MemoryStream stream = new MemoryStream();
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(stream, data);
return stream.GetBuffer();
}
public static T DeserializeByteArray<T>(byte[] byteData)
{
MemoryStream stream = new MemoryStream(byteData);
BinaryFormatter binaryFormatter = new BinaryFormatter();
return (T) binaryFormatter.Deserialize(stream);
}
}
|
[
"public",
"class",
"SaveLoad",
"{",
"public",
"static",
"string",
"DefaultPath",
"(",
")",
"{",
"if",
"UNITY_WEBGL",
"&&",
"!",
"UNITY_EDITOR",
"return",
"Application",
".",
"persistentDataPath",
"+",
"\"",
"/Save/",
"\"",
";",
"else",
"return",
"Application",
".",
"dataPath",
"+",
"\"",
"/Save/",
"\"",
";",
"endif",
"}",
"public",
"static",
"void",
"Save",
"(",
"string",
"fileName",
",",
"Object",
"data",
")",
"{",
"Directory",
".",
"CreateDirectory",
"(",
"DefaultPath",
"(",
")",
")",
";",
"string",
"directory",
"=",
"Path",
".",
"GetDirectoryName",
"(",
"fileName",
")",
";",
"if",
"(",
"directory",
".",
"Length",
">",
"0",
")",
"{",
"Directory",
".",
"CreateDirectory",
"(",
"DefaultPath",
"(",
")",
"+",
"directory",
")",
";",
"}",
"Stream",
"stream",
"=",
"File",
".",
"Open",
"(",
"DefaultPath",
"(",
")",
"+",
"fileName",
",",
"FileMode",
".",
"Create",
")",
";",
"BinaryFormatter",
"bformatter",
"=",
"new",
"BinaryFormatter",
"(",
")",
";",
"bformatter",
".",
"Binder",
"=",
"new",
"VersionDeserializationBinder",
"(",
")",
";",
"bformatter",
".",
"Serialize",
"(",
"stream",
",",
"data",
")",
";",
"stream",
".",
"Close",
"(",
")",
";",
"}",
"public",
"static",
"T",
"Load",
"<",
"T",
">",
"(",
"string",
"fileName",
")",
"where",
"T",
":",
"new",
"(",
")",
"{",
"T",
"data",
"=",
"new",
"T",
"(",
")",
";",
"string",
"path",
"=",
"DefaultPath",
"(",
")",
"+",
"fileName",
";",
"try",
"{",
"if",
"(",
"!",
"File",
".",
"Exists",
"(",
"path",
")",
")",
"throw",
"new",
"FileNotFoundException",
"(",
")",
";",
"Stream",
"stream",
"=",
"File",
".",
"Open",
"(",
"path",
",",
"FileMode",
".",
"Open",
")",
";",
"BinaryFormatter",
"bformatter",
"=",
"new",
"BinaryFormatter",
"(",
")",
";",
"bformatter",
".",
"Binder",
"=",
"new",
"VersionDeserializationBinder",
"(",
")",
";",
"data",
"=",
"(",
"T",
")",
"bformatter",
".",
"Deserialize",
"(",
"stream",
")",
";",
"stream",
".",
"Close",
"(",
")",
";",
"}",
"catch",
"(",
"FileNotFoundException",
")",
"{",
"Debug",
".",
"LogError",
"(",
"\"",
"ERROR: Coudn't find file at path: ",
"\"",
"+",
"path",
")",
";",
"}",
"catch",
"(",
"DirectoryNotFoundException",
")",
"{",
"Debug",
".",
"LogError",
"(",
"\"",
"ERROR: Coudn't find directory at path: ",
"\"",
"+",
"path",
")",
";",
"}",
"if",
"(",
"data",
"is",
"IFile",
")",
"{",
"(",
"data",
"as",
"IFile",
")",
".",
"SetPath",
"(",
"fileName",
",",
"Path",
".",
"GetFileNameWithoutExtension",
"(",
"DefaultPath",
"(",
")",
"+",
"fileName",
")",
")",
";",
"}",
"return",
"data",
";",
"}",
"public",
"static",
"T",
"LoadFromPath",
"<",
"T",
">",
"(",
"string",
"pathAndFileName",
")",
"where",
"T",
":",
"new",
"(",
")",
"{",
"T",
"data",
"=",
"new",
"T",
"(",
")",
";",
"Stream",
"stream",
"=",
"File",
".",
"Open",
"(",
"pathAndFileName",
",",
"FileMode",
".",
"Open",
")",
";",
"BinaryFormatter",
"bformatter",
"=",
"new",
"BinaryFormatter",
"(",
")",
";",
"bformatter",
".",
"Binder",
"=",
"new",
"VersionDeserializationBinder",
"(",
")",
";",
"data",
"=",
"(",
"T",
")",
"bformatter",
".",
"Deserialize",
"(",
"stream",
")",
";",
"stream",
".",
"Close",
"(",
")",
";",
"return",
"data",
";",
"}",
"public",
"static",
"T",
"DeepClone",
"<",
"T",
">",
"(",
"T",
"obj",
")",
"{",
"using",
"(",
"var",
"ms",
"=",
"new",
"MemoryStream",
"(",
")",
")",
"{",
"var",
"formatter",
"=",
"new",
"BinaryFormatter",
"(",
")",
";",
"formatter",
".",
"Serialize",
"(",
"ms",
",",
"obj",
")",
";",
"ms",
".",
"Position",
"=",
"0",
";",
"return",
"(",
"T",
")",
"formatter",
".",
"Deserialize",
"(",
"ms",
")",
";",
"}",
"}",
"public",
"static",
"List",
"<",
"T",
">",
"LoadList",
"<",
"T",
">",
"(",
"string",
"directory",
",",
"string",
"extention",
")",
"where",
"T",
":",
"new",
"(",
")",
"{",
"var",
"result",
"=",
"new",
"List",
"<",
"T",
">",
"(",
")",
";",
"foreach",
"(",
"var",
"file",
"in",
"GetFilesByExtention",
"(",
"directory",
",",
"extention",
")",
")",
"{",
"result",
".",
"Add",
"(",
"Load",
"<",
"T",
">",
"(",
"file",
")",
")",
";",
"}",
"return",
"result",
";",
"}",
"public",
"static",
"List",
"<",
"string",
">",
"GetFilesByExtention",
"(",
"string",
"directory",
",",
"string",
"extention",
")",
"{",
"var",
"result",
"=",
"new",
"List",
"<",
"string",
">",
"(",
")",
";",
"string",
"path",
"=",
"DefaultPath",
"(",
")",
";",
"string",
"[",
"]",
"files",
";",
"try",
"{",
"if",
"(",
"!",
"Directory",
".",
"Exists",
"(",
"path",
"+",
"directory",
")",
")",
"throw",
"new",
"DirectoryNotFoundException",
"(",
")",
";",
"files",
"=",
"Directory",
".",
"GetFiles",
"(",
"path",
"+",
"directory",
",",
"\"",
"*.",
"\"",
"+",
"extention",
")",
";",
"}",
"catch",
"(",
"DirectoryNotFoundException",
")",
"{",
"Debug",
".",
"Log",
"(",
"\"",
"Warning: The directory '",
"\"",
"+",
"path",
"+",
"directory",
"+",
"\"",
"' to load from does not exist.",
"\"",
")",
";",
"files",
"=",
"new",
"string",
"[",
"0",
"]",
";",
"}",
"foreach",
"(",
"var",
"file",
"in",
"files",
")",
"{",
"result",
".",
"Add",
"(",
"file",
".",
"Substring",
"(",
"path",
".",
"Length",
",",
"file",
".",
"Length",
"-",
"path",
".",
"Length",
")",
")",
";",
"}",
"return",
"result",
";",
"}",
"public",
"static",
"byte",
"[",
"]",
"SerializeToByteArray",
"(",
"Object",
"data",
")",
"{",
"MemoryStream",
"stream",
"=",
"new",
"MemoryStream",
"(",
")",
";",
"BinaryFormatter",
"binaryFormatter",
"=",
"new",
"BinaryFormatter",
"(",
")",
";",
"binaryFormatter",
".",
"Serialize",
"(",
"stream",
",",
"data",
")",
";",
"return",
"stream",
".",
"GetBuffer",
"(",
")",
";",
"}",
"public",
"static",
"T",
"DeserializeByteArray",
"<",
"T",
">",
"(",
"byte",
"[",
"]",
"byteData",
")",
"{",
"MemoryStream",
"stream",
"=",
"new",
"MemoryStream",
"(",
"byteData",
")",
";",
"BinaryFormatter",
"binaryFormatter",
"=",
"new",
"BinaryFormatter",
"(",
")",
";",
"return",
"(",
"T",
")",
"binaryFormatter",
".",
"Deserialize",
"(",
"stream",
")",
";",
"}",
"}"
] |
This class offers different saving and loading options using BinaryFormater.
|
[
"This",
"class",
"offers",
"different",
"saving",
"and",
"loading",
"options",
"using",
"BinaryFormater",
"."
] |
[
"/// <summary>",
"/// Returns the default path where this class stores files when no absolute directory is specified. On desktop",
"/// builds it will be next to the executable while in WebGL, it will save in a local database. In Editor it saves",
"/// to \"Assets/\".",
"/// </summary>",
"/// <returns></returns>",
"/// <summary>",
"/// Saves the given object in a file with the given name. The object must be serializable.",
"/// </summary>",
"/// <param name=\"fileName\"></param>",
"/// <param name=\"data\"></param>",
"//Debug.Log(\"Saved \" + fileName + \". Path: \" + directory);",
"/// <summary>",
"/// Loads an object from the given file and deserializes it.",
"/// </summary>",
"/// <typeparam name=\"T\"></typeparam>",
"/// <param name=\"fileName\"></param>",
"/// <returns></returns>",
"//Debug.Log(\"Loading from \" + path);",
"/// <summary>",
"/// Creates a deep copy of the given object using serialization.",
"/// </summary>",
"/// <typeparam name=\"T\"></typeparam>",
"/// <param name=\"obj\"></param>",
"/// <returns></returns>",
"/// <summary>",
"/// Loads all files in the given directory with the given file extention and returns them as a list of the given type.",
"/// </summary>",
"/// <typeparam name=\"T\"></typeparam>",
"/// <param name=\"directory\"></param>",
"/// <param name=\"extention\"></param>",
"/// <returns></returns>",
"//string path = DefaultPath();",
"//string[] files = Directory.GetFiles(path + directory, \"*.\" + extention);",
"/// <summary>",
"/// Returns a list of paths to files in the given directory with the given file extention.",
"/// For example: GetFilesByExtention(\"Replay\", \"rpl\")",
"/// </summary>",
"/// <param name=\"directory\"></param>",
"/// <param name=\"extention\"></param>",
"/// <returns></returns>",
"/// <summary>",
"/// Serializes the given object to a byte array.",
"/// </summary>",
"/// <param name=\"data\"></param>",
"/// <returns></returns>",
"/// <summary>",
"/// Deserializes the given byte array back to the initial object.",
"/// </summary>",
"/// <typeparam name=\"T\"></typeparam>",
"/// <param name=\"byteData\"></param>",
"/// <returns></returns>"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 17
| 801
| 87
|
222e2fa2c9c5cec068f4d230b70a95168b6ea1a5
|
mtaimoorkhan/jml4sec
|
BM/OpenJMLTest/testfiles/racHansAbstract/unitTest/TestSuite.java
|
[
"MIT"
] |
Java
|
TestSuite
|
/**
* A <code>TestSuite</code> is a <code>Composite</code> of Tests.
* It runs a collection of test cases. Here is an example using
* the dynamic test definition.
* <pre>
* TestSuite suite= new TestSuite();
* suite.addTest(new MathTest("testAdd"));
* suite.addTest(new MathTest("testDivideByZero"));
* </pre>
* Alternatively, a TestSuite can extract the tests to be run automatically.
* To do so you pass the class of your TestCase class to the
* TestSuite constructor.
* <pre>
* TestSuite suite= new TestSuite(MathTest.class);
* </pre>
* This constructor creates a suite with all the methods
* starting with "test" that take no arguments.
* <p>
* A final option is to do the same for a large array of test classes.
* <pre>
* Class[] testClasses = { MathTest.class, AnotherTest.class }
* TestSuite suite= new TestSuite(testClasses);
* </pre>
*
* @see Test
*/
|
A TestSuite is a Composite of Tests.
It runs a collection of test cases. Here is an example using
the dynamic test definition.
@see Test
|
[
"A",
"TestSuite",
"is",
"a",
"Composite",
"of",
"Tests",
".",
"It",
"runs",
"a",
"collection",
"of",
"test",
"cases",
".",
"Here",
"is",
"an",
"example",
"using",
"the",
"dynamic",
"test",
"definition",
".",
"@see",
"Test"
] |
public class TestSuite implements Test {
/**
* ...as the moon sets over the early morning Merlin, Oregon
* mountains, our intrepid adventurers type...
*/
/*static public Test createTest(Class theClass, String name) {
Constructor constructor;
try {
constructor= getTestConstructor(theClass);
} catch (NoSuchMethodException e) {
return warning("Class "+theClass.getName()+" has no public constructor TestCase(String name) or TestCase()");
}
Object test;
try {
if (constructor.getParameterTypes().length == 0) {
test= constructor.newInstance(new Object[0]);
if (test instanceof TestCase)
((TestCase) test).setName(name);
} else {
test= constructor.newInstance(new Object[]{name});
}
} catch (InstantiationException e) {
return(warning("Cannot instantiate test case: "+name+" ("+exceptionToString(e)+")"));
} catch (InvocationTargetException e) {
return(warning("Exception in constructor: "+name+" ("+exceptionToString(e.getTargetException())+")"));
} catch (IllegalAccessException e) {
return(warning("Cannot access test case: "+name+" ("+exceptionToString(e)+")"));
}
return (Test) test;
}*/
/**
* Gets a constructor which takes a single String as
* its argument or a no arg constructor.
*/
/*public static Constructor getTestConstructor(Class theClass) throws NoSuchMethodException {
Class[] args= { String.class };
try {
return theClass.getConstructor(args);
} catch (NoSuchMethodException e) {
// fall through
}
return theClass.getConstructor(new Class[0]);
}*/
/**
* Returns a test which will fail and log a warning message.
*/
public static Test warning(final String message) {
return new TestCase("warning") {
protected void runTest() {
fail(message);
}
};
}
/**
* Converts the stack trace into a string
private static String exceptionToString(Throwable t) {
StringWriter stringWriter= new StringWriter();
PrintWriter writer= new PrintWriter(stringWriter);
t.printStackTrace(writer);
return stringWriter.toString();
}
*/
private String fName;
private Vector<Test> fTests= new Vector<Test>(10);
/**
* Constructs an empty TestSuite.
*/
public TestSuite() {
}
/**
* Constructs a TestSuite from the given class. Adds all the methods
* starting with "test" as test cases to the suite.
* Parts of this method was written at 2337 meters in the Hueffihuette,
* Kanton Uri
*/
/*public TestSuite(final Class theClass) {
fName= theClass.getName();
try {
getTestConstructor(theClass); // Avoid generating multiple error messages
} catch (NoSuchMethodException e) {
addTest(warning("Class "+theClass.getName()+" has no public constructor TestCase(String name) or TestCase()"));
return;
}
if (!Modifier.isPublic(theClass.getModifiers())) {
addTest(warning("Class "+theClass.getName()+" is not public"));
return;
}
Class superClass= theClass;
Vector names= new Vector();
while (Test.class.isAssignableFrom(superClass)) {
Method[] methods= superClass.getDeclaredMethods();
for (int i= 0; i < methods.length; i++) {
addTestMethod(methods[i], names, theClass);
}
superClass= superClass.getSuperclass();
}
if (fTests.size() == 0)
addTest(warning("No tests found in "+theClass.getName()));
}*/
/**
* Constructs a TestSuite from the given class with the given name.
* @see TestSuite#TestSuite(Class)
*/
/*public TestSuite(Class theClass, String name) {
this(theClass);
setName(name);
}*/
/**
* Constructs an empty TestSuite.
*/
public TestSuite(String name) {
setName(name);
}
/**
* Constructs a TestSuite from the given array of classes.
* @param classes
*/
/*public TestSuite (Class[] classes) {
for (int i= 0; i < classes.length; i++)
addTest(new TestSuite(classes[i]));
}*/
/**
* Constructs a TestSuite from the given array of classes with the given name.
* @see TestSuite#TestSuite(Class[])
*/
/*public TestSuite(Class[] classes, String name) {
this(classes);
setName(name);
}*/
/**
* Adds a test to the suite.
*/
public void addTest(Test test) {
fTests.addElement(test);
}
/**
* Adds the tests from the given class to the suite
*/
/*public void addTestSuite(Class testClass) {
addTest(new TestSuite(testClass));
}*/
/**
* Counts the number of test cases that will be run by this test.
*/
public int countTestCases() {
int count= 0;
for (Enumeration<Test> e= tests(); e.hasMoreElements(); ) {
Test test= (Test)e.nextElement();
count= count + test.countTestCases();
}
return count;
}
/**
* Returns the name of the suite. Not all
* test suites have a name and this method
* can return null.
*/
public String getName() {
return fName;
}
/**
* Runs the tests and collects their result in a TestResult.
*/
public void run(TestResult result) {
for (Enumeration<Test> e= tests(); e.hasMoreElements(); ) {
if (result.shouldStop() )
break;
Test test= (Test)e.nextElement();
runTest(test, result);
}
}
public void runTest(Test test, TestResult result) {
test.run(result);
}
/**
* Sets the name of the suite.
* @param name The name to set
*/
public void setName(String name) {
fName= name;
}
/**
* Returns the test at the given index
*/
public Test testAt(int index) {
return (Test)fTests.elementAt(index);
}
/**
* Returns the number of tests in this suite
*/
public int testCount() {
return fTests.size();
}
/**
* Returns the tests as an enumeration
*/
public Enumeration<Test> tests() {
return fTests.elements();
}
/**
*/
public String toString() {
if (getName() != null)
return getName();
return super.toString();
}
/*private void addTestMethod(Method m, Vector names, Class theClass) {
String name= m.getName();
if (names.contains(name))
return;
if (! isPublicTestMethod(m)) {
if (isTestMethod(m))
addTest(warning("Test method isn't public: "+m.getName()));
return;
}
names.addElement(name);
addTest(createTest(theClass, name));
}
private boolean isPublicTestMethod(Method m) {
return isTestMethod(m) && Modifier.isPublic(m.getModifiers());
}
private boolean isTestMethod(Method m) {
String name= m.getName();
Class[] parameters= m.getParameterTypes();
Class returnType= m.getReturnType();
return parameters.length == 0 && name.startsWith("test") && returnType.equals(Void.TYPE);
}*/
}
|
[
"public",
"class",
"TestSuite",
"implements",
"Test",
"{",
"/**\n\t * ...as the moon sets over the early morning Merlin, Oregon\n\t * mountains, our intrepid adventurers type...\n\t */",
"/*static public Test createTest(Class theClass, String name) {\n\t\tConstructor constructor;\n\t\ttry {\n\t\t\tconstructor= getTestConstructor(theClass);\n\t\t} catch (NoSuchMethodException e) {\n\t\t\treturn warning(\"Class \"+theClass.getName()+\" has no public constructor TestCase(String name) or TestCase()\");\n\t\t}\n\t\tObject test;\n\t\ttry {\n\t\t\tif (constructor.getParameterTypes().length == 0) {\n\t\t\t\ttest= constructor.newInstance(new Object[0]);\n\t\t\t\tif (test instanceof TestCase)\n\t\t\t\t\t((TestCase) test).setName(name);\n\t\t\t} else {\n\t\t\t\ttest= constructor.newInstance(new Object[]{name});\n\t\t\t}\n\t\t} catch (InstantiationException e) {\n\t\t\treturn(warning(\"Cannot instantiate test case: \"+name+\" (\"+exceptionToString(e)+\")\"));\n\t\t} catch (InvocationTargetException e) {\n\t\t\treturn(warning(\"Exception in constructor: \"+name+\" (\"+exceptionToString(e.getTargetException())+\")\"));\n\t\t} catch (IllegalAccessException e) {\n\t\t\treturn(warning(\"Cannot access test case: \"+name+\" (\"+exceptionToString(e)+\")\"));\n\t\t}\n\t\treturn (Test) test;\n\t}*/",
"/**\n\t * Gets a constructor which takes a single String as\n\t * its argument or a no arg constructor.\n\t */",
"/*public static Constructor getTestConstructor(Class theClass) throws NoSuchMethodException {\n\t\tClass[] args= { String.class };\n\t\ttry {\n\t\t\treturn theClass.getConstructor(args);\t\n\t\t} catch (NoSuchMethodException e) {\n\t\t\t// fall through\n\t\t}\n\t\treturn theClass.getConstructor(new Class[0]);\n\t}*/",
"/**\n\t * Returns a test which will fail and log a warning message.\n\t */",
"public",
"static",
"Test",
"warning",
"(",
"final",
"String",
"message",
")",
"{",
"return",
"new",
"TestCase",
"(",
"\"",
"warning",
"\"",
")",
"{",
"protected",
"void",
"runTest",
"(",
")",
"{",
"fail",
"(",
"message",
")",
";",
"}",
"}",
";",
"}",
"/**\n\t * Converts the stack trace into a string\n\t \n\tprivate static String exceptionToString(Throwable t) {\n\t\tStringWriter stringWriter= new StringWriter();\n\t\tPrintWriter writer= new PrintWriter(stringWriter);\n\t\tt.printStackTrace(writer);\n\t\treturn stringWriter.toString();\n\n\t}\n\t*/",
"private",
"String",
"fName",
";",
"private",
"Vector",
"<",
"Test",
">",
"fTests",
"=",
"new",
"Vector",
"<",
"Test",
">",
"(",
"10",
")",
";",
"/**\n\t * Constructs an empty TestSuite.\n\t */",
"public",
"TestSuite",
"(",
")",
"{",
"}",
"/**\n\t * Constructs a TestSuite from the given class. Adds all the methods\n\t * starting with \"test\" as test cases to the suite.\n\t * Parts of this method was written at 2337 meters in the Hueffihuette,\n\t * Kanton Uri\n\t */",
"/*public TestSuite(final Class theClass) {\n\t\tfName= theClass.getName();\n\t\ttry {\n\t\t\tgetTestConstructor(theClass); // Avoid generating multiple error messages\n\t\t} catch (NoSuchMethodException e) {\n\t\t\taddTest(warning(\"Class \"+theClass.getName()+\" has no public constructor TestCase(String name) or TestCase()\"));\n\t\t\treturn;\n\t\t}\n\n\t\tif (!Modifier.isPublic(theClass.getModifiers())) {\n\t\t\taddTest(warning(\"Class \"+theClass.getName()+\" is not public\"));\n\t\t\treturn;\n\t\t}\n\n\t\tClass superClass= theClass;\n\t\tVector names= new Vector();\n\t\twhile (Test.class.isAssignableFrom(superClass)) {\n\t\t\tMethod[] methods= superClass.getDeclaredMethods();\n\t\t\tfor (int i= 0; i < methods.length; i++) {\n\t\t\t\taddTestMethod(methods[i], names, theClass);\n\t\t\t}\n\t\t\tsuperClass= superClass.getSuperclass();\n\t\t}\n\t\tif (fTests.size() == 0)\n\t\t\taddTest(warning(\"No tests found in \"+theClass.getName()));\n\t}*/",
"/**\n\t * Constructs a TestSuite from the given class with the given name.\n\t * @see TestSuite#TestSuite(Class)\n\t */",
"/*public TestSuite(Class theClass, String name) {\n\t\tthis(theClass);\n\t\tsetName(name);\n\t}*/",
"/**\n\t * Constructs an empty TestSuite.\n\t */",
"public",
"TestSuite",
"(",
"String",
"name",
")",
"{",
"setName",
"(",
"name",
")",
";",
"}",
"/**\n\t * Constructs a TestSuite from the given array of classes. \n\t * @param classes\n\t */",
"/*public TestSuite (Class[] classes) {\n\t\tfor (int i= 0; i < classes.length; i++)\n\t\t\taddTest(new TestSuite(classes[i]));\n\t}*/",
"/**\n\t * Constructs a TestSuite from the given array of classes with the given name.\n\t * @see TestSuite#TestSuite(Class[])\n\t */",
"/*public TestSuite(Class[] classes, String name) {\n\t\tthis(classes);\n\t\tsetName(name);\n\t}*/",
"/**\n\t * Adds a test to the suite.\n\t */",
"public",
"void",
"addTest",
"(",
"Test",
"test",
")",
"{",
"fTests",
".",
"addElement",
"(",
"test",
")",
";",
"}",
"/**\n\t * Adds the tests from the given class to the suite\n\t */",
"/*public void addTestSuite(Class testClass) {\n\t\taddTest(new TestSuite(testClass));\n\t}*/",
"/**\n\t * Counts the number of test cases that will be run by this test.\n\t */",
"public",
"int",
"countTestCases",
"(",
")",
"{",
"int",
"count",
"=",
"0",
";",
"for",
"(",
"Enumeration",
"<",
"Test",
">",
"e",
"=",
"tests",
"(",
")",
";",
"e",
".",
"hasMoreElements",
"(",
")",
";",
")",
"{",
"Test",
"test",
"=",
"(",
"Test",
")",
"e",
".",
"nextElement",
"(",
")",
";",
"count",
"=",
"count",
"+",
"test",
".",
"countTestCases",
"(",
")",
";",
"}",
"return",
"count",
";",
"}",
"/**\n\t * Returns the name of the suite. Not all\n\t * test suites have a name and this method\n\t * can return null.\n\t */",
"public",
"String",
"getName",
"(",
")",
"{",
"return",
"fName",
";",
"}",
"/**\n\t * Runs the tests and collects their result in a TestResult.\n\t */",
"public",
"void",
"run",
"(",
"TestResult",
"result",
")",
"{",
"for",
"(",
"Enumeration",
"<",
"Test",
">",
"e",
"=",
"tests",
"(",
")",
";",
"e",
".",
"hasMoreElements",
"(",
")",
";",
")",
"{",
"if",
"(",
"result",
".",
"shouldStop",
"(",
")",
")",
"break",
";",
"Test",
"test",
"=",
"(",
"Test",
")",
"e",
".",
"nextElement",
"(",
")",
";",
"runTest",
"(",
"test",
",",
"result",
")",
";",
"}",
"}",
"public",
"void",
"runTest",
"(",
"Test",
"test",
",",
"TestResult",
"result",
")",
"{",
"test",
".",
"run",
"(",
"result",
")",
";",
"}",
"/**\n\t * Sets the name of the suite.\n\t * @param name The name to set\n\t */",
"public",
"void",
"setName",
"(",
"String",
"name",
")",
"{",
"fName",
"=",
"name",
";",
"}",
"/**\n\t * Returns the test at the given index\n\t */",
"public",
"Test",
"testAt",
"(",
"int",
"index",
")",
"{",
"return",
"(",
"Test",
")",
"fTests",
".",
"elementAt",
"(",
"index",
")",
";",
"}",
"/**\n\t * Returns the number of tests in this suite\n\t */",
"public",
"int",
"testCount",
"(",
")",
"{",
"return",
"fTests",
".",
"size",
"(",
")",
";",
"}",
"/**\n\t * Returns the tests as an enumeration\n\t */",
"public",
"Enumeration",
"<",
"Test",
">",
"tests",
"(",
")",
"{",
"return",
"fTests",
".",
"elements",
"(",
")",
";",
"}",
"/**\n\t */",
"public",
"String",
"toString",
"(",
")",
"{",
"if",
"(",
"getName",
"(",
")",
"!=",
"null",
")",
"return",
"getName",
"(",
")",
";",
"return",
"super",
".",
"toString",
"(",
")",
";",
"}",
"/*private void addTestMethod(Method m, Vector names, Class theClass) {\n\t\tString name= m.getName();\n\t\tif (names.contains(name))\n\t\t\treturn;\n\t\tif (! isPublicTestMethod(m)) {\n\t\t\tif (isTestMethod(m))\n\t\t\t\taddTest(warning(\"Test method isn't public: \"+m.getName()));\n\t\t\treturn;\n\t\t}\n\t\tnames.addElement(name);\n\t\taddTest(createTest(theClass, name));\n\t}\n\n\tprivate boolean isPublicTestMethod(Method m) {\n\t\treturn isTestMethod(m) && Modifier.isPublic(m.getModifiers());\n\t }\n\t \n\tprivate boolean isTestMethod(Method m) {\n\t\tString name= m.getName();\n\t\tClass[] parameters= m.getParameterTypes();\n\t\tClass returnType= m.getReturnType();\n\t\treturn parameters.length == 0 && name.startsWith(\"test\") && returnType.equals(Void.TYPE);\n\t }*/",
"}"
] |
A <code>TestSuite</code> is a <code>Composite</code> of Tests.
|
[
"A",
"<code",
">",
"TestSuite<",
"/",
"code",
">",
"is",
"a",
"<code",
">",
"Composite<",
"/",
"code",
">",
"of",
"Tests",
"."
] |
[] |
[
{
"param": "Test",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "Test",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 13
| 1,619
| 225
|
602bf6b14499b7f1cca5cacf315cd8011fa7ef0c
|
Dot42Xna/master
|
Generated/v3.2/Org.Apache.Http.Params.cs
|
[
"Apache-2.0"
] |
C#
|
DefaultedHttpParams
|
/// <summary>
/// <para>HttpParams implementation that delegates resolution of a parameter to the given default HttpParams instance if the parameter is not present in the local one. The state of the local collection can be mutated, whereas the default collection is treated as read-only.</para><para><para></para><para></para><title>Revision:</title><para>610763 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/params/DefaultedHttpParams
/// </java-name>
|
HttpParams implementation that delegates resolution of a parameter to the given default HttpParams instance if the parameter is not present in the local one. The state of the local collection can be mutated, whereas the default collection is treated as read-only.
|
[
"HttpParams",
"implementation",
"that",
"delegates",
"resolution",
"of",
"a",
"parameter",
"to",
"the",
"given",
"default",
"HttpParams",
"instance",
"if",
"the",
"parameter",
"is",
"not",
"present",
"in",
"the",
"local",
"one",
".",
"The",
"state",
"of",
"the",
"local",
"collection",
"can",
"be",
"mutated",
"whereas",
"the",
"default",
"collection",
"is",
"treated",
"as",
"read",
"-",
"only",
"."
] |
[Dot42.DexImport("org/apache/http/params/DefaultedHttpParams", AccessFlags = 49)]
public sealed partial class DefaultedHttpParams : global::Org.Apache.Http.Params.AbstractHttpParams
{
[Dot42.DexImport("<init>", "(Lorg/apache/http/params/HttpParams;Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1)]
public DefaultedHttpParams(global::Org.Apache.Http.Params.IHttpParams local, global::Org.Apache.Http.Params.IHttpParams defaults)
{
}
[Dot42.DexImport("copy", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1)]
public override global::Org.Apache.Http.Params.IHttpParams Copy()
{
return default(global::Org.Apache.Http.Params.IHttpParams);
}
[Dot42.DexImport("getParameter", "(Ljava/lang/String;)Ljava/lang/Object;", AccessFlags = 1)]
public override object GetParameter(string name)
{
return default(object);
}
[Dot42.DexImport("removeParameter", "(Ljava/lang/String;)Z", AccessFlags = 1)]
public override bool RemoveParameter(string name)
{
return default(bool);
}
[Dot42.DexImport("setParameter", "(Ljava/lang/String;Ljava/lang/Object;)Lorg/apache/http/params/HttpParams;", AccessFlags = 1)]
public override global::Org.Apache.Http.Params.IHttpParams SetParameter(string name, object value)
{
return default(global::Org.Apache.Http.Params.IHttpParams);
}
[Dot42.DexImport("getDefaults", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1)]
public global::Org.Apache.Http.Params.IHttpParams GetDefaults()
{
return default(global::Org.Apache.Http.Params.IHttpParams);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal DefaultedHttpParams()
{
}
public global::Org.Apache.Http.Params.IHttpParams Defaults
{
[Dot42.DexImport("getDefaults", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1)]
get{ return GetDefaults(); }
}
}
|
[
"[",
"Dot42",
".",
"DexImport",
"(",
"\"",
"org/apache/http/params/DefaultedHttpParams",
"\"",
",",
"AccessFlags",
"=",
"49",
")",
"]",
"public",
"sealed",
"partial",
"class",
"DefaultedHttpParams",
":",
"global",
"::",
"Org",
".",
"Apache",
".",
"Http",
".",
"Params",
".",
"AbstractHttpParams",
"{",
"[",
"Dot42",
".",
"DexImport",
"(",
"\"",
"<init>",
"\"",
",",
"\"",
"(Lorg/apache/http/params/HttpParams;Lorg/apache/http/params/HttpParams;)V",
"\"",
",",
"AccessFlags",
"=",
"1",
")",
"]",
"public",
"DefaultedHttpParams",
"(",
"global",
"::",
"Org",
".",
"Apache",
".",
"Http",
".",
"Params",
".",
"IHttpParams",
"local",
",",
"global",
"::",
"Org",
".",
"Apache",
".",
"Http",
".",
"Params",
".",
"IHttpParams",
"defaults",
")",
"{",
"}",
"[",
"Dot42",
".",
"DexImport",
"(",
"\"",
"copy",
"\"",
",",
"\"",
"()Lorg/apache/http/params/HttpParams;",
"\"",
",",
"AccessFlags",
"=",
"1",
")",
"]",
"public",
"override",
"global",
"::",
"Org",
".",
"Apache",
".",
"Http",
".",
"Params",
".",
"IHttpParams",
"Copy",
"(",
")",
"{",
"return",
"default",
"(",
"global",
"::",
"Org",
".",
"Apache",
".",
"Http",
".",
"Params",
".",
"IHttpParams",
")",
";",
"}",
"[",
"Dot42",
".",
"DexImport",
"(",
"\"",
"getParameter",
"\"",
",",
"\"",
"(Ljava/lang/String;)Ljava/lang/Object;",
"\"",
",",
"AccessFlags",
"=",
"1",
")",
"]",
"public",
"override",
"object",
"GetParameter",
"(",
"string",
"name",
")",
"{",
"return",
"default",
"(",
"object",
")",
";",
"}",
"[",
"Dot42",
".",
"DexImport",
"(",
"\"",
"removeParameter",
"\"",
",",
"\"",
"(Ljava/lang/String;)Z",
"\"",
",",
"AccessFlags",
"=",
"1",
")",
"]",
"public",
"override",
"bool",
"RemoveParameter",
"(",
"string",
"name",
")",
"{",
"return",
"default",
"(",
"bool",
")",
";",
"}",
"[",
"Dot42",
".",
"DexImport",
"(",
"\"",
"setParameter",
"\"",
",",
"\"",
"(Ljava/lang/String;Ljava/lang/Object;)Lorg/apache/http/params/HttpParams;",
"\"",
",",
"AccessFlags",
"=",
"1",
")",
"]",
"public",
"override",
"global",
"::",
"Org",
".",
"Apache",
".",
"Http",
".",
"Params",
".",
"IHttpParams",
"SetParameter",
"(",
"string",
"name",
",",
"object",
"value",
")",
"{",
"return",
"default",
"(",
"global",
"::",
"Org",
".",
"Apache",
".",
"Http",
".",
"Params",
".",
"IHttpParams",
")",
";",
"}",
"[",
"Dot42",
".",
"DexImport",
"(",
"\"",
"getDefaults",
"\"",
",",
"\"",
"()Lorg/apache/http/params/HttpParams;",
"\"",
",",
"AccessFlags",
"=",
"1",
")",
"]",
"public",
"global",
"::",
"Org",
".",
"Apache",
".",
"Http",
".",
"Params",
".",
"IHttpParams",
"GetDefaults",
"(",
")",
"{",
"return",
"default",
"(",
"global",
"::",
"Org",
".",
"Apache",
".",
"Http",
".",
"Params",
".",
"IHttpParams",
")",
";",
"}",
"[",
"global",
"::",
"System",
".",
"ComponentModel",
".",
"EditorBrowsable",
"(",
"global",
"::",
"System",
".",
"ComponentModel",
".",
"EditorBrowsableState",
".",
"Never",
")",
"]",
"internal",
"DefaultedHttpParams",
"(",
")",
"{",
"}",
"public",
"global",
"::",
"Org",
".",
"Apache",
".",
"Http",
".",
"Params",
".",
"IHttpParams",
"Defaults",
"{",
"[",
"Dot42",
".",
"DexImport",
"(",
"\"",
"getDefaults",
"\"",
",",
"\"",
"()Lorg/apache/http/params/HttpParams;",
"\"",
",",
"AccessFlags",
"=",
"1",
")",
"]",
"get",
"{",
"return",
"GetDefaults",
"(",
")",
";",
"}",
"}",
"}"
] |
HttpParams implementation that delegates resolution of a parameter to the given default HttpParams instance if the parameter is not present in the local one.
|
[
"HttpParams",
"implementation",
"that",
"delegates",
"resolution",
"of",
"a",
"parameter",
"to",
"the",
"given",
"default",
"HttpParams",
"instance",
"if",
"the",
"parameter",
"is",
"not",
"present",
"in",
"the",
"local",
"one",
"."
] |
[
"/* scope: __dot42__ */",
"/* MethodBuilder.Create */",
"/// <summary>",
"/// <para>Creates a copy of the local collection with the same default </para> ",
"/// </summary>",
"/// <java-name>",
"/// copy",
"/// </java-name>",
"/* MethodBuilder.Create */",
"/// <summary>",
"/// <para>Retrieves the value of the parameter from the local collection and, if the parameter is not set locally, delegates its resolution to the default collection. </para> ",
"/// </summary>",
"/// <java-name>",
"/// getParameter",
"/// </java-name>",
"/* MethodBuilder.Create */",
"/// <summary>",
"/// <para>Attempts to remove the parameter from the local collection. This method <b>does not</b> modify the default collection. </para> ",
"/// </summary>",
"/// <java-name>",
"/// removeParameter",
"/// </java-name>",
"/* MethodBuilder.Create */",
"/// <summary>",
"/// <para>Sets the parameter in the local collection. This method <b>does not</b> modify the default collection. </para> ",
"/// </summary>",
"/// <java-name>",
"/// setParameter",
"/// </java-name>",
"/* MethodBuilder.Create */",
"/// <java-name>",
"/// getDefaults",
"/// </java-name>",
"/* MethodBuilder.Create */",
"/* TypeBuilder.AddDefaultConstructor */",
"/// <java-name>",
"/// getDefaults",
"/// </java-name>"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": [
{
"identifier": "java-name",
"docstring": null,
"docstring_tokens": [
"None"
]
}
]
}
| false
| 13
| 526
| 113
|
66f6318b85230b4eadf25f0c2be5399e575ae50d
|
chef-boneyard/tf_delivery_cluster
|
cookbooks/delivery-cluster/libraries/helpers_delivery.rb
|
[
"Apache-2.0"
] |
Ruby
|
DeliveryCluster
|
#
# Cookbook Name:: delivery-cluster
# Library:: helpers_delivery
#
# Author:: Salim Afiune (<[email protected]>)
#
# Copyright:: Copyright (c) 2015 Chef Software, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
|
Cookbook Name:: delivery-cluster
Library:: helpers_delivery
: Salim Afiune ()
: Copyright (c) 2015 Chef Software, Inc.
License:: Apache License, Version 2.0
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
|
[
"Cookbook",
"Name",
"::",
"delivery",
"-",
"cluster",
"Library",
"::",
"helpers_delivery",
":",
"Salim",
"Afiune",
"()",
":",
"Copyright",
"(",
"c",
")",
"2015",
"Chef",
"Software",
"Inc",
".",
"License",
"::",
"Apache",
"License",
"Version",
"2",
".",
"0",
"Licensed",
"under",
"the",
"Apache",
"License",
"Version",
"2",
".",
"0",
"(",
"the",
"\"",
"License",
"\"",
")",
";",
"you",
"may",
"not",
"use",
"this",
"file",
"except",
"in",
"compliance",
"with",
"the",
"License",
".",
"You",
"may",
"obtain",
"a",
"copy",
"of",
"the",
"License",
"at",
"Unless",
"required",
"by",
"applicable",
"law",
"or",
"agreed",
"to",
"in",
"writing",
"software",
"distributed",
"under",
"the",
"License",
"is",
"distributed",
"on",
"an",
"\"",
"AS",
"IS",
"\"",
"BASIS",
"WITHOUT",
"WARRANTIES",
"OR",
"CONDITIONS",
"OF",
"ANY",
"KIND",
"either",
"express",
"or",
"implied",
".",
"See",
"the",
"License",
"for",
"the",
"specific",
"language",
"governing",
"permissions",
"and",
"limitations",
"under",
"the",
"License",
"."
] |
module DeliveryCluster
module Helpers
#
# Delivery Module
#
# This module provides helpers related to the Delivery Component
module Delivery
module_function
# Get the Hostname of the Delivery Server
#
# @param node [Chef::Node] Chef Node object
# @return hostname [String] The hostname of the Delivery server
def delivery_server_hostname(node)
DeliveryCluster::Helpers::Component.component_hostname(node, 'delivery')
end
# Returns the FQDN of the Delivery Server
#
# @param node [Chef::Node] Chef Node object
# @return [String] Delivery FQDN
def delivery_server_fqdn(node)
@delivery_server_fqdn ||= DeliveryCluster::Helpers::Component.component_fqdn(node, 'delivery')
end
# Generates the Delivery Server Attributes
#
# @param node [Chef::Node] Chef Node object
# @return [Hash] Delivery attributes for a machine resource
def delivery_server_attributes(node)
# If we want to pull down the packages from Chef Artifactory
if node['delivery-cluster']['delivery']['artifactory']
artifact = delivery_artifact(node)
node.set['delivery-cluster']['delivery']['version'] = artifact['version']
node.set['delivery-cluster']['delivery']['artifact'] = artifact['artifact']
node.set['delivery-cluster']['delivery']['checksum'] = artifact['checksum']
end
# Configuring the chef-server url for delivery
node.set['delivery-cluster']['delivery']['chef_server'] = DeliveryCluster::Helpers::ChefServer.chef_server_url(node) unless node['delivery-cluster']['delivery']['chef_server']
# Ensure we have a Delivery FQDN
node.set['delivery-cluster']['delivery']['fqdn'] = delivery_server_fqdn(node) unless node['delivery-cluster']['delivery']['fqdn']
Chef::Mixin::DeepMerge.hash_only_merge(
{ 'delivery-cluster' => node['delivery-cluster'] },
DeliveryCluster::Helpers::Component.component_attributes(node, 'delivery')
)
end
# Delivery Artifact
# We will get the Delivery Package from artifactory (Require Chef VPN)
#
# Get the latest artifact:
# => artifact = get_delivery_artifact('latest', 'redhat', '6.5')
#
# Get specific artifact:
# => artifact = get_delivery_artifact('0.2.21', 'ubuntu', '12.04', '/var/tmp')
#
# @param node [Chef::Node] Chef Node object
# @return [Hash] Delivery Artifact
def delivery_artifact(node)
@delivery_artifact ||= begin
artifact = get_delivery_artifact(
node,
node['delivery-cluster']['delivery']['version'],
DeliveryCluster::Helpers::Component.component_node(node, 'delivery')['platform'],
DeliveryCluster::Helpers::Component.component_node(node, 'delivery')['platform_version'],
node['delivery-cluster']['delivery']['pass-through'] ? nil : DeliveryCluster::Helpers.cluster_data_dir(node)
)
delivery_artifact = {
'version' => artifact['version'],
'checksum' => artifact['checksum']
}
# Upload Artifact to Delivery Server only if we have donwloaded the artifact
if artifact['local_path']
machine_file = Chef::Resource::MachineFile.new("/var/tmp/#{artifact['name']}", run_context)
machine_file.chef_server(DeliveryCluster::Helpers::ChefServer.chef_server_config(node))
machine_file.machine(node['delivery-cluster']['delivery']['hostname'])
machine_file.local_path(artifact['local_path'])
machine_file.run_action(:upload)
delivery_artifact['artifact'] = "/var/tmp/#{artifact['name']}"
else
delivery_artifact['artifact'] = artifact['uri']
end
delivery_artifact
end
end
# Return the delivery-ctl command
# The delivery-ctl needs to be executed with elevated privileges
# we validate the user that is coming from the provisioning abstraction
#
# @param node [Chef::Node] Chef Node object
# @return [String] delivery-ctl command
def delivery_ctl(node)
DeliveryCluster::Helpers.username(node) == 'root' ? 'delivery-ctl' : 'sudo -E delivery-ctl'
end
# Return the command to create an enterprise
#
# @param node [Chef::Node] Chef Node object
# @return [String] delivery-ctl command to create an enterprise
def delivery_enterprise_cmd(node)
# Validating that the enterprise does not already exist
cmd = <<-CMD.gsub(/\s+/, ' ').strip!
#{delivery_ctl(node)} list-enterprises | grep -w ^#{node['delivery-cluster']['delivery']['enterprise']};
[ $? -ne 0 ] && #{delivery_ctl(node)} create-enterprise #{node['delivery-cluster']['delivery']['enterprise']}
CMD
# We have introduced an additional constrain to the enterprise_ctl
# command that require to specify --ssh-pub-key-file param starting
# from the Delivery Version 0.2.52
if node['delivery-cluster']['delivery']['version'] == 'latest' ||
Gem::Version.new(node['delivery-cluster']['delivery']['version']) > Gem::Version.new('0.2.52')
cmd << ' --ssh-pub-key-file=/etc/delivery/builder_key.pub'
end
cmd << " > /tmp/#{node['delivery-cluster']['delivery']['enterprise']}.creds || echo 1"
end
end
end
# Module that exposes multiple helpers
module DSL
# Hostname of the Delivery Server
def delivery_server_hostname
DeliveryCluster::Helpers::Delivery.delivery_server_hostname(node)
end
# FQDN of the Delivery Server
def delivery_server_fqdn
DeliveryCluster::Helpers::Delivery.delivery_server_fqdn(node)
end
# Delivery Server Attributes
def delivery_server_attributes
DeliveryCluster::Helpers::Delivery.delivery_server_attributes(node)
end
# Delivery Artifact
def delivery_artifact
DeliveryCluster::Helpers::Delivery.delivery_artifact(node)
end
# Return the delivery-ctl command
def delivery_ctl
DeliveryCluster::Helpers::Delivery.delivery_ctl(node)
end
# Return the command to create an enterprise
def delivery_enterprise_cmd
DeliveryCluster::Helpers::Delivery.delivery_enterprise_cmd(node)
end
end
end
|
[
"module",
"DeliveryCluster",
"module",
"Helpers",
"module",
"Delivery",
"module_function",
"def",
"delivery_server_hostname",
"(",
"node",
")",
"DeliveryCluster",
"::",
"Helpers",
"::",
"Component",
".",
"component_hostname",
"(",
"node",
",",
"'delivery'",
")",
"end",
"def",
"delivery_server_fqdn",
"(",
"node",
")",
"@delivery_server_fqdn",
"||=",
"DeliveryCluster",
"::",
"Helpers",
"::",
"Component",
".",
"component_fqdn",
"(",
"node",
",",
"'delivery'",
")",
"end",
"def",
"delivery_server_attributes",
"(",
"node",
")",
"if",
"node",
"[",
"'delivery-cluster'",
"]",
"[",
"'delivery'",
"]",
"[",
"'artifactory'",
"]",
"artifact",
"=",
"delivery_artifact",
"(",
"node",
")",
"node",
".",
"set",
"[",
"'delivery-cluster'",
"]",
"[",
"'delivery'",
"]",
"[",
"'version'",
"]",
"=",
"artifact",
"[",
"'version'",
"]",
"node",
".",
"set",
"[",
"'delivery-cluster'",
"]",
"[",
"'delivery'",
"]",
"[",
"'artifact'",
"]",
"=",
"artifact",
"[",
"'artifact'",
"]",
"node",
".",
"set",
"[",
"'delivery-cluster'",
"]",
"[",
"'delivery'",
"]",
"[",
"'checksum'",
"]",
"=",
"artifact",
"[",
"'checksum'",
"]",
"end",
"node",
".",
"set",
"[",
"'delivery-cluster'",
"]",
"[",
"'delivery'",
"]",
"[",
"'chef_server'",
"]",
"=",
"DeliveryCluster",
"::",
"Helpers",
"::",
"ChefServer",
".",
"chef_server_url",
"(",
"node",
")",
"unless",
"node",
"[",
"'delivery-cluster'",
"]",
"[",
"'delivery'",
"]",
"[",
"'chef_server'",
"]",
"node",
".",
"set",
"[",
"'delivery-cluster'",
"]",
"[",
"'delivery'",
"]",
"[",
"'fqdn'",
"]",
"=",
"delivery_server_fqdn",
"(",
"node",
")",
"unless",
"node",
"[",
"'delivery-cluster'",
"]",
"[",
"'delivery'",
"]",
"[",
"'fqdn'",
"]",
"Chef",
"::",
"Mixin",
"::",
"DeepMerge",
".",
"hash_only_merge",
"(",
"{",
"'delivery-cluster'",
"=>",
"node",
"[",
"'delivery-cluster'",
"]",
"}",
",",
"DeliveryCluster",
"::",
"Helpers",
"::",
"Component",
".",
"component_attributes",
"(",
"node",
",",
"'delivery'",
")",
")",
"end",
"def",
"delivery_artifact",
"(",
"node",
")",
"@delivery_artifact",
"||=",
"begin",
"artifact",
"=",
"get_delivery_artifact",
"(",
"node",
",",
"node",
"[",
"'delivery-cluster'",
"]",
"[",
"'delivery'",
"]",
"[",
"'version'",
"]",
",",
"DeliveryCluster",
"::",
"Helpers",
"::",
"Component",
".",
"component_node",
"(",
"node",
",",
"'delivery'",
")",
"[",
"'platform'",
"]",
",",
"DeliveryCluster",
"::",
"Helpers",
"::",
"Component",
".",
"component_node",
"(",
"node",
",",
"'delivery'",
")",
"[",
"'platform_version'",
"]",
",",
"node",
"[",
"'delivery-cluster'",
"]",
"[",
"'delivery'",
"]",
"[",
"'pass-through'",
"]",
"?",
"nil",
":",
"DeliveryCluster",
"::",
"Helpers",
".",
"cluster_data_dir",
"(",
"node",
")",
")",
"delivery_artifact",
"=",
"{",
"'version'",
"=>",
"artifact",
"[",
"'version'",
"]",
",",
"'checksum'",
"=>",
"artifact",
"[",
"'checksum'",
"]",
"}",
"if",
"artifact",
"[",
"'local_path'",
"]",
"machine_file",
"=",
"Chef",
"::",
"Resource",
"::",
"MachineFile",
".",
"new",
"(",
"\"/var/tmp/#{artifact['name']}\"",
",",
"run_context",
")",
"machine_file",
".",
"chef_server",
"(",
"DeliveryCluster",
"::",
"Helpers",
"::",
"ChefServer",
".",
"chef_server_config",
"(",
"node",
")",
")",
"machine_file",
".",
"machine",
"(",
"node",
"[",
"'delivery-cluster'",
"]",
"[",
"'delivery'",
"]",
"[",
"'hostname'",
"]",
")",
"machine_file",
".",
"local_path",
"(",
"artifact",
"[",
"'local_path'",
"]",
")",
"machine_file",
".",
"run_action",
"(",
":upload",
")",
"delivery_artifact",
"[",
"'artifact'",
"]",
"=",
"\"/var/tmp/#{artifact['name']}\"",
"else",
"delivery_artifact",
"[",
"'artifact'",
"]",
"=",
"artifact",
"[",
"'uri'",
"]",
"end",
"delivery_artifact",
"end",
"end",
"def",
"delivery_ctl",
"(",
"node",
")",
"DeliveryCluster",
"::",
"Helpers",
".",
"username",
"(",
"node",
")",
"==",
"'root'",
"?",
"'delivery-ctl'",
":",
"'sudo -E delivery-ctl'",
"end",
"def",
"delivery_enterprise_cmd",
"(",
"node",
")",
"cmd",
"=",
"<<-CMD",
".",
"gsub",
"(",
"/",
"\\s",
"+",
"/",
",",
"' '",
")",
".",
"strip!",
"\n ",
"#{",
"delivery_ctl",
"(",
"node",
")",
"}",
" list-enterprises | grep -w ^",
"#{",
"node",
"[",
"'delivery-cluster'",
"]",
"[",
"'delivery'",
"]",
"[",
"'enterprise'",
"]",
"}",
";\n [ $? -ne 0 ] && ",
"#{",
"delivery_ctl",
"(",
"node",
")",
"}",
" create-enterprise ",
"#{",
"node",
"[",
"'delivery-cluster'",
"]",
"[",
"'delivery'",
"]",
"[",
"'enterprise'",
"]",
"}",
"\n ",
"CMD",
"if",
"node",
"[",
"'delivery-cluster'",
"]",
"[",
"'delivery'",
"]",
"[",
"'version'",
"]",
"==",
"'latest'",
"||",
"Gem",
"::",
"Version",
".",
"new",
"(",
"node",
"[",
"'delivery-cluster'",
"]",
"[",
"'delivery'",
"]",
"[",
"'version'",
"]",
")",
">",
"Gem",
"::",
"Version",
".",
"new",
"(",
"'0.2.52'",
")",
"cmd",
"<<",
"' --ssh-pub-key-file=/etc/delivery/builder_key.pub'",
"end",
"cmd",
"<<",
"\" > /tmp/#{node['delivery-cluster']['delivery']['enterprise']}.creds || echo 1\"",
"end",
"end",
"end",
"module",
"DSL",
"def",
"delivery_server_hostname",
"DeliveryCluster",
"::",
"Helpers",
"::",
"Delivery",
".",
"delivery_server_hostname",
"(",
"node",
")",
"end",
"def",
"delivery_server_fqdn",
"DeliveryCluster",
"::",
"Helpers",
"::",
"Delivery",
".",
"delivery_server_fqdn",
"(",
"node",
")",
"end",
"def",
"delivery_server_attributes",
"DeliveryCluster",
"::",
"Helpers",
"::",
"Delivery",
".",
"delivery_server_attributes",
"(",
"node",
")",
"end",
"def",
"delivery_artifact",
"DeliveryCluster",
"::",
"Helpers",
"::",
"Delivery",
".",
"delivery_artifact",
"(",
"node",
")",
"end",
"def",
"delivery_ctl",
"DeliveryCluster",
"::",
"Helpers",
"::",
"Delivery",
".",
"delivery_ctl",
"(",
"node",
")",
"end",
"def",
"delivery_enterprise_cmd",
"DeliveryCluster",
"::",
"Helpers",
"::",
"Delivery",
".",
"delivery_enterprise_cmd",
"(",
"node",
")",
"end",
"end",
"end"
] |
Cookbook Name:: delivery-cluster
Library:: helpers_delivery
|
[
"Cookbook",
"Name",
"::",
"delivery",
"-",
"cluster",
"Library",
"::",
"helpers_delivery"
] |
[
"#",
"# Delivery Module",
"#",
"# This module provides helpers related to the Delivery Component",
"# Get the Hostname of the Delivery Server",
"#",
"# @param node [Chef::Node] Chef Node object",
"# @return hostname [String] The hostname of the Delivery server",
"# Returns the FQDN of the Delivery Server",
"#",
"# @param node [Chef::Node] Chef Node object",
"# @return [String] Delivery FQDN",
"# Generates the Delivery Server Attributes",
"#",
"# @param node [Chef::Node] Chef Node object",
"# @return [Hash] Delivery attributes for a machine resource",
"# If we want to pull down the packages from Chef Artifactory",
"# Configuring the chef-server url for delivery",
"# Ensure we have a Delivery FQDN",
"# Delivery Artifact",
"# We will get the Delivery Package from artifactory (Require Chef VPN)",
"#",
"# Get the latest artifact:",
"# => artifact = get_delivery_artifact('latest', 'redhat', '6.5')",
"#",
"# Get specific artifact:",
"# => artifact = get_delivery_artifact('0.2.21', 'ubuntu', '12.04', '/var/tmp')",
"#",
"# @param node [Chef::Node] Chef Node object",
"# @return [Hash] Delivery Artifact",
"# Upload Artifact to Delivery Server only if we have donwloaded the artifact",
"# Return the delivery-ctl command",
"# The delivery-ctl needs to be executed with elevated privileges",
"# we validate the user that is coming from the provisioning abstraction",
"#",
"# @param node [Chef::Node] Chef Node object",
"# @return [String] delivery-ctl command",
"# Return the command to create an enterprise",
"#",
"# @param node [Chef::Node] Chef Node object",
"# @return [String] delivery-ctl command to create an enterprise",
"# Validating that the enterprise does not already exist",
"# We have introduced an additional constrain to the enterprise_ctl",
"# command that require to specify --ssh-pub-key-file param starting",
"# from the Delivery Version 0.2.52",
"# Module that exposes multiple helpers",
"# Hostname of the Delivery Server",
"# FQDN of the Delivery Server",
"# Delivery Server Attributes",
"# Delivery Artifact",
"# Return the delivery-ctl command",
"# Return the command to create an enterprise"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 20
| 1,398
| 181
|
c02d9765516388626d8b19c500f9db9fc049c6f0
|
vjacquet/WmcSoft
|
Tools/WmcSoft.VisualStudio/CustomTools/Design/CustomToolBase.cs
|
[
"MIT"
] |
C#
|
CustomToolBase
|
/// <summary>
/// Base class for all custom tools.
/// </summary>
/// <remarks>
/// Inheriting classes must provide a <see cref="GuidAttribute"/>, static
/// methods with <see cref="ComRegisterFunctionAttribute"/> and <see cref="ComUnregisterFunctionAttribute"/>,
/// which should call this class <see cref="Register"/> and <see cref="UnRegister"/>
/// methods, passing the required parameters.
/// </remarks>
|
Base class for all custom tools.
|
[
"Base",
"class",
"for",
"all",
"custom",
"tools",
"."
] |
public abstract class CustomToolBase : VisualStudio.BaseCodeGeneratorWithSite
{
#region Constants
const string RegistryKey = @"SOFTWARE\Microsoft\VisualStudio\{0}.{1}\Generators\{2}\{3}";
const string TemplateAutogenerated = @"//------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by the {0} tool.
// Tool Version: {1}
// Runtime Version: {2}
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </autogenerated>
//------------------------------------------------------------------------------
";
#endregion Constants
protected override sealed byte[] GenerateCode(string inputFileName, string inputFileContent)
{
try {
string code = OnGenerateCode(inputFileContent, inputFileContent);
return ConvertStringToBytes(code);
} catch (Exception ex) {
if (ex is TargetInvocationException) {
ex = ex.InnerException;
}
return ConvertStringToBytes(String.Format(
CultureInfo.CurrentCulture,
Properties.Resources.CustomTool_GeneralError, ex));
}
}
private byte[] ConvertStringToBytes(string code)
{
return System.Text.Encoding.UTF8.GetBytes(code);
}
protected abstract string OnGenerateCode(string inputFileName, string inputFileContent);
public static string GetToolGeneratedCodeWarning(Type customToolType)
{
CustomToolAttribute attribute = (CustomToolAttribute)Attribute.GetCustomAttribute(
customToolType, typeof(CustomToolAttribute), true);
if (attribute == null) {
throw new ArgumentException(String.Format(
CultureInfo.CurrentCulture,
Properties.Resources.CustomTool_ToolRequiredAttributeMissing,
customToolType, typeof(CustomToolAttribute)));
}
return String.Format(TemplateAutogenerated,
attribute.Name,
GetAssembyVersion(customToolType),
Environment.Version);
}
private static object CustomToolAttribute(CustomToolAttribute customToolAttribute)
{
throw new NotImplementedException("The method or operation is not implemented.");
}
#region Properties
protected ProjectItem CurrentItem {
get {
return base.GetService(typeof(ProjectItem)) as ProjectItem;
}
}
protected VSProject CurrentProject {
get {
if (CurrentItem != null)
return CurrentItem.ContainingProject.Object as VSProject;
return null;
}
}
#endregion Properties
#region Service access
public override object GetService(Type serviceType)
{
object svc = base.GetService(serviceType);
if (svc == null && CurrentItem == null)
return null;
IOleServiceProvider ole =
CurrentItem.DTE as IOleServiceProvider;
if (ole != null)
return new ComServiceProvider(ole).GetService(serviceType);
return null;
}
#endregion Service access
#region Registration and Installation
public static void Register(Type type)
{
Guid generator;
CustomToolAttribute tool;
SupportedVersionAttribute[] versions;
SupportedCategoryAttribute[] categories;
string description;
GetAttributes(type, out generator, out tool, out versions, out categories, out description);
foreach (SupportedVersionAttribute version in versions) {
foreach (SupportedCategoryAttribute category in categories) {
RegisterCustomTool(generator, category.Guid, version.Version,
description, tool.Name, tool.GeneratesDesignTimeCode);
}
}
}
public static void UnRegister(Type type)
{
Guid generator;
CustomToolAttribute tool;
SupportedVersionAttribute[] versions;
SupportedCategoryAttribute[] categories;
string description;
GetAttributes(type, out generator, out tool, out versions, out categories, out description);
foreach (SupportedVersionAttribute version in versions) {
foreach (SupportedCategoryAttribute category in categories) {
UnRegisterCustomTool(category.Guid, version.Version, tool.Name);
}
}
}
#endregion Registration and Installation
#region Helper methods
private static void RegisterCustomTool(Guid generator, Guid category, Version vsVersion,
string description, string toolName, bool generatesDesignTimeCode)
{
string keypath = String.Format(RegistryKey, vsVersion.Major, vsVersion.Minor,
category.ToString("B"), toolName);
using (RegistryKey key = Registry.LocalMachine.CreateSubKey(keypath)) {
key.SetValue("", description);
key.SetValue("CLSID", generator.ToString("B"));
key.SetValue("GeneratesDesignTimeSource",
generatesDesignTimeCode ? 1 : 0);
}
}
private static void UnRegisterCustomTool(Guid category, Version vsVersion, string toolName)
{
string key = String.Format(RegistryKey, vsVersion.Major, vsVersion.Minor,
category.ToString("B"), toolName);
Registry.LocalMachine.DeleteSubKey(key, false);
}
private static Version GetAssembyVersion(Type type)
{
object[] attrs = type.Assembly.GetCustomAttributes(typeof(AssemblyVersionAttribute), true);
if (attrs.Length == 0)
throw new ArgumentException(String.Format(
CultureInfo.CurrentCulture,
Properties.Resources.Tool_AttributeMissing,
type, typeof(AssemblyVersionAttribute)));
return new Version(((AssemblyVersionAttribute)attrs[0]).Version);
}
private static void GetAttributes(Type type, out Guid generator, out CustomToolAttribute tool,
out SupportedVersionAttribute[] versions, out SupportedCategoryAttribute[] categories, out string description)
{
object[] attrs;
attrs = type.GetCustomAttributes(typeof(GuidAttribute), false);
if (attrs.Length == 0)
throw new ArgumentException(String.Format(
CultureInfo.CurrentCulture,
Properties.Resources.Tool_AttributeMissing,
type, typeof(GuidAttribute)));
generator = new Guid(((GuidAttribute)attrs[0]).Value);
attrs = type.GetCustomAttributes(typeof(CustomToolAttribute), false);
if (attrs.Length == 0)
throw new ArgumentException(String.Format(
CultureInfo.CurrentCulture,
Properties.Resources.Tool_AttributeMissing,
type, typeof(CustomToolAttribute)));
tool = (CustomToolAttribute)attrs[0];
attrs = type.GetCustomAttributes(typeof(SupportedVersionAttribute), true);
if (attrs.Length == 0)
throw new ArgumentException(String.Format(
CultureInfo.CurrentCulture,
Properties.Resources.Tool_AttributeMissing,
type, typeof(SupportedVersionAttribute)));
versions = (SupportedVersionAttribute[])attrs;
attrs = type.GetCustomAttributes(typeof(SupportedCategoryAttribute), true);
if (attrs.Length == 0)
throw new ArgumentException(String.Format(
CultureInfo.CurrentCulture,
Properties.Resources.Tool_AttributeMissing,
type, typeof(SupportedCategoryAttribute)));
categories = (SupportedCategoryAttribute[])attrs;
attrs = type.GetCustomAttributes(typeof(DescriptionAttribute), true);
if (attrs.Length == 0)
throw new ArgumentException(String.Format(
CultureInfo.CurrentCulture,
Properties.Resources.Tool_AttributeMissing,
type, typeof(DescriptionAttribute)));
description = ((DescriptionAttribute)attrs[0]).Description;
}
#endregion
}
|
[
"public",
"abstract",
"class",
"CustomToolBase",
":",
"VisualStudio",
".",
"BaseCodeGeneratorWithSite",
"{",
"region",
" Constants",
"const",
"string",
"RegistryKey",
"=",
"@\"SOFTWARE\\Microsoft\\VisualStudio\\{0}.{1}\\Generators\\{2}\\{3}\"",
";",
"const",
"string",
"TemplateAutogenerated",
"=",
"@\"//------------------------------------------------------------------------------\n// <autogenerated>\n// This code was generated by the {0} tool.\n// Tool Version: {1}\n// Runtime Version: {2}\n//\n// Changes to this file may cause incorrect behavior and will be lost if\n// the code is regenerated.\n// </autogenerated>\n//------------------------------------------------------------------------------\n\"",
";",
"endregion",
" Constants",
"protected",
"override",
"sealed",
"byte",
"[",
"]",
"GenerateCode",
"(",
"string",
"inputFileName",
",",
"string",
"inputFileContent",
")",
"{",
"try",
"{",
"string",
"code",
"=",
"OnGenerateCode",
"(",
"inputFileContent",
",",
"inputFileContent",
")",
";",
"return",
"ConvertStringToBytes",
"(",
"code",
")",
";",
"}",
"catch",
"(",
"Exception",
"ex",
")",
"{",
"if",
"(",
"ex",
"is",
"TargetInvocationException",
")",
"{",
"ex",
"=",
"ex",
".",
"InnerException",
";",
"}",
"return",
"ConvertStringToBytes",
"(",
"String",
".",
"Format",
"(",
"CultureInfo",
".",
"CurrentCulture",
",",
"Properties",
".",
"Resources",
".",
"CustomTool_GeneralError",
",",
"ex",
")",
")",
";",
"}",
"}",
"private",
"byte",
"[",
"]",
"ConvertStringToBytes",
"(",
"string",
"code",
")",
"{",
"return",
"System",
".",
"Text",
".",
"Encoding",
".",
"UTF8",
".",
"GetBytes",
"(",
"code",
")",
";",
"}",
"protected",
"abstract",
"string",
"OnGenerateCode",
"(",
"string",
"inputFileName",
",",
"string",
"inputFileContent",
")",
";",
"public",
"static",
"string",
"GetToolGeneratedCodeWarning",
"(",
"Type",
"customToolType",
")",
"{",
"CustomToolAttribute",
"attribute",
"=",
"(",
"CustomToolAttribute",
")",
"Attribute",
".",
"GetCustomAttribute",
"(",
"customToolType",
",",
"typeof",
"(",
"CustomToolAttribute",
")",
",",
"true",
")",
";",
"if",
"(",
"attribute",
"==",
"null",
")",
"{",
"throw",
"new",
"ArgumentException",
"(",
"String",
".",
"Format",
"(",
"CultureInfo",
".",
"CurrentCulture",
",",
"Properties",
".",
"Resources",
".",
"CustomTool_ToolRequiredAttributeMissing",
",",
"customToolType",
",",
"typeof",
"(",
"CustomToolAttribute",
")",
")",
")",
";",
"}",
"return",
"String",
".",
"Format",
"(",
"TemplateAutogenerated",
",",
"attribute",
".",
"Name",
",",
"GetAssembyVersion",
"(",
"customToolType",
")",
",",
"Environment",
".",
"Version",
")",
";",
"}",
"private",
"static",
"object",
"CustomToolAttribute",
"(",
"CustomToolAttribute",
"customToolAttribute",
")",
"{",
"throw",
"new",
"NotImplementedException",
"(",
"\"",
"The method or operation is not implemented.",
"\"",
")",
";",
"}",
"region",
" Properties",
"protected",
"ProjectItem",
"CurrentItem",
"{",
"get",
"{",
"return",
"base",
".",
"GetService",
"(",
"typeof",
"(",
"ProjectItem",
")",
")",
"as",
"ProjectItem",
";",
"}",
"}",
"protected",
"VSProject",
"CurrentProject",
"{",
"get",
"{",
"if",
"(",
"CurrentItem",
"!=",
"null",
")",
"return",
"CurrentItem",
".",
"ContainingProject",
".",
"Object",
"as",
"VSProject",
";",
"return",
"null",
";",
"}",
"}",
"endregion",
" Properties",
"region",
" Service access",
"public",
"override",
"object",
"GetService",
"(",
"Type",
"serviceType",
")",
"{",
"object",
"svc",
"=",
"base",
".",
"GetService",
"(",
"serviceType",
")",
";",
"if",
"(",
"svc",
"==",
"null",
"&&",
"CurrentItem",
"==",
"null",
")",
"return",
"null",
";",
"IOleServiceProvider",
"ole",
"=",
"CurrentItem",
".",
"DTE",
"as",
"IOleServiceProvider",
";",
"if",
"(",
"ole",
"!=",
"null",
")",
"return",
"new",
"ComServiceProvider",
"(",
"ole",
")",
".",
"GetService",
"(",
"serviceType",
")",
";",
"return",
"null",
";",
"}",
"endregion",
" Service access",
"region",
" Registration and Installation",
"public",
"static",
"void",
"Register",
"(",
"Type",
"type",
")",
"{",
"Guid",
"generator",
";",
"CustomToolAttribute",
"tool",
";",
"SupportedVersionAttribute",
"[",
"]",
"versions",
";",
"SupportedCategoryAttribute",
"[",
"]",
"categories",
";",
"string",
"description",
";",
"GetAttributes",
"(",
"type",
",",
"out",
"generator",
",",
"out",
"tool",
",",
"out",
"versions",
",",
"out",
"categories",
",",
"out",
"description",
")",
";",
"foreach",
"(",
"SupportedVersionAttribute",
"version",
"in",
"versions",
")",
"{",
"foreach",
"(",
"SupportedCategoryAttribute",
"category",
"in",
"categories",
")",
"{",
"RegisterCustomTool",
"(",
"generator",
",",
"category",
".",
"Guid",
",",
"version",
".",
"Version",
",",
"description",
",",
"tool",
".",
"Name",
",",
"tool",
".",
"GeneratesDesignTimeCode",
")",
";",
"}",
"}",
"}",
"public",
"static",
"void",
"UnRegister",
"(",
"Type",
"type",
")",
"{",
"Guid",
"generator",
";",
"CustomToolAttribute",
"tool",
";",
"SupportedVersionAttribute",
"[",
"]",
"versions",
";",
"SupportedCategoryAttribute",
"[",
"]",
"categories",
";",
"string",
"description",
";",
"GetAttributes",
"(",
"type",
",",
"out",
"generator",
",",
"out",
"tool",
",",
"out",
"versions",
",",
"out",
"categories",
",",
"out",
"description",
")",
";",
"foreach",
"(",
"SupportedVersionAttribute",
"version",
"in",
"versions",
")",
"{",
"foreach",
"(",
"SupportedCategoryAttribute",
"category",
"in",
"categories",
")",
"{",
"UnRegisterCustomTool",
"(",
"category",
".",
"Guid",
",",
"version",
".",
"Version",
",",
"tool",
".",
"Name",
")",
";",
"}",
"}",
"}",
"endregion",
" Registration and Installation",
"region",
" Helper methods",
"private",
"static",
"void",
"RegisterCustomTool",
"(",
"Guid",
"generator",
",",
"Guid",
"category",
",",
"Version",
"vsVersion",
",",
"string",
"description",
",",
"string",
"toolName",
",",
"bool",
"generatesDesignTimeCode",
")",
"{",
"string",
"keypath",
"=",
"String",
".",
"Format",
"(",
"RegistryKey",
",",
"vsVersion",
".",
"Major",
",",
"vsVersion",
".",
"Minor",
",",
"category",
".",
"ToString",
"(",
"\"",
"B",
"\"",
")",
",",
"toolName",
")",
";",
"using",
"(",
"RegistryKey",
"key",
"=",
"Registry",
".",
"LocalMachine",
".",
"CreateSubKey",
"(",
"keypath",
")",
")",
"{",
"key",
".",
"SetValue",
"(",
"\"",
"\"",
",",
"description",
")",
";",
"key",
".",
"SetValue",
"(",
"\"",
"CLSID",
"\"",
",",
"generator",
".",
"ToString",
"(",
"\"",
"B",
"\"",
")",
")",
";",
"key",
".",
"SetValue",
"(",
"\"",
"GeneratesDesignTimeSource",
"\"",
",",
"generatesDesignTimeCode",
"?",
"1",
":",
"0",
")",
";",
"}",
"}",
"private",
"static",
"void",
"UnRegisterCustomTool",
"(",
"Guid",
"category",
",",
"Version",
"vsVersion",
",",
"string",
"toolName",
")",
"{",
"string",
"key",
"=",
"String",
".",
"Format",
"(",
"RegistryKey",
",",
"vsVersion",
".",
"Major",
",",
"vsVersion",
".",
"Minor",
",",
"category",
".",
"ToString",
"(",
"\"",
"B",
"\"",
")",
",",
"toolName",
")",
";",
"Registry",
".",
"LocalMachine",
".",
"DeleteSubKey",
"(",
"key",
",",
"false",
")",
";",
"}",
"private",
"static",
"Version",
"GetAssembyVersion",
"(",
"Type",
"type",
")",
"{",
"object",
"[",
"]",
"attrs",
"=",
"type",
".",
"Assembly",
".",
"GetCustomAttributes",
"(",
"typeof",
"(",
"AssemblyVersionAttribute",
")",
",",
"true",
")",
";",
"if",
"(",
"attrs",
".",
"Length",
"==",
"0",
")",
"throw",
"new",
"ArgumentException",
"(",
"String",
".",
"Format",
"(",
"CultureInfo",
".",
"CurrentCulture",
",",
"Properties",
".",
"Resources",
".",
"Tool_AttributeMissing",
",",
"type",
",",
"typeof",
"(",
"AssemblyVersionAttribute",
")",
")",
")",
";",
"return",
"new",
"Version",
"(",
"(",
"(",
"AssemblyVersionAttribute",
")",
"attrs",
"[",
"0",
"]",
")",
".",
"Version",
")",
";",
"}",
"private",
"static",
"void",
"GetAttributes",
"(",
"Type",
"type",
",",
"out",
"Guid",
"generator",
",",
"out",
"CustomToolAttribute",
"tool",
",",
"out",
"SupportedVersionAttribute",
"[",
"]",
"versions",
",",
"out",
"SupportedCategoryAttribute",
"[",
"]",
"categories",
",",
"out",
"string",
"description",
")",
"{",
"object",
"[",
"]",
"attrs",
";",
"attrs",
"=",
"type",
".",
"GetCustomAttributes",
"(",
"typeof",
"(",
"GuidAttribute",
")",
",",
"false",
")",
";",
"if",
"(",
"attrs",
".",
"Length",
"==",
"0",
")",
"throw",
"new",
"ArgumentException",
"(",
"String",
".",
"Format",
"(",
"CultureInfo",
".",
"CurrentCulture",
",",
"Properties",
".",
"Resources",
".",
"Tool_AttributeMissing",
",",
"type",
",",
"typeof",
"(",
"GuidAttribute",
")",
")",
")",
";",
"generator",
"=",
"new",
"Guid",
"(",
"(",
"(",
"GuidAttribute",
")",
"attrs",
"[",
"0",
"]",
")",
".",
"Value",
")",
";",
"attrs",
"=",
"type",
".",
"GetCustomAttributes",
"(",
"typeof",
"(",
"CustomToolAttribute",
")",
",",
"false",
")",
";",
"if",
"(",
"attrs",
".",
"Length",
"==",
"0",
")",
"throw",
"new",
"ArgumentException",
"(",
"String",
".",
"Format",
"(",
"CultureInfo",
".",
"CurrentCulture",
",",
"Properties",
".",
"Resources",
".",
"Tool_AttributeMissing",
",",
"type",
",",
"typeof",
"(",
"CustomToolAttribute",
")",
")",
")",
";",
"tool",
"=",
"(",
"CustomToolAttribute",
")",
"attrs",
"[",
"0",
"]",
";",
"attrs",
"=",
"type",
".",
"GetCustomAttributes",
"(",
"typeof",
"(",
"SupportedVersionAttribute",
")",
",",
"true",
")",
";",
"if",
"(",
"attrs",
".",
"Length",
"==",
"0",
")",
"throw",
"new",
"ArgumentException",
"(",
"String",
".",
"Format",
"(",
"CultureInfo",
".",
"CurrentCulture",
",",
"Properties",
".",
"Resources",
".",
"Tool_AttributeMissing",
",",
"type",
",",
"typeof",
"(",
"SupportedVersionAttribute",
")",
")",
")",
";",
"versions",
"=",
"(",
"SupportedVersionAttribute",
"[",
"]",
")",
"attrs",
";",
"attrs",
"=",
"type",
".",
"GetCustomAttributes",
"(",
"typeof",
"(",
"SupportedCategoryAttribute",
")",
",",
"true",
")",
";",
"if",
"(",
"attrs",
".",
"Length",
"==",
"0",
")",
"throw",
"new",
"ArgumentException",
"(",
"String",
".",
"Format",
"(",
"CultureInfo",
".",
"CurrentCulture",
",",
"Properties",
".",
"Resources",
".",
"Tool_AttributeMissing",
",",
"type",
",",
"typeof",
"(",
"SupportedCategoryAttribute",
")",
")",
")",
";",
"categories",
"=",
"(",
"SupportedCategoryAttribute",
"[",
"]",
")",
"attrs",
";",
"attrs",
"=",
"type",
".",
"GetCustomAttributes",
"(",
"typeof",
"(",
"DescriptionAttribute",
")",
",",
"true",
")",
";",
"if",
"(",
"attrs",
".",
"Length",
"==",
"0",
")",
"throw",
"new",
"ArgumentException",
"(",
"String",
".",
"Format",
"(",
"CultureInfo",
".",
"CurrentCulture",
",",
"Properties",
".",
"Resources",
".",
"Tool_AttributeMissing",
",",
"type",
",",
"typeof",
"(",
"DescriptionAttribute",
")",
")",
")",
";",
"description",
"=",
"(",
"(",
"DescriptionAttribute",
")",
"attrs",
"[",
"0",
"]",
")",
".",
"Description",
";",
"}",
"endregion",
"}"
] |
Base class for all custom tools.
|
[
"Base",
"class",
"for",
"all",
"custom",
"tools",
"."
] |
[
"/// <summary>",
"/// {0}=VsVersion.Mayor, {1}=VsVersion.Minor, {2}=CategoryGuid, {3}=CustomTool",
"/// </summary>",
"/// <summary>",
"/// {0}=Custom Tool Name",
"/// {1}=Tool version",
"/// {2}=.NET Runtime version",
"/// </summary>",
"/// <summary>",
"/// Provides access to the current project item selected.",
"/// </summary>",
"/// <summary>",
"/// Provides access to the current project item selected.",
"/// </summary>",
"/// <summary>",
"/// Provides access to services.",
"/// </summary>",
"/// <param name=\"serviceType\">Service to retrieve.</param>",
"/// <returns>The service object or null.</returns>",
"// Try the root environment.",
"/// <summary>",
"/// Registers the custom tool.",
"/// </summary>",
"/// <summary>",
"/// Unregisters the custom tool.",
"/// </summary>",
"/// <summary>",
"/// Registers the custom tool.",
"/// </summary>",
"/*\n * [HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\[vsVersion]\\Generators\\[category]\\[toolName]]\n * @=\"[description]\"\n * \"CLSID\"=\"[category]\"\n * \"GeneratesDesignTimeSource\"=[generatesDesignTimeCode]\n */",
"/// <summary>",
"/// Unregisters the custom tool.",
"/// </summary>",
"// Retrieve the GUID associated with the generator class.",
"// Retrieve the custom tool information.",
"// Retrieve the VS.NET versions supported. Can be inherited.",
"// Retrieve the VS.NET generator categories supported. Can be inherited.",
"// retrieve the description"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": [
{
"identifier": "remarks",
"docstring": "Inheriting classes must provide a , static\nmethods with and ,\nwhich should call this class and\nmethods, passing the required parameters.",
"docstring_tokens": [
"Inheriting",
"classes",
"must",
"provide",
"a",
"static",
"methods",
"with",
"and",
"which",
"should",
"call",
"this",
"class",
"and",
"methods",
"passing",
"the",
"required",
"parameters",
"."
]
}
]
}
| false
| 17
| 1,447
| 96
|
8d183be484c15e2fa6a91a0ed2fccd67fe67131d
|
nirmalpavan/MatterTest
|
tree/master/cloud/src/solution/Microsoft.Legal.MatterCenter.Utility/Log.Designer.cs
|
[
"MIT"
] |
C#
|
Log
|
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
|
A strongly-typed resource class, for looking up localized strings, etc.
|
[
"A",
"strongly",
"-",
"typed",
"resource",
"class",
"for",
"looking",
"up",
"localized",
"strings",
"etc",
"."
] |
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Log {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Log() {
}
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.Legal.MatterCenter.Utility.Log", typeof(Log).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
internal static string Azure_RowKey_Date_Format {
get {
return ResourceManager.GetString("Azure_RowKey_Date_Format", resourceCulture);
}
}
internal static string CloudStorageConnectionString {
get {
return ResourceManager.GetString("CloudStorageConnectionString", resourceCulture);
}
}
internal static string EventViewer_EventID {
get {
return ResourceManager.GetString("EventViewer_EventID", resourceCulture);
}
}
internal static string EventViewer_LogName {
get {
return ResourceManager.GetString("EventViewer_LogName", resourceCulture);
}
}
internal static string EventViewer_Source {
get {
return ResourceManager.GetString("EventViewer_Source", resourceCulture);
}
}
internal static string IsDeployedOnAzure {
get {
return ResourceManager.GetString("IsDeployedOnAzure", resourceCulture);
}
}
internal static string IsLoggingOnAzure {
get {
return ResourceManager.GetString("IsLoggingOnAzure", resourceCulture);
}
}
internal static string UtilityLogTableName {
get {
return ResourceManager.GetString("UtilityLogTableName", resourceCulture);
}
}
}
|
[
"[",
"global",
"::",
"System",
".",
"CodeDom",
".",
"Compiler",
".",
"GeneratedCodeAttribute",
"(",
"\"",
"System.Resources.Tools.StronglyTypedResourceBuilder",
"\"",
",",
"\"",
"4.0.0.0",
"\"",
")",
"]",
"[",
"global",
"::",
"System",
".",
"Diagnostics",
".",
"DebuggerNonUserCodeAttribute",
"(",
")",
"]",
"[",
"global",
"::",
"System",
".",
"Runtime",
".",
"CompilerServices",
".",
"CompilerGeneratedAttribute",
"(",
")",
"]",
"internal",
"class",
"Log",
"{",
"private",
"static",
"global",
"::",
"System",
".",
"Resources",
".",
"ResourceManager",
"resourceMan",
";",
"private",
"static",
"global",
"::",
"System",
".",
"Globalization",
".",
"CultureInfo",
"resourceCulture",
";",
"[",
"global",
"::",
"System",
".",
"Diagnostics",
".",
"CodeAnalysis",
".",
"SuppressMessageAttribute",
"(",
"\"",
"Microsoft.Performance",
"\"",
",",
"\"",
"CA1811:AvoidUncalledPrivateCode",
"\"",
")",
"]",
"internal",
"Log",
"(",
")",
"{",
"}",
"[",
"global",
"::",
"System",
".",
"ComponentModel",
".",
"EditorBrowsableAttribute",
"(",
"global",
"::",
"System",
".",
"ComponentModel",
".",
"EditorBrowsableState",
".",
"Advanced",
")",
"]",
"internal",
"static",
"global",
"::",
"System",
".",
"Resources",
".",
"ResourceManager",
"ResourceManager",
"{",
"get",
"{",
"if",
"(",
"object",
".",
"ReferenceEquals",
"(",
"resourceMan",
",",
"null",
")",
")",
"{",
"global",
"::",
"System",
".",
"Resources",
".",
"ResourceManager",
"temp",
"=",
"new",
"global",
"::",
"System",
".",
"Resources",
".",
"ResourceManager",
"(",
"\"",
"Microsoft.Legal.MatterCenter.Utility.Log",
"\"",
",",
"typeof",
"(",
"Log",
")",
".",
"Assembly",
")",
";",
"resourceMan",
"=",
"temp",
";",
"}",
"return",
"resourceMan",
";",
"}",
"}",
"[",
"global",
"::",
"System",
".",
"ComponentModel",
".",
"EditorBrowsableAttribute",
"(",
"global",
"::",
"System",
".",
"ComponentModel",
".",
"EditorBrowsableState",
".",
"Advanced",
")",
"]",
"internal",
"static",
"global",
"::",
"System",
".",
"Globalization",
".",
"CultureInfo",
"Culture",
"{",
"get",
"{",
"return",
"resourceCulture",
";",
"}",
"set",
"{",
"resourceCulture",
"=",
"value",
";",
"}",
"}",
"internal",
"static",
"string",
"Azure_RowKey_Date_Format",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Azure_RowKey_Date_Format",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"CloudStorageConnectionString",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"CloudStorageConnectionString",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"EventViewer_EventID",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"EventViewer_EventID",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"EventViewer_LogName",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"EventViewer_LogName",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"EventViewer_Source",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"EventViewer_Source",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"IsDeployedOnAzure",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"IsDeployedOnAzure",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"IsLoggingOnAzure",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"IsLoggingOnAzure",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"UtilityLogTableName",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"UtilityLogTableName",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"}"
] |
A strongly-typed resource class, for looking up localized strings, etc.
|
[
"A",
"strongly",
"-",
"typed",
"resource",
"class",
"for",
"looking",
"up",
"localized",
"strings",
"etc",
"."
] |
[
"/// <summary>",
"/// Returns the cached ResourceManager instance used by this class.",
"/// </summary>",
"/// <summary>",
"/// Overrides the current thread's CurrentUICulture property for all",
"/// resource lookups using this strongly typed resource class.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to MM-dd-yyyy HH:mm:ss:fffffff.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to DefaultEndpointsProtocol=https;AccountName=[Enter Azure account name, e.g. mattercenterlogaccount];AccountKey=[Enter Account Key for this storage account, e.g. BDLWAl5dePECEtzZTZEBdpPrTrIzUehs4odNasdaw5d8l7pKl2o0uOz4QQqQ+hBQwavQEwRWAasy8xhdxb78vow==].",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to 1001.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to LCADMS.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to LCADMS.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to TRUE.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to TRUE.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to [Enter name of the table on Azure storage where all error/exception log, e.g. MatterCenterLogTable].",
"/// </summary>"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 17
| 494
| 84
|
30400e16fd9b7ccac7cb7978f106634add5133ae
|
udaysagar2177/aws-sdk-java-v2
|
services/sqs/src/it/java/software/amazon/awssdk/services/sqs/SqsConcurrentPerformanceIntegrationTest.java
|
[
"Apache-2.0"
] |
Java
|
SqsConcurrentPerformanceIntegrationTest
|
/**
* This is a manually run test that can be run to test idle connection reaping in the SDK.
* Connections sitting around in the connection pool for too long will eventually be terminated by
* the AWS end of the connection, and will go into CLOSE_WAIT. If this happens, sockets will sit
* around in CLOSE_WAIT, still using resources on the client side to manage that socket. At its
* worse, this can cause the client to be unable to create any new connections until the CLOSE_WAIT
* sockets are eventually expired and released.
*/
|
This is a manually run test that can be run to test idle connection reaping in the SDK.
Connections sitting around in the connection pool for too long will eventually be terminated by
the AWS end of the connection, and will go into CLOSE_WAIT. If this happens, sockets will sit
around in CLOSE_WAIT, still using resources on the client side to manage that socket. At its
worse, this can cause the client to be unable to create any new connections until the CLOSE_WAIT
sockets are eventually expired and released.
|
[
"This",
"is",
"a",
"manually",
"run",
"test",
"that",
"can",
"be",
"run",
"to",
"test",
"idle",
"connection",
"reaping",
"in",
"the",
"SDK",
".",
"Connections",
"sitting",
"around",
"in",
"the",
"connection",
"pool",
"for",
"too",
"long",
"will",
"eventually",
"be",
"terminated",
"by",
"the",
"AWS",
"end",
"of",
"the",
"connection",
"and",
"will",
"go",
"into",
"CLOSE_WAIT",
".",
"If",
"this",
"happens",
"sockets",
"will",
"sit",
"around",
"in",
"CLOSE_WAIT",
"still",
"using",
"resources",
"on",
"the",
"client",
"side",
"to",
"manage",
"that",
"socket",
".",
"At",
"its",
"worse",
"this",
"can",
"cause",
"the",
"client",
"to",
"be",
"unable",
"to",
"create",
"any",
"new",
"connections",
"until",
"the",
"CLOSE_WAIT",
"sockets",
"are",
"eventually",
"expired",
"and",
"released",
"."
] |
public class SqsConcurrentPerformanceIntegrationTest extends IntegrationTestBase {
/** Total number of worker threads to hit SQS. */
private static final int TOTAL_WORKER_THREADS = 30;
private SqsAsyncClient sqs;
/**
* Spins up a pool of threads to make concurrent requests and thus grow the runtime's HTTP
* connection pool, then sits idle.
* <p>
* You can use the netstat command to look at the current sockets connected to SQS and verify
* that they don't sit around in CLOSE_WAIT, and are correctly being reaped.
*/
@Test
@Ignore
public void testIdleConnectionReaping() throws Exception {
sqs = SqsAsyncClient.builder().credentialsProvider(getCredentialsProvider()).build();
sqs = SqsAsyncClient.builder().credentialsProvider(getCredentialsProvider()).build();
List<WorkerThread> workers = new ArrayList<WorkerThread>();
for (int i = 0; i < TOTAL_WORKER_THREADS; i++) {
workers.add(new WorkerThread());
}
for (WorkerThread worker : workers) {
worker.start();
}
// Sleep for five minutes to let the sockets go idle
Thread.sleep(1000 * 60 * 5);
// Wait for the user to acknowledge test before we exit the JVM
System.out.println("Test complete");
waitForUserInput();
}
private class WorkerThread extends Thread {
@Override
public void run() {
sqs.listQueues(ListQueuesRequest.builder().build());
sqs.listQueues(ListQueuesRequest.builder().build());
}
}
private void waitForUserInput() throws IOException {
new BufferedReader(new InputStreamReader(System.in)).readLine();
}
}
|
[
"public",
"class",
"SqsConcurrentPerformanceIntegrationTest",
"extends",
"IntegrationTestBase",
"{",
"/** Total number of worker threads to hit SQS. */",
"private",
"static",
"final",
"int",
"TOTAL_WORKER_THREADS",
"=",
"30",
";",
"private",
"SqsAsyncClient",
"sqs",
";",
"/**\n * Spins up a pool of threads to make concurrent requests and thus grow the runtime's HTTP\n * connection pool, then sits idle.\n * <p>\n * You can use the netstat command to look at the current sockets connected to SQS and verify\n * that they don't sit around in CLOSE_WAIT, and are correctly being reaped.\n */",
"@",
"Test",
"@",
"Ignore",
"public",
"void",
"testIdleConnectionReaping",
"(",
")",
"throws",
"Exception",
"{",
"sqs",
"=",
"SqsAsyncClient",
".",
"builder",
"(",
")",
".",
"credentialsProvider",
"(",
"getCredentialsProvider",
"(",
")",
")",
".",
"build",
"(",
")",
";",
"sqs",
"=",
"SqsAsyncClient",
".",
"builder",
"(",
")",
".",
"credentialsProvider",
"(",
"getCredentialsProvider",
"(",
")",
")",
".",
"build",
"(",
")",
";",
"List",
"<",
"WorkerThread",
">",
"workers",
"=",
"new",
"ArrayList",
"<",
"WorkerThread",
">",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"TOTAL_WORKER_THREADS",
";",
"i",
"++",
")",
"{",
"workers",
".",
"add",
"(",
"new",
"WorkerThread",
"(",
")",
")",
";",
"}",
"for",
"(",
"WorkerThread",
"worker",
":",
"workers",
")",
"{",
"worker",
".",
"start",
"(",
")",
";",
"}",
"Thread",
".",
"sleep",
"(",
"1000",
"*",
"60",
"*",
"5",
")",
";",
"System",
".",
"out",
".",
"println",
"(",
"\"",
"Test complete",
"\"",
")",
";",
"waitForUserInput",
"(",
")",
";",
"}",
"private",
"class",
"WorkerThread",
"extends",
"Thread",
"{",
"@",
"Override",
"public",
"void",
"run",
"(",
")",
"{",
"sqs",
".",
"listQueues",
"(",
"ListQueuesRequest",
".",
"builder",
"(",
")",
".",
"build",
"(",
")",
")",
";",
"sqs",
".",
"listQueues",
"(",
"ListQueuesRequest",
".",
"builder",
"(",
")",
".",
"build",
"(",
")",
")",
";",
"}",
"}",
"private",
"void",
"waitForUserInput",
"(",
")",
"throws",
"IOException",
"{",
"new",
"BufferedReader",
"(",
"new",
"InputStreamReader",
"(",
"System",
".",
"in",
")",
")",
".",
"readLine",
"(",
")",
";",
"}",
"}"
] |
This is a manually run test that can be run to test idle connection reaping in the SDK.
|
[
"This",
"is",
"a",
"manually",
"run",
"test",
"that",
"can",
"be",
"run",
"to",
"test",
"idle",
"connection",
"reaping",
"in",
"the",
"SDK",
"."
] |
[
"// Sleep for five minutes to let the sockets go idle",
"// Wait for the user to acknowledge test before we exit the JVM"
] |
[
{
"param": "IntegrationTestBase",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "IntegrationTestBase",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 13
| 377
| 113
|
111b4626b453edf70bc58a4480935975b5142e30
|
thomas07vt/transit-ruby
|
lib/transit/writer.rb
|
[
"Apache-2.0"
] |
Ruby
|
Transit
|
# Copyright 2014 Cognitect. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
|
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
|
[
"Unless",
"required",
"by",
"applicable",
"law",
"or",
"agreed",
"to",
"in",
"writing",
"software",
"distributed",
"under",
"the",
"License",
"is",
"distributed",
"on",
"an",
"\"",
"AS",
"-",
"IS",
"\"",
"BASIS",
"WITHOUT",
"WARRANTIES",
"OR",
"CONDITIONS",
"OF",
"ANY",
"KIND",
"either",
"express",
"or",
"implied",
".",
"See",
"the",
"License",
"for",
"the",
"specific",
"language",
"governing",
"permissions",
"and",
"limitations",
"under",
"the",
"License",
"."
] |
module Transit
# Transit::Writer marshals Ruby objects as transit values to an output stream.
# @see https://github.com/cognitect/transit-format
class Writer
# @param [Symbol] format required :json, :json_verbose, or :msgpack
# @param [IO] io required
# @param [Hash] opts optional
#
# Creates a new Writer configured to write to <tt>io</tt> in
# <tt>format</tt> (<tt>:json</tt>, <tt>:json_verbose</tt>,
# <tt>:msgpack</tt>).
#
# Use opts to register custom write handlers, associating each one
# with its type.
#
# @example
# json_writer = Transit::Writer.new(:json, io)
# json_verbose_writer = Transit::Writer.new(:json_verbose, io)
# msgpack_writer = Transit::Writer.new(:msgpack, io)
# writer_with_custom_handlers = Transit::Writer.new(:json, io,
# :handlers => {Point => PointWriteHandler})
#
# @see Transit::WriteHandlers
def initialize(format, io, opts={})
@marshaler = case format
when :json
Marshaler::Json.new(io, {:handlers => {},
:oj_opts => {:indent => -1}}.merge(opts))
when :json_verbose
Marshaler::VerboseJson.new(io, {:handlers => {}}.merge(opts))
else
Marshaler::MessagePack.new(io, {:handlers => {}}.merge(opts))
end
end
# Converts a Ruby object to a transit value and writes it to this
# Writer's output stream.
#
# @param obj the value to write
# @example
# writer = Transit::Writer.new(:json, io)
# writer.write(Date.new(2014,7,22))
if Transit::jruby?
def write(obj)
@marshaler.write(obj)
end
else
def write(obj)
@marshaler.marshal_top(obj)
end
end
end
end
|
[
"module",
"Transit",
"class",
"Writer",
"def",
"initialize",
"(",
"format",
",",
"io",
",",
"opts",
"=",
"{",
"}",
")",
"@marshaler",
"=",
"case",
"format",
"when",
":json",
"Marshaler",
"::",
"Json",
".",
"new",
"(",
"io",
",",
"{",
":handlers",
"=>",
"{",
"}",
",",
":oj_opts",
"=>",
"{",
":indent",
"=>",
"-",
"1",
"}",
"}",
".",
"merge",
"(",
"opts",
")",
")",
"when",
":json_verbose",
"Marshaler",
"::",
"VerboseJson",
".",
"new",
"(",
"io",
",",
"{",
":handlers",
"=>",
"{",
"}",
"}",
".",
"merge",
"(",
"opts",
")",
")",
"else",
"Marshaler",
"::",
"MessagePack",
".",
"new",
"(",
"io",
",",
"{",
":handlers",
"=>",
"{",
"}",
"}",
".",
"merge",
"(",
"opts",
")",
")",
"end",
"end",
"if",
"Transit",
"::",
"jruby?",
"def",
"write",
"(",
"obj",
")",
"@marshaler",
".",
"write",
"(",
"obj",
")",
"end",
"else",
"def",
"write",
"(",
"obj",
")",
"@marshaler",
".",
"marshal_top",
"(",
"obj",
")",
"end",
"end",
"end",
"end"
] |
Copyright 2014 Cognitect.
|
[
"Copyright",
"2014",
"Cognitect",
"."
] |
[
"# Transit::Writer marshals Ruby objects as transit values to an output stream.",
"# @see https://github.com/cognitect/transit-format",
"# @param [Symbol] format required :json, :json_verbose, or :msgpack",
"# @param [IO] io required",
"# @param [Hash] opts optional",
"#",
"# Creates a new Writer configured to write to <tt>io</tt> in",
"# <tt>format</tt> (<tt>:json</tt>, <tt>:json_verbose</tt>,",
"# <tt>:msgpack</tt>).",
"#",
"# Use opts to register custom write handlers, associating each one",
"# with its type.",
"#",
"# @example",
"# json_writer = Transit::Writer.new(:json, io)",
"# json_verbose_writer = Transit::Writer.new(:json_verbose, io)",
"# msgpack_writer = Transit::Writer.new(:msgpack, io)",
"# writer_with_custom_handlers = Transit::Writer.new(:json, io,",
"# :handlers => {Point => PointWriteHandler})",
"#",
"# @see Transit::WriteHandlers",
"# Converts a Ruby object to a transit value and writes it to this",
"# Writer's output stream.",
"#",
"# @param obj the value to write",
"# @example",
"# writer = Transit::Writer.new(:json, io)",
"# writer.write(Date.new(2014,7,22))"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 19
| 483
| 135
|
fa27947242333f1e1784b47c4904f415f465387b
|
kenjdavidson/yahoo-fantasy-ruby
|
lib/yahoo_fantasy/resource/filterable.rb
|
[
"MIT"
] |
Ruby
|
Filterable
|
# Provides common functionality for filterable reasources.
#
# At this point it doesn't really do much but provide inline code/comments for what
# filters are available for the respective subresource.
#
# The end goal is provide "type checking" (solely because I haven't wrapped my head around
# non type checking yet) and Resource request validation. Although, at this point the
# Yahoo Fantasy API just ignores unknown filters.
#
# @todo add a Filter class instead of options Hash
#
|
Provides common functionality for filterable reasources.
At this point it doesn't really do much but provide inline code/comments for what
filters are available for the respective subresource.
The end goal is provide "type checking" (solely because I haven't wrapped my head around
non type checking yet) and Resource request validation. Although, at this point the
Yahoo Fantasy API just ignores unknown filters.
|
[
"Provides",
"common",
"functionality",
"for",
"filterable",
"reasources",
".",
"At",
"this",
"point",
"it",
"doesn",
"'",
"t",
"really",
"do",
"much",
"but",
"provide",
"inline",
"code",
"/",
"comments",
"for",
"what",
"filters",
"are",
"available",
"for",
"the",
"respective",
"subresource",
".",
"The",
"end",
"goal",
"is",
"provide",
"\"",
"type",
"checking",
"\"",
"(",
"solely",
"because",
"I",
"haven",
"'",
"t",
"wrapped",
"my",
"head",
"around",
"non",
"type",
"checking",
"yet",
")",
"and",
"Resource",
"request",
"validation",
".",
"Although",
"at",
"this",
"point",
"the",
"Yahoo",
"Fantasy",
"API",
"just",
"ignores",
"unknown",
"filters",
"."
] |
module Filterable
class InvalidFilterError < StandardError; end
def self.included(base)
base.extend ClassMethods
end
# Filter ClassMethods
#
module ClassMethods
# Returns a duplicate (immutable) copy of the filters.
# @return [Hash]
#
def filters
@filters ||= {}
@filters.dup.freeze
end
# Builds the filter parameters, which is pretty much the same as the key string. Basically
# a semi-colon separated list key/value pairs of comma separated values.
#
# @todo flip flopping at parsing out unknown filters (but since Yahoo doesn't fail) it's safter
# at this poin to just leave them in there.
#
# @param filters [Hash{String => Array<String>}] requested filters
# @return [String]
#
def filter_params(filters = {})
return '' if filters.nil? || filters.empty?
filter_query = filters.map { |k, v| build_parameter_string(k, v) }
.join
filter_query = filter_query.to_s unless filter_query.empty?
filter_query
end
# Builds the single parameter string, which includes the key and a comma
# separated list of values.
#
# @param key [String]
# @param values [Array<String>,String]
#
def build_parameter_string(key, values = [])
parameter = +";#{key}="
parameter << if values.is_a?(Array)
values.join(',').to_s
else
values.to_s
end
parameter
end
# Define a custom Filter with custom options.
#
# At this point the options aren't used, but this sets us up for being able to implement
# different options:
#
# @param name [Symbol]
# @param options [Hash]
# @option options [Class] type
# @option options [Values] values
#
def filter(name, options = {})
opts = options.dup
opts[:name] = name
@filters ||= {}
@filters[name] = opts
end
end
end
|
[
"module",
"Filterable",
"class",
"InvalidFilterError",
"<",
"StandardError",
";",
"end",
"def",
"self",
".",
"included",
"(",
"base",
")",
"base",
".",
"extend",
"ClassMethods",
"end",
"module",
"ClassMethods",
"def",
"filters",
"@filters",
"||=",
"{",
"}",
"@filters",
".",
"dup",
".",
"freeze",
"end",
"def",
"filter_params",
"(",
"filters",
"=",
"{",
"}",
")",
"return",
"''",
"if",
"filters",
".",
"nil?",
"||",
"filters",
".",
"empty?",
"filter_query",
"=",
"filters",
".",
"map",
"{",
"|",
"k",
",",
"v",
"|",
"build_parameter_string",
"(",
"k",
",",
"v",
")",
"}",
".",
"join",
"filter_query",
"=",
"filter_query",
".",
"to_s",
"unless",
"filter_query",
".",
"empty?",
"filter_query",
"end",
"def",
"build_parameter_string",
"(",
"key",
",",
"values",
"=",
"[",
"]",
")",
"parameter",
"=",
"+",
"\";#{key}=\"",
"parameter",
"<<",
"if",
"values",
".",
"is_a?",
"(",
"Array",
")",
"values",
".",
"join",
"(",
"','",
")",
".",
"to_s",
"else",
"values",
".",
"to_s",
"end",
"parameter",
"end",
"def",
"filter",
"(",
"name",
",",
"options",
"=",
"{",
"}",
")",
"opts",
"=",
"options",
".",
"dup",
"opts",
"[",
":name",
"]",
"=",
"name",
"@filters",
"||=",
"{",
"}",
"@filters",
"[",
"name",
"]",
"=",
"opts",
"end",
"end",
"end"
] |
Provides common functionality for filterable reasources.
|
[
"Provides",
"common",
"functionality",
"for",
"filterable",
"reasources",
"."
] |
[
"# Filter ClassMethods\r",
"#\r",
"# Returns a duplicate (immutable) copy of the filters.\r",
"# @return [Hash]\r",
"#\r",
"# Builds the filter parameters, which is pretty much the same as the key string. Basically\r",
"# a semi-colon separated list key/value pairs of comma separated values.\r",
"#\r",
"# @todo flip flopping at parsing out unknown filters (but since Yahoo doesn't fail) it's safter\r",
"# at this poin to just leave them in there.\r",
"#\r",
"# @param filters [Hash{String => Array<String>}] requested filters\r",
"# @return [String]\r",
"#\r",
"# Builds the single parameter string, which includes the key and a comma\r",
"# separated list of values.\r",
"#\r",
"# @param key [String]\r",
"# @param values [Array<String>,String]\r",
"#\r",
"# Define a custom Filter with custom options.\r",
"#\r",
"# At this point the options aren't used, but this sets us up for being able to implement\r",
"# different options:\r",
"#\r",
"# @param name [Symbol]\r",
"# @param options [Hash]\r",
"# @option options [Class] type\r",
"# @option options [Values] values\r",
"#\r"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": [
{
"identifier": "todo",
"docstring": "add a Filter class instead of options Hash",
"docstring_tokens": [
"add",
"a",
"Filter",
"class",
"instead",
"of",
"options",
"Hash"
]
}
]
}
| false
| 14
| 479
| 106
|
1e56cd255272cb28f59dba0b3e8e7f9721b3a2d4
|
sorah/aws-sdk-ruby
|
lib/aws/auto_scaling/instance.rb
|
[
"Apache-2.0"
] |
Ruby
|
Instance
|
# A small wrapper around an {EC2::Instance}.
#
# ## Getting Auto Scaling Instances
#
# If you know the EC2 instance id, you can use {InstanceCollection#[]}
# to get the Auto Scaling instance.
#
# instance = auto_scaling.instances['i-1234578']
# instance.health_statue #=> :healthy
# instance.ec2_instance #=> <AWS::EC2::Instance instance_id:i-1234578>
#
# ## Enumerating Auto Scaling Instances
#
# You can enumerate *ALL* instances like so:
#
# auto_scaling = AWS::AutoScaling.new
# auto_scaling.instances.each do |auto_scaling_instance|
# # ...
# end
#
# If you want the instances for a single auto scaling group:
#
# group = auto_scaling.groups['group-name']
# group.auto_scaling_instances.each do |instance|
# # ...
# end
#
# If you prefer {EC2::Instance} objects you should use
# {Group#ec2_instances} instead.
#
# @attr_reader [String] auto_scaling_group_name
#
# @attr_reader [String] launch_configuration_name
#
# @attr_reader [String] health_status Returns the instance health status
# (e.g. 'Healthly' or 'Unhealthly').
#
# @attr_reader [String] availability_zone_name
#
# @attr_reader [String] lifecycle_state
#
|
A small wrapper around an {EC2::Instance}.
Getting Auto Scaling Instances
If you know the EC2 instance id, you can use {InstanceCollection#[]}
to get the Auto Scaling instance.
Enumerating Auto Scaling Instances
You can enumerate *ALL* instances like so.
If you want the instances for a single auto scaling group.
If you prefer {EC2::Instance} objects you should use
{Group#ec2_instances} instead.
|
[
"A",
"small",
"wrapper",
"around",
"an",
"{",
"EC2",
"::",
"Instance",
"}",
".",
"Getting",
"Auto",
"Scaling",
"Instances",
"If",
"you",
"know",
"the",
"EC2",
"instance",
"id",
"you",
"can",
"use",
"{",
"InstanceCollection#",
"[]",
"}",
"to",
"get",
"the",
"Auto",
"Scaling",
"instance",
".",
"Enumerating",
"Auto",
"Scaling",
"Instances",
"You",
"can",
"enumerate",
"*",
"ALL",
"*",
"instances",
"like",
"so",
".",
"If",
"you",
"want",
"the",
"instances",
"for",
"a",
"single",
"auto",
"scaling",
"group",
".",
"If",
"you",
"prefer",
"{",
"EC2",
"::",
"Instance",
"}",
"objects",
"you",
"should",
"use",
"{",
"Group#ec2_instances",
"}",
"instead",
"."
] |
class Instance < Core::Resource
# @api private
def initialize instance_id, options = {}
@instance_id = instance_id
super
end
# @return [String] instance_id Returns the EC2 id instance.
attr_reader :instance_id
alias_method :id, :instance_id
attribute :auto_scaling_group_name, :static => true
attribute :availability_zone_name,
:from => :availability_zone,
:static => true
attribute :health_status
attribute :launch_configuration_name, :static => true
attribute :lifecycle_state
populates_from(:describe_auto_scaling_instances) do |resp|
resp.auto_scaling_instances.find do |i|
i.instance_id == instance_id
end
end
# describe auto scaling groups returns ALL attributes
# except :auto_scaling_group_name
provider(:describe_auto_scaling_groups) do |provider|
provider.find do |resp|
instance = nil
resp.auto_scaling_groups.each do |group|
group.instances.each do |i|
instance = i if i.instance_id == instance_id
end
end
instance
end
provider.provides(*(attributes.keys - [:auto_scaling_group_name]))
end
# @return [EC2::Instance]
def ec2_instance
EC2::Instance.new(instance_id, :config => config)
end
# @return [AutoScaling::Group]
def auto_scaling_group
Group.new(auto_scaling_group_name, :config => config)
end
alias_method :group, :auto_scaling_group
# @return [EC2::AvailabilityZone]
def availability_zone
EC2::AvailabilityZone.new(availability_zone_name, :config => config)
end
# @return [LaunchConfiguration]
def launch_configuration
LaunchConfiguration.new(launch_configuration_name, :config => config)
end
# @param [String] status Sets the health status of an instance.
# Valid values inculde 'Healthy' and 'Unhealthy'
#
# @param [Hash] options
#
# @option options [Boolean] :respect_grace_period (false) If true,
# this call should respect the grace period associated with
# this instance's Auto Scaling group.
#
# @return [nil]
#
def set_health status, options = {}
client_opts = {}
client_opts[:instance_id] = instance_id
client_opts[:health_status] = status
client_opts[:should_respect_grace_period] =
options[:respect_grace_period] == true
client.set_instance_health(client_opts)
end
# @return [Boolean] Returns true if there exists an Auto Scaling
# instance with this instance id.
def exists?
!get_resource.auto_scaling_instances.empty?
end
# Terminates the current Auto Scaling instance.
#
# @param [Boolean] decrement_desired_capacity Specifies whether or not
# terminating this instance should also decrement the size of
# the AutoScalingGroup.
#
# @return [Activity] Returns an activity that represents the
# termination of the instance.
#
def terminate decrement_desired_capacity
client_opts = {}
client_opts[:instance_id] = instance_id
client_opts[:should_decrement_desired_capacity] =
decrement_desired_capacity
resp = client.terminate_instance_in_auto_scaling_group(client_opts)
Activity.new_from(
:terminate_instance_in_auto_scaling_group,
resp.activity,
resp.activity.activity_id,
:config => config)
end
alias_method :delete, :terminate
protected
def resource_identifiers
[[:instance_id, instance_id]]
end
def get_resource attr_name = nil
client_opts = {}
client_opts[:instance_ids] = [instance_id]
client.describe_auto_scaling_instances(client_opts)
end
end
|
[
"class",
"Instance",
"<",
"Core",
"::",
"Resource",
"def",
"initialize",
"instance_id",
",",
"options",
"=",
"{",
"}",
"@instance_id",
"=",
"instance_id",
"super",
"end",
"attr_reader",
":instance_id",
"alias_method",
":id",
",",
":instance_id",
"attribute",
":auto_scaling_group_name",
",",
":static",
"=>",
"true",
"attribute",
":availability_zone_name",
",",
":from",
"=>",
":availability_zone",
",",
":static",
"=>",
"true",
"attribute",
":health_status",
"attribute",
":launch_configuration_name",
",",
":static",
"=>",
"true",
"attribute",
":lifecycle_state",
"populates_from",
"(",
":describe_auto_scaling_instances",
")",
"do",
"|",
"resp",
"|",
"resp",
".",
"auto_scaling_instances",
".",
"find",
"do",
"|",
"i",
"|",
"i",
".",
"instance_id",
"==",
"instance_id",
"end",
"end",
"provider",
"(",
":describe_auto_scaling_groups",
")",
"do",
"|",
"provider",
"|",
"provider",
".",
"find",
"do",
"|",
"resp",
"|",
"instance",
"=",
"nil",
"resp",
".",
"auto_scaling_groups",
".",
"each",
"do",
"|",
"group",
"|",
"group",
".",
"instances",
".",
"each",
"do",
"|",
"i",
"|",
"instance",
"=",
"i",
"if",
"i",
".",
"instance_id",
"==",
"instance_id",
"end",
"end",
"instance",
"end",
"provider",
".",
"provides",
"(",
"*",
"(",
"attributes",
".",
"keys",
"-",
"[",
":auto_scaling_group_name",
"]",
")",
")",
"end",
"def",
"ec2_instance",
"EC2",
"::",
"Instance",
".",
"new",
"(",
"instance_id",
",",
":config",
"=>",
"config",
")",
"end",
"def",
"auto_scaling_group",
"Group",
".",
"new",
"(",
"auto_scaling_group_name",
",",
":config",
"=>",
"config",
")",
"end",
"alias_method",
":group",
",",
":auto_scaling_group",
"def",
"availability_zone",
"EC2",
"::",
"AvailabilityZone",
".",
"new",
"(",
"availability_zone_name",
",",
":config",
"=>",
"config",
")",
"end",
"def",
"launch_configuration",
"LaunchConfiguration",
".",
"new",
"(",
"launch_configuration_name",
",",
":config",
"=>",
"config",
")",
"end",
"def",
"set_health",
"status",
",",
"options",
"=",
"{",
"}",
"client_opts",
"=",
"{",
"}",
"client_opts",
"[",
":instance_id",
"]",
"=",
"instance_id",
"client_opts",
"[",
":health_status",
"]",
"=",
"status",
"client_opts",
"[",
":should_respect_grace_period",
"]",
"=",
"options",
"[",
":respect_grace_period",
"]",
"==",
"true",
"client",
".",
"set_instance_health",
"(",
"client_opts",
")",
"end",
"def",
"exists?",
"!",
"get_resource",
".",
"auto_scaling_instances",
".",
"empty?",
"end",
"def",
"terminate",
"decrement_desired_capacity",
"client_opts",
"=",
"{",
"}",
"client_opts",
"[",
":instance_id",
"]",
"=",
"instance_id",
"client_opts",
"[",
":should_decrement_desired_capacity",
"]",
"=",
"decrement_desired_capacity",
"resp",
"=",
"client",
".",
"terminate_instance_in_auto_scaling_group",
"(",
"client_opts",
")",
"Activity",
".",
"new_from",
"(",
":terminate_instance_in_auto_scaling_group",
",",
"resp",
".",
"activity",
",",
"resp",
".",
"activity",
".",
"activity_id",
",",
":config",
"=>",
"config",
")",
"end",
"alias_method",
":delete",
",",
":terminate",
"protected",
"def",
"resource_identifiers",
"[",
"[",
":instance_id",
",",
"instance_id",
"]",
"]",
"end",
"def",
"get_resource",
"attr_name",
"=",
"nil",
"client_opts",
"=",
"{",
"}",
"client_opts",
"[",
":instance_ids",
"]",
"=",
"[",
"instance_id",
"]",
"client",
".",
"describe_auto_scaling_instances",
"(",
"client_opts",
")",
"end",
"end"
] |
A small wrapper around an {EC2::Instance}.
|
[
"A",
"small",
"wrapper",
"around",
"an",
"{",
"EC2",
"::",
"Instance",
"}",
"."
] |
[
"# @api private",
"# @return [String] instance_id Returns the EC2 id instance.",
"# describe auto scaling groups returns ALL attributes",
"# except :auto_scaling_group_name",
"# @return [EC2::Instance]",
"# @return [AutoScaling::Group]",
"# @return [EC2::AvailabilityZone]",
"# @return [LaunchConfiguration]",
"# @param [String] status Sets the health status of an instance.",
"# Valid values inculde 'Healthy' and 'Unhealthy'",
"#",
"# @param [Hash] options",
"#",
"# @option options [Boolean] :respect_grace_period (false) If true,",
"# this call should respect the grace period associated with",
"# this instance's Auto Scaling group.",
"#",
"# @return [nil]",
"#",
"# @return [Boolean] Returns true if there exists an Auto Scaling",
"# instance with this instance id.",
"# Terminates the current Auto Scaling instance.",
"#",
"# @param [Boolean] decrement_desired_capacity Specifies whether or not",
"# terminating this instance should also decrement the size of",
"# the AutoScalingGroup.",
"#",
"# @return [Activity] Returns an activity that represents the",
"# termination of the instance.",
"#"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": [
{
"identifier": "attr_reader",
"docstring": null,
"docstring_tokens": [
"None"
]
},
{
"identifier": "attr_reader",
"docstring": null,
"docstring_tokens": [
"None"
]
},
{
"identifier": "attr_reader",
"docstring": "[String] health_status Returns the instance health status .",
"docstring_tokens": [
"[",
"String",
"]",
"health_status",
"Returns",
"the",
"instance",
"health",
"status",
"."
]
},
{
"identifier": "attr_reader",
"docstring": null,
"docstring_tokens": [
"None"
]
},
{
"identifier": "attr_reader",
"docstring": null,
"docstring_tokens": [
"None"
]
}
]
}
| false
| 18
| 851
| 309
|
3169b2b289cb9d95aba25d21e9e56ea5b909bbbe
|
fakeNetflix/facebook-repo-fbthrift
|
thrift/lib/rb/lib/thrift/transport/memory_buffer_transport.rb
|
[
"Apache-2.0"
] |
Ruby
|
Thrift
|
# encoding: ascii-8bit
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
|
ascii-8bit
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
|
[
"ascii",
"-",
"8bit",
"Licensed",
"to",
"the",
"Apache",
"Software",
"Foundation",
"(",
"ASF",
")",
"under",
"one",
"or",
"more",
"contributor",
"license",
"agreements",
".",
"See",
"the",
"NOTICE",
"file",
"distributed",
"with",
"this",
"work",
"for",
"additional",
"information",
"regarding",
"copyright",
"ownership",
".",
"The",
"ASF",
"licenses",
"this",
"file",
"to",
"you",
"under",
"the",
"Apache",
"License",
"Version",
"2",
".",
"0",
"(",
"the",
"\"",
"License",
"\"",
")",
";",
"you",
"may",
"not",
"use",
"this",
"file",
"except",
"in",
"compliance",
"with",
"the",
"License",
".",
"You",
"may",
"obtain",
"a",
"copy",
"of",
"the",
"License",
"at",
"Unless",
"required",
"by",
"applicable",
"law",
"or",
"agreed",
"to",
"in",
"writing",
"software",
"distributed",
"under",
"the",
"License",
"is",
"distributed",
"on",
"an",
"\"",
"AS",
"IS",
"\"",
"BASIS",
"WITHOUT",
"WARRANTIES",
"OR",
"CONDITIONS",
"OF",
"ANY",
"KIND",
"either",
"express",
"or",
"implied",
".",
"See",
"the",
"License",
"for",
"the",
"specific",
"language",
"governing",
"permissions",
"and",
"limitations",
"under",
"the",
"License",
"."
] |
module Thrift
class MemoryBufferTransport < BaseTransport
GARBAGE_BUFFER_SIZE = 4*(2**10) # 4kB
# If you pass a string to this, you should #dup that string
# unless you want it to be modified by #read and #write
#--
# this behavior is no longer required. If you wish to change it
# go ahead, just make sure the specs pass
def initialize(buffer = nil)
@buf = buffer || ''
@index = 0
end
def open?
return true
end
def open
end
def close
end
def peek
@index < @buf.size
end
# this method does not use the passed object directly but copies it
def reset_buffer(new_buf = '')
@buf.replace new_buf
@index = 0
end
def available
@buf.length - @index
end
def read(len)
data = @buf.slice(@index, len)
@index += len
@index = @buf.size if @index > @buf.size
if @index >= GARBAGE_BUFFER_SIZE
@buf = @buf.slice(@index..-1)
@index = 0
end
if data.size < len
raise EOFError, "Not enough bytes remain in buffer"
end
data
end
def write(wbuf)
@buf << wbuf
end
def flush
end
def inspect_buffer
out = []
for idx in 0...(@buf.size)
# if idx != 0
# out << " "
# end
if idx == @index
out << ">"
end
out << @buf[idx].ord.to_s(16)
end
out.join(" ")
end
end
end
|
[
"module",
"Thrift",
"class",
"MemoryBufferTransport",
"<",
"BaseTransport",
"GARBAGE_BUFFER_SIZE",
"=",
"4",
"*",
"(",
"2",
"**",
"10",
")",
"def",
"initialize",
"(",
"buffer",
"=",
"nil",
")",
"@buf",
"=",
"buffer",
"||",
"''",
"@index",
"=",
"0",
"end",
"def",
"open?",
"return",
"true",
"end",
"def",
"open",
"end",
"def",
"close",
"end",
"def",
"peek",
"@index",
"<",
"@buf",
".",
"size",
"end",
"def",
"reset_buffer",
"(",
"new_buf",
"=",
"''",
")",
"@buf",
".",
"replace",
"new_buf",
"@index",
"=",
"0",
"end",
"def",
"available",
"@buf",
".",
"length",
"-",
"@index",
"end",
"def",
"read",
"(",
"len",
")",
"data",
"=",
"@buf",
".",
"slice",
"(",
"@index",
",",
"len",
")",
"@index",
"+=",
"len",
"@index",
"=",
"@buf",
".",
"size",
"if",
"@index",
">",
"@buf",
".",
"size",
"if",
"@index",
">=",
"GARBAGE_BUFFER_SIZE",
"@buf",
"=",
"@buf",
".",
"slice",
"(",
"@index",
"..",
"-",
"1",
")",
"@index",
"=",
"0",
"end",
"if",
"data",
".",
"size",
"<",
"len",
"raise",
"EOFError",
",",
"\"Not enough bytes remain in buffer\"",
"end",
"data",
"end",
"def",
"write",
"(",
"wbuf",
")",
"@buf",
"<<",
"wbuf",
"end",
"def",
"flush",
"end",
"def",
"inspect_buffer",
"out",
"=",
"[",
"]",
"for",
"idx",
"in",
"0",
"...",
"(",
"@buf",
".",
"size",
")",
"if",
"idx",
"==",
"@index",
"out",
"<<",
"\">\"",
"end",
"out",
"<<",
"@buf",
"[",
"idx",
"]",
".",
"ord",
".",
"to_s",
"(",
"16",
")",
"end",
"out",
".",
"join",
"(",
"\" \"",
")",
"end",
"end",
"end"
] |
encoding: ascii-8bit
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.
|
[
"encoding",
":",
"ascii",
"-",
"8bit",
"Licensed",
"to",
"the",
"Apache",
"Software",
"Foundation",
"(",
"ASF",
")",
"under",
"one",
"or",
"more",
"contributor",
"license",
"agreements",
"."
] |
[
"# 4kB",
"# If you pass a string to this, you should #dup that string",
"# unless you want it to be modified by #read and #write",
"#--",
"# this behavior is no longer required. If you wish to change it",
"# go ahead, just make sure the specs pass",
"# this method does not use the passed object directly but copies it",
"# if idx != 0",
"# out << \" \"",
"# end"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 14
| 422
| 183
|
1f9b66b7e0940701e8d45f9db6f40a431b17a3dc
|
Juggernaut93/EDDI
|
EDSMResponder/Properties/EDSMResources.Designer.cs
|
[
"Apache-2.0"
] |
C#
|
EDSMResources
|
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
|
A strongly-typed resource class, for looking up localized strings, etc.
|
[
"A",
"strongly",
"-",
"typed",
"resource",
"class",
"for",
"looking",
"up",
"localized",
"strings",
"etc",
"."
] |
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
public class EDSMResources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal EDSMResources() {
}
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("EddiEdsmResponder.Properties.EDSMResources", typeof(EDSMResources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
public static string api_key_label {
get {
return ResourceManager.GetString("api_key_label", resourceCulture);
}
}
public static string cmd_name_label {
get {
return ResourceManager.GetString("cmd_name_label", resourceCulture);
}
}
public static string desc {
get {
return ResourceManager.GetString("desc", resourceCulture);
}
}
public static string log_button {
get {
return ResourceManager.GetString("log_button", resourceCulture);
}
}
public static string log_button_companion_unconfigured {
get {
return ResourceManager.GetString("log_button_companion_unconfigured", resourceCulture);
}
}
public static string log_button_empty_api_key {
get {
return ResourceManager.GetString("log_button_empty_api_key", resourceCulture);
}
}
public static string log_button_error_received {
get {
return ResourceManager.GetString("log_button_error_received", resourceCulture);
}
}
public static string log_button_fetched {
get {
return ResourceManager.GetString("log_button_fetched", resourceCulture);
}
}
public static string log_button_fetching {
get {
return ResourceManager.GetString("log_button_fetching", resourceCulture);
}
}
public static string log_button_fetching_progress {
get {
return ResourceManager.GetString("log_button_fetching_progress", resourceCulture);
}
}
public static string name {
get {
return ResourceManager.GetString("name", resourceCulture);
}
}
public static string p1 {
get {
return ResourceManager.GetString("p1", resourceCulture);
}
}
public static string p2 {
get {
return ResourceManager.GetString("p2", resourceCulture);
}
}
public static string p3 {
get {
return ResourceManager.GetString("p3", resourceCulture);
}
}
}
|
[
"[",
"global",
"::",
"System",
".",
"CodeDom",
".",
"Compiler",
".",
"GeneratedCodeAttribute",
"(",
"\"",
"System.Resources.Tools.StronglyTypedResourceBuilder",
"\"",
",",
"\"",
"15.0.0.0",
"\"",
")",
"]",
"[",
"global",
"::",
"System",
".",
"Diagnostics",
".",
"DebuggerNonUserCodeAttribute",
"(",
")",
"]",
"[",
"global",
"::",
"System",
".",
"Runtime",
".",
"CompilerServices",
".",
"CompilerGeneratedAttribute",
"(",
")",
"]",
"public",
"class",
"EDSMResources",
"{",
"private",
"static",
"global",
"::",
"System",
".",
"Resources",
".",
"ResourceManager",
"resourceMan",
";",
"private",
"static",
"global",
"::",
"System",
".",
"Globalization",
".",
"CultureInfo",
"resourceCulture",
";",
"[",
"global",
"::",
"System",
".",
"Diagnostics",
".",
"CodeAnalysis",
".",
"SuppressMessageAttribute",
"(",
"\"",
"Microsoft.Performance",
"\"",
",",
"\"",
"CA1811:AvoidUncalledPrivateCode",
"\"",
")",
"]",
"internal",
"EDSMResources",
"(",
")",
"{",
"}",
"[",
"global",
"::",
"System",
".",
"ComponentModel",
".",
"EditorBrowsableAttribute",
"(",
"global",
"::",
"System",
".",
"ComponentModel",
".",
"EditorBrowsableState",
".",
"Advanced",
")",
"]",
"public",
"static",
"global",
"::",
"System",
".",
"Resources",
".",
"ResourceManager",
"ResourceManager",
"{",
"get",
"{",
"if",
"(",
"object",
".",
"ReferenceEquals",
"(",
"resourceMan",
",",
"null",
")",
")",
"{",
"global",
"::",
"System",
".",
"Resources",
".",
"ResourceManager",
"temp",
"=",
"new",
"global",
"::",
"System",
".",
"Resources",
".",
"ResourceManager",
"(",
"\"",
"EddiEdsmResponder.Properties.EDSMResources",
"\"",
",",
"typeof",
"(",
"EDSMResources",
")",
".",
"Assembly",
")",
";",
"resourceMan",
"=",
"temp",
";",
"}",
"return",
"resourceMan",
";",
"}",
"}",
"[",
"global",
"::",
"System",
".",
"ComponentModel",
".",
"EditorBrowsableAttribute",
"(",
"global",
"::",
"System",
".",
"ComponentModel",
".",
"EditorBrowsableState",
".",
"Advanced",
")",
"]",
"public",
"static",
"global",
"::",
"System",
".",
"Globalization",
".",
"CultureInfo",
"Culture",
"{",
"get",
"{",
"return",
"resourceCulture",
";",
"}",
"set",
"{",
"resourceCulture",
"=",
"value",
";",
"}",
"}",
"public",
"static",
"string",
"api_key_label",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"api_key_label",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"cmd_name_label",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"cmd_name_label",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"desc",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"desc",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"log_button",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"log_button",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"log_button_companion_unconfigured",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"log_button_companion_unconfigured",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"log_button_empty_api_key",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"log_button_empty_api_key",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"log_button_error_received",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"log_button_error_received",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"log_button_fetched",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"log_button_fetched",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"log_button_fetching",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"log_button_fetching",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"log_button_fetching_progress",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"log_button_fetching_progress",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"name",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"name",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"p1",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"p1",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"p2",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"p2",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"p3",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"p3",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"}"
] |
A strongly-typed resource class, for looking up localized strings, etc.
|
[
"A",
"strongly",
"-",
"typed",
"resource",
"class",
"for",
"looking",
"up",
"localized",
"strings",
"etc",
"."
] |
[
"/// <summary>",
"/// Returns the cached ResourceManager instance used by this class.",
"/// </summary>",
"/// <summary>",
"/// Overrides the current thread's CurrentUICulture property for all",
"/// resource lookups using this strongly typed resource class.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to EDSM API key:.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to EDSM Commander name:.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Send details of your travels to EDSM. EDSM is a third-party tool that provides information on the locations of star systems and keeps a log of the star systems you have visited. It uses the data provided to crowd-source a map of the galaxy.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Obtain EDSM log.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to EDSM API not configured; cannot obtain logs..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Please enter EDSM API key to obtain log.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to EDSM error received: .",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Obtained log.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Obtaining log....",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Obtaining log .",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to EDSM Responder.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to To connect to EDSM you need to have registered an account with them. Once you have done this you can obtain your API key by clicking on your portrait in the top-right corner of the screen and selecting 'My API Key'.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to If you registered a different commander name from your actual one, please enter it below.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Once you have entered your data above you can pull your existing logs from EDSM so that EDDI knows how many times you have been to each system. You only need to do this the first time you set up EDSM. Note that this can take a while to run.",
"/// </summary>"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 17
| 659
| 84
|
c5254bdaba6a3f41eab557e3e9e44bce8c653c1a
|
paulthomson/jtool-sct
|
projects/avrora/src/main/java/avrora/gui/SingleNodeMonitor.java
|
[
"MIT"
] |
Java
|
SingleNodeMonitor
|
/**
* There are two types of visual monitors for the GUI. First, there are single
* node monitors. Each time a monitor is added to a node, a new panel is created
* and each "instance" of this monitor gets its chalkboard/panel to draw on.
* Second, there are global monitors. Every time a global monitor is attached
* to a new node, one one total chalkboard/diplay panel is created. (e.g. a
* global monitor might have five nodes attached to it, but each node only
* writes to one central chalkboard).
* <p>
* This class is for the first type: single node monitors. It is a physical
* implementation of a monitor factory -> thus once inited, it can create
* nodes on command.
* <p>
* Since many of the single node monitors are very similar is data collection
* and display (just a few lines are different in the actual data collection),
* most single node monitors can just use this class as a factory.
*
* @author Ben L. Titzer
*/
|
There are two types of visual monitors for the GUI. First, there are single
node monitors. Each time a monitor is added to a node, a new panel is created
and each "instance" of this monitor gets its chalkboard/panel to draw on.
Second, there are global monitors. Every time a global monitor is attached
to a new node, one one total chalkboard/diplay panel is created.
@author Ben L. Titzer
|
[
"There",
"are",
"two",
"types",
"of",
"visual",
"monitors",
"for",
"the",
"GUI",
".",
"First",
"there",
"are",
"single",
"node",
"monitors",
".",
"Each",
"time",
"a",
"monitor",
"is",
"added",
"to",
"a",
"node",
"a",
"new",
"panel",
"is",
"created",
"and",
"each",
"\"",
"instance",
"\"",
"of",
"this",
"monitor",
"gets",
"its",
"chalkboard",
"/",
"panel",
"to",
"draw",
"on",
".",
"Second",
"there",
"are",
"global",
"monitors",
".",
"Every",
"time",
"a",
"global",
"monitor",
"is",
"attached",
"to",
"a",
"new",
"node",
"one",
"one",
"total",
"chalkboard",
"/",
"diplay",
"panel",
"is",
"created",
".",
"@author",
"Ben",
"L",
".",
"Titzer"
] |
public abstract class SingleNodeMonitor implements Simulation.Monitor {
final HashMap panelMap; // maps VisualSimulation.Node -> SingleNodePanel
final HashMap monitorMap; // maps MonitorPanel -> PCMonitor
final String monitorName;
/**
* Default constuctor, will init the hash maps that store information
* about the monitors in this node
*/
public SingleNodeMonitor(String n) {
panelMap = new HashMap();
monitorMap = new HashMap();
monitorName = n;
}
/**
* This actually informs our data structure that the list of
* nodes passed to this function want this monitor. A display
* panel is created. Note that the monitors are NOT created
* by attach - you need to call init
*
* @param nodes A list of the nodes that should be attached to the monitor
*/
public void attach(Simulation sim, List nodes) {
Iterator i = nodes.iterator();
while ( i.hasNext()) {
Simulation.Node n = (Simulation.Node)i.next();
if ( panelMap.containsKey(n) ) continue;
MonitorPanel p = AvroraGui.instance.createMonitorPanel(monitorName+" - "+n.id);
SingleNodePanel snp = newPanel(n, p);
panelMap.put(n, snp);
n.addMonitor(this);
}
}
/**
* This is called at the beginning of the simulation to physically
* create the nodes
*
* @param n The node the monitor is attached to
* @param s The simulator that the monitor can be inserted into
*/
public void construct(Simulation sim, Simulation.Node n, Simulator s) {
SingleNodePanel snp = (SingleNodePanel)panelMap.get(n);
snp.construct(s);
}
/**
* This is called at the end of the simulation to remove any data structures
* associated with the nodes.
*
* @param n The node the monitor is attached to
* @param s The simulator that the monitor can be inserted into
*/
public void destruct(Simulation sim, Simulation.Node n, Simulator s) {
SingleNodePanel snp = (SingleNodePanel)panelMap.get(n);
snp.destruct();
}
/**
* You can multiple remove nodes from a monitor using this function
*
* @param nodes A <code> List </code> of nodes that should be removed. If an
* element of the list is not already attached to the node, it will just
* skip that element.
*/
public void remove(Simulation sim, List nodes) {
Iterator i = nodes.iterator();
while ( i.hasNext()) {
Simulation.Node n = (Simulation.Node)i.next();
removeOne(n);
}
}
private void removeOne(Simulation.Node n) {
SingleNodePanel snp = (SingleNodePanel)panelMap.get(n);
if ( snp == null ) return;
snp.remove();
AvroraGui.instance.removeMonitorPanel(snp.panel);
panelMap.remove(n);
n.removeMonitor(this);
}
protected abstract class SingleNodePanel {
protected final Simulation.Node node;
protected final MonitorPanel panel;
SingleNodePanel(Simulation.Node n, MonitorPanel p) {
node = n;
panel = p;
}
protected abstract void construct(Simulator s);
protected abstract void destruct();
protected abstract void remove();
}
protected abstract SingleNodePanel newPanel(Simulation.Node n, MonitorPanel p);
}
|
[
"public",
"abstract",
"class",
"SingleNodeMonitor",
"implements",
"Simulation",
".",
"Monitor",
"{",
"final",
"HashMap",
"panelMap",
";",
"final",
"HashMap",
"monitorMap",
";",
"final",
"String",
"monitorName",
";",
"/**\n * Default constuctor, will init the hash maps that store information\n * about the monitors in this node\n */",
"public",
"SingleNodeMonitor",
"(",
"String",
"n",
")",
"{",
"panelMap",
"=",
"new",
"HashMap",
"(",
")",
";",
"monitorMap",
"=",
"new",
"HashMap",
"(",
")",
";",
"monitorName",
"=",
"n",
";",
"}",
"/**\n * This actually informs our data structure that the list of\n * nodes passed to this function want this monitor. A display \n * panel is created. Note that the monitors are NOT created\n * by attach - you need to call init\n *\n * @param nodes A list of the nodes that should be attached to the monitor\n */",
"public",
"void",
"attach",
"(",
"Simulation",
"sim",
",",
"List",
"nodes",
")",
"{",
"Iterator",
"i",
"=",
"nodes",
".",
"iterator",
"(",
")",
";",
"while",
"(",
"i",
".",
"hasNext",
"(",
")",
")",
"{",
"Simulation",
".",
"Node",
"n",
"=",
"(",
"Simulation",
".",
"Node",
")",
"i",
".",
"next",
"(",
")",
";",
"if",
"(",
"panelMap",
".",
"containsKey",
"(",
"n",
")",
")",
"continue",
";",
"MonitorPanel",
"p",
"=",
"AvroraGui",
".",
"instance",
".",
"createMonitorPanel",
"(",
"monitorName",
"+",
"\"",
" - ",
"\"",
"+",
"n",
".",
"id",
")",
";",
"SingleNodePanel",
"snp",
"=",
"newPanel",
"(",
"n",
",",
"p",
")",
";",
"panelMap",
".",
"put",
"(",
"n",
",",
"snp",
")",
";",
"n",
".",
"addMonitor",
"(",
"this",
")",
";",
"}",
"}",
"/**\n * This is called at the beginning of the simulation to physically\n * create the nodes\n *\n * @param n The node the monitor is attached to\n * @param s The simulator that the monitor can be inserted into\n */",
"public",
"void",
"construct",
"(",
"Simulation",
"sim",
",",
"Simulation",
".",
"Node",
"n",
",",
"Simulator",
"s",
")",
"{",
"SingleNodePanel",
"snp",
"=",
"(",
"SingleNodePanel",
")",
"panelMap",
".",
"get",
"(",
"n",
")",
";",
"snp",
".",
"construct",
"(",
"s",
")",
";",
"}",
"/**\n * This is called at the end of the simulation to remove any data structures\n * associated with the nodes.\n *\n * @param n The node the monitor is attached to\n * @param s The simulator that the monitor can be inserted into\n */",
"public",
"void",
"destruct",
"(",
"Simulation",
"sim",
",",
"Simulation",
".",
"Node",
"n",
",",
"Simulator",
"s",
")",
"{",
"SingleNodePanel",
"snp",
"=",
"(",
"SingleNodePanel",
")",
"panelMap",
".",
"get",
"(",
"n",
")",
";",
"snp",
".",
"destruct",
"(",
")",
";",
"}",
"/**\n * You can multiple remove nodes from a monitor using this function\n *\n * @param nodes A <code> List </code> of nodes that should be removed. If an \n * element of the list is not already attached to the node, it will just\n * skip that element.\n */",
"public",
"void",
"remove",
"(",
"Simulation",
"sim",
",",
"List",
"nodes",
")",
"{",
"Iterator",
"i",
"=",
"nodes",
".",
"iterator",
"(",
")",
";",
"while",
"(",
"i",
".",
"hasNext",
"(",
")",
")",
"{",
"Simulation",
".",
"Node",
"n",
"=",
"(",
"Simulation",
".",
"Node",
")",
"i",
".",
"next",
"(",
")",
";",
"removeOne",
"(",
"n",
")",
";",
"}",
"}",
"private",
"void",
"removeOne",
"(",
"Simulation",
".",
"Node",
"n",
")",
"{",
"SingleNodePanel",
"snp",
"=",
"(",
"SingleNodePanel",
")",
"panelMap",
".",
"get",
"(",
"n",
")",
";",
"if",
"(",
"snp",
"==",
"null",
")",
"return",
";",
"snp",
".",
"remove",
"(",
")",
";",
"AvroraGui",
".",
"instance",
".",
"removeMonitorPanel",
"(",
"snp",
".",
"panel",
")",
";",
"panelMap",
".",
"remove",
"(",
"n",
")",
";",
"n",
".",
"removeMonitor",
"(",
"this",
")",
";",
"}",
"protected",
"abstract",
"class",
"SingleNodePanel",
"{",
"protected",
"final",
"Simulation",
".",
"Node",
"node",
";",
"protected",
"final",
"MonitorPanel",
"panel",
";",
"SingleNodePanel",
"(",
"Simulation",
".",
"Node",
"n",
",",
"MonitorPanel",
"p",
")",
"{",
"node",
"=",
"n",
";",
"panel",
"=",
"p",
";",
"}",
"protected",
"abstract",
"void",
"construct",
"(",
"Simulator",
"s",
")",
";",
"protected",
"abstract",
"void",
"destruct",
"(",
")",
";",
"protected",
"abstract",
"void",
"remove",
"(",
")",
";",
"}",
"protected",
"abstract",
"SingleNodePanel",
"newPanel",
"(",
"Simulation",
".",
"Node",
"n",
",",
"MonitorPanel",
"p",
")",
";",
"}"
] |
There are two types of visual monitors for the GUI.
|
[
"There",
"are",
"two",
"types",
"of",
"visual",
"monitors",
"for",
"the",
"GUI",
"."
] |
[
"// maps VisualSimulation.Node -> SingleNodePanel",
"// maps MonitorPanel -> PCMonitor"
] |
[
{
"param": "Simulation.Monitor",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "Simulation.Monitor",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 14
| 750
| 230
|
5907d321170f4fd4dff840a1455d2822b1b457d0
|
tamlyn/substance
|
packages/split-pane/SplitPane.js
|
[
"MIT"
] |
JavaScript
|
SplitPane
|
/**
A split view layout component. Takes properties for configuration and 2 children via append.
@class SplitPane
@component
@prop {String} splitType either 'vertical' (default) or 'horizontal'.
@prop {String} sizeA size of the first pane (A). '40%' or '100px' or 'inherit' are valid values.
@prop {String} sizeB size of second pane. sizeA and sizeB can not be combined.
@example
```js
$$(SplitPane, {
sizeA: '30%',
splitType: 'horizontal'
}).append(
$$('div').append('Pane A'),
$$('div').append('Pane B')
)
```
*/
|
A split view layout component. Takes properties for configuration and 2 children via append.
|
[
"A",
"split",
"view",
"layout",
"component",
".",
"Takes",
"properties",
"for",
"configuration",
"and",
"2",
"children",
"via",
"append",
"."
] |
class SplitPane extends Component {
render($$) {
if (this.props.children.length !== 2) {
throw new Error('SplitPane only works with exactly two child elements')
}
let el = $$('div').addClass('sc-split-pane')
if (this.props.splitType === 'horizontal') {
el.addClass('sm-horizontal')
} else {
el.addClass('sm-vertical')
}
let paneA = this.props.children[0]
let paneB = this.props.children[1]
// Apply configured size either to pane A or B.
if (this.props.sizeB) {
paneB.addClass('se-pane sm-sized')
paneB.css(this.getSizedStyle(this.props.sizeB))
paneA.addClass('se-pane sm-auto-fill')
} else {
paneA.addClass('se-pane sm-sized')
paneA.css(this.getSizedStyle(this.props.sizeA))
paneB.addClass('se-pane sm-auto-fill')
}
el.append(
paneA,
paneB
)
return el
}
// Accepts % and px units for size property
getSizedStyle(size) {
if (!size || size === 'inherit') return {}
if (this.props.splitType === 'horizontal') {
return {'height': size}
} else {
return {'width': size}
}
}
}
|
[
"class",
"SplitPane",
"extends",
"Component",
"{",
"render",
"(",
"$$",
")",
"{",
"if",
"(",
"this",
".",
"props",
".",
"children",
".",
"length",
"!==",
"2",
")",
"{",
"throw",
"new",
"Error",
"(",
"'SplitPane only works with exactly two child elements'",
")",
"}",
"let",
"el",
"=",
"$$",
"(",
"'div'",
")",
".",
"addClass",
"(",
"'sc-split-pane'",
")",
"if",
"(",
"this",
".",
"props",
".",
"splitType",
"===",
"'horizontal'",
")",
"{",
"el",
".",
"addClass",
"(",
"'sm-horizontal'",
")",
"}",
"else",
"{",
"el",
".",
"addClass",
"(",
"'sm-vertical'",
")",
"}",
"let",
"paneA",
"=",
"this",
".",
"props",
".",
"children",
"[",
"0",
"]",
"let",
"paneB",
"=",
"this",
".",
"props",
".",
"children",
"[",
"1",
"]",
"if",
"(",
"this",
".",
"props",
".",
"sizeB",
")",
"{",
"paneB",
".",
"addClass",
"(",
"'se-pane sm-sized'",
")",
"paneB",
".",
"css",
"(",
"this",
".",
"getSizedStyle",
"(",
"this",
".",
"props",
".",
"sizeB",
")",
")",
"paneA",
".",
"addClass",
"(",
"'se-pane sm-auto-fill'",
")",
"}",
"else",
"{",
"paneA",
".",
"addClass",
"(",
"'se-pane sm-sized'",
")",
"paneA",
".",
"css",
"(",
"this",
".",
"getSizedStyle",
"(",
"this",
".",
"props",
".",
"sizeA",
")",
")",
"paneB",
".",
"addClass",
"(",
"'se-pane sm-auto-fill'",
")",
"}",
"el",
".",
"append",
"(",
"paneA",
",",
"paneB",
")",
"return",
"el",
"}",
"getSizedStyle",
"(",
"size",
")",
"{",
"if",
"(",
"!",
"size",
"||",
"size",
"===",
"'inherit'",
")",
"return",
"{",
"}",
"if",
"(",
"this",
".",
"props",
".",
"splitType",
"===",
"'horizontal'",
")",
"{",
"return",
"{",
"'height'",
":",
"size",
"}",
"}",
"else",
"{",
"return",
"{",
"'width'",
":",
"size",
"}",
"}",
"}",
"}"
] |
A split view layout component.
|
[
"A",
"split",
"view",
"layout",
"component",
"."
] |
[
"// Apply configured size either to pane A or B.",
"// Accepts % and px units for size property"
] |
[
{
"param": "Component",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "Component",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": [
{
"identifier": "class",
"docstring": null,
"docstring_tokens": [
"None"
]
},
{
"identifier": "component",
"docstring": null,
"docstring_tokens": [
"None"
]
},
{
"identifier": "prop",
"docstring": "{String} splitType either 'vertical' (default) or 'horizontal'.",
"docstring_tokens": [
"{",
"String",
"}",
"splitType",
"either",
"'",
"vertical",
"'",
"(",
"default",
")",
"or",
"'",
"horizontal",
"'",
"."
]
},
{
"identifier": "prop",
"docstring": "{String} sizeA size of the first pane (A). '40%' or '100px' or 'inherit' are valid values.",
"docstring_tokens": [
"{",
"String",
"}",
"sizeA",
"size",
"of",
"the",
"first",
"pane",
"(",
"A",
")",
".",
"'",
"40%",
"'",
"or",
"'",
"100px",
"'",
"or",
"'",
"inherit",
"'",
"are",
"valid",
"values",
"."
]
},
{
"identifier": "prop",
"docstring": "{String} sizeB size of second pane. sizeA and sizeB can not be combined.",
"docstring_tokens": [
"{",
"String",
"}",
"sizeB",
"size",
"of",
"second",
"pane",
".",
"sizeA",
"and",
"sizeB",
"can",
"not",
"be",
"combined",
"."
]
},
{
"identifier": "example\n\n```js\n$$(SplitPane,",
"docstring": null,
"docstring_tokens": [
"None"
]
}
]
}
| false
| 15
| 290
| 165
|
898cde2cafe2e299a153b5fe1c18ac8b8e03c68a
|
JeromeJGuay/viking_ADCP_processing
|
rti_python/Codecs/BinaryCodec.py
|
[
"MIT"
] |
Python
|
BinaryCodec
|
Use the 2 threads, AddDataThread and ProcessDataThread
to buffer the streaming data and decode it.
Subscribe to ensemble_event to receive the latest
decoded data.
bin_codec.ensemble_event += event_handler
event_handler(self, sender, ens)
AddDataThread will buffer the data.
ProcessDataThread will decode the buffer.
|
Use the 2 threads, AddDataThread and ProcessDataThread
to buffer the streaming data and decode it.
Subscribe to ensemble_event to receive the latest
decoded data.
AddDataThread will buffer the data.
ProcessDataThread will decode the buffer.
|
[
"Use",
"the",
"2",
"threads",
"AddDataThread",
"and",
"ProcessDataThread",
"to",
"buffer",
"the",
"streaming",
"data",
"and",
"decode",
"it",
".",
"Subscribe",
"to",
"ensemble_event",
"to",
"receive",
"the",
"latest",
"decoded",
"data",
".",
"AddDataThread",
"will",
"buffer",
"the",
"data",
".",
"ProcessDataThread",
"will",
"decode",
"the",
"buffer",
"."
] |
class BinaryCodec:
"""
Use the 2 threads, AddDataThread and ProcessDataThread
to buffer the streaming data and decode it.
Subscribe to ensemble_event to receive the latest
decoded data.
bin_codec.ensemble_event += event_handler
event_handler(self, sender, ens)
AddDataThread will buffer the data.
ProcessDataThread will decode the buffer.
"""
def __init__(self):
"""
Start the two threads.
"""
# Start the Add Data Thread
self.add_data_thread = AddDataThread()
self.add_data_thread.start()
# Start the Processing Data Thread
self.process_data_thread = ProcessDataThread()
self.process_data_thread.ensemble_event += self.receive_ens
self.process_data_thread.start()
def shutdown(self):
"""
Shutdown the two threads.
:return:
"""
self.add_data_thread.shutdown()
self.process_data_thread.shutdown()
@event
def ensemble_event(self, ens):
"""
Event to subscribe to receive the latest ensemble data.
:param ens: Ensemble object
:return:
"""
if ens.IsEnsembleData:
logging.debug(str(ens.EnsembleData.EnsembleNumber))
def receive_ens(self, sender, ens):
"""
Event handler for ProcessDataThread to receive the latest ensembles.
:param sender: Not Used
:param ens: Ensemble data
:return:
"""
# Pass to the ensemble to subscribers of this object
self.ensemble_event(ens)
def add(self, data):
"""
Add data to the AddDataThread. This will start the
processing of the data.
:param data: Data to start decoding.
:return:
"""
self.add_data_thread.add(data)
def buffer_size(self):
"""
Monitor the buffer size.
:return: Buffer size to monitor.
"""
global buffer
return len(buffer)
@staticmethod
def verify_ens_data(ens_data, ens_start=0):
"""
This will check the checksum and verify it is correct.
:param ens_data: Ensemble data.
:param ens_start: Start location in the ens_data
"""
try:
# Ensemble Length
ens_len = len(ens_data)
# Verify at least the minimum number of bytes are available to verify the ensemble
if ens_len <= Ensemble.HeaderSize + Ensemble.ChecksumSize:
return False
# Check Ensemble number
ens_num = struct.unpack("I", ens_data[ens_start + 16 : ens_start + 20])
# Check ensemble size
payload_size = struct.unpack("I", ens_data[ens_start + 24 : ens_start + 28])
# Ensure the entire ensemble is in the buffer
if (
ens_len
>= ens_start
+ Ensemble.HeaderSize
+ payload_size[0]
+ Ensemble.ChecksumSize
):
# Check checksum
checksum_loc = ens_start + Ensemble.HeaderSize + payload_size[0]
checksum = struct.unpack(
"I", ens_data[checksum_loc : checksum_loc + Ensemble.ChecksumSize]
)
# Calculate Checksum
# Use only the payload for the checksum
ens = ens_data[
ens_start
+ Ensemble.HeaderSize : ens_start
+ Ensemble.HeaderSize
+ payload_size[0]
]
calc_checksum = binascii.crc_hqx(ens, 0)
# Verify checksum
if checksum[0] == calc_checksum:
logging.debug(ens_num[0])
return True
else:
logging.warning(
"Ensemble fails checksum. {:#04x} {:#04x}".format(
checksum[0], calc_checksum
)
)
return False
else:
logging.warning("Incomplete ensemble.")
return False
except Exception as e:
logging.error("Error verifying Ensemble. " + str(e))
return False
@staticmethod
def decode_data_sets(ens):
"""
Decode the datasets in the ensemble.
Use verify_ens_data if you are using this
as a static method to verify the data is correct.
:param ens: Ensemble data. Decode the dataset.
:return: Return the decoded ensemble.
"""
# print(ens)
packetPointer = Ensemble.HeaderSize
type = 0
numElements = 0
elementMultiplier = 0
imag = 0
nameLen = 0
name = ""
dataSetSize = 0
ens_len = len(ens)
# Create the ensemble
ensemble = Ensemble()
# Add the raw data to the ensemble
# ensemble.AddRawData(ens)
try:
# Decode the ensemble datasets
for x in range(Ensemble.MaxNumDataSets):
# Check if we are at the end of the payload
if (
packetPointer
>= ens_len - Ensemble.ChecksumSize - Ensemble.HeaderSize
):
break
try:
# Get the dataset info
ds_type = Ensemble.GetInt32(
packetPointer + (Ensemble.BytesInInt32 * 0),
Ensemble.BytesInInt32,
ens,
)
num_elements = Ensemble.GetInt32(
packetPointer + (Ensemble.BytesInInt32 * 1),
Ensemble.BytesInInt32,
ens,
)
element_multiplier = Ensemble.GetInt32(
packetPointer + (Ensemble.BytesInInt32 * 2),
Ensemble.BytesInInt32,
ens,
)
image = Ensemble.GetInt32(
packetPointer + (Ensemble.BytesInInt32 * 3),
Ensemble.BytesInInt32,
ens,
)
name_len = Ensemble.GetInt32(
packetPointer + (Ensemble.BytesInInt32 * 4),
Ensemble.BytesInInt32,
ens,
)
name = str(
ens[
packetPointer
+ (Ensemble.BytesInInt32 * 5) : packetPointer
+ (Ensemble.BytesInInt32 * 5)
+ 8
],
"UTF-8",
)
except Exception as e:
logging.warning("Bad Ensemble header" + str(e))
break
# Calculate the dataset size
data_set_size = Ensemble.GetDataSetSize(
ds_type, name_len, num_elements, element_multiplier
)
# Beam Velocity
if "E000001" in name:
logging.debug(name)
bv = BeamVelocity(num_elements, element_multiplier)
bv.decode(ens[packetPointer : packetPointer + data_set_size])
ensemble.AddBeamVelocity(bv)
# Instrument Velocity
if "E000002" in name:
logging.debug(name)
iv = InstrumentVelocity(num_elements, element_multiplier)
iv.decode(ens[packetPointer : packetPointer + data_set_size])
ensemble.AddInstrumentVelocity(iv)
# Earth Velocity
if "E000003" in name:
logging.debug(name)
ev = EarthVelocity(num_elements, element_multiplier)
ev.decode(ens[packetPointer : packetPointer + data_set_size])
ensemble.AddEarthVelocity(ev)
# Amplitude
if "E000004" in name:
logging.debug(name)
amp = Amplitude(num_elements, element_multiplier)
amp.decode(ens[packetPointer : packetPointer + data_set_size])
ensemble.AddAmplitude(amp)
# Correlation
if "E000005" in name:
logging.debug(name)
corr = Correlation(num_elements, element_multiplier)
corr.decode(ens[packetPointer : packetPointer + data_set_size])
ensemble.AddCorrelation(corr)
# Good Beam
if "E000006" in name:
logging.debug(name)
gb = GoodBeam(num_elements, element_multiplier)
gb.decode(ens[packetPointer : packetPointer + data_set_size])
ensemble.AddGoodBeam(gb)
# Good Earth
if "E000007" in name:
logging.debug(name)
ge = GoodEarth(num_elements, element_multiplier)
ge.decode(ens[packetPointer : packetPointer + data_set_size])
ensemble.AddGoodEarth(ge)
# Ensemble Data
if "E000008" in name:
logging.debug(name)
ed = EnsembleData(num_elements, element_multiplier)
ed.decode(ens[packetPointer : packetPointer + data_set_size])
ensemble.AddEnsembleData(ed)
# Ancillary Data
if "E000009" in name:
logging.debug(name)
ad = AncillaryData(num_elements, element_multiplier)
ad.decode(ens[packetPointer : packetPointer + data_set_size])
ensemble.AddAncillaryData(ad)
# Bottom Track
if "E000010" in name:
logging.debug(name)
bt = BottomTrack(num_elements, element_multiplier)
bt.decode(ens[packetPointer : packetPointer + data_set_size])
ensemble.AddBottomTrack(bt)
# NMEA data
if "E000011" in name:
logging.debug(name)
nd = NmeaData(num_elements, element_multiplier)
nd.decode(ens[packetPointer : packetPointer + data_set_size])
ensemble.AddNmeaData(nd)
# System Setup
if "E000014" in name:
logging.debug(name)
ss = SystemSetup(num_elements, element_multiplier)
ss.decode(ens[packetPointer : packetPointer + data_set_size])
ensemble.AddSystemSetup(ss)
# Range Tracking
if "E000015" in name:
logging.debug(name)
rt = RangeTracking(num_elements, element_multiplier)
rt.decode(ens[packetPointer : packetPointer + data_set_size])
ensemble.AddRangeTracking(rt)
# Move to the next dataset
packetPointer += data_set_size
except Exception as e:
logging.warning("Error decoding the ensemble. " + str(e))
return None
return ensemble
|
[
"class",
"BinaryCodec",
":",
"def",
"__init__",
"(",
"self",
")",
":",
"\"\"\"\n Start the two threads.\n \"\"\"",
"self",
".",
"add_data_thread",
"=",
"AddDataThread",
"(",
")",
"self",
".",
"add_data_thread",
".",
"start",
"(",
")",
"self",
".",
"process_data_thread",
"=",
"ProcessDataThread",
"(",
")",
"self",
".",
"process_data_thread",
".",
"ensemble_event",
"+=",
"self",
".",
"receive_ens",
"self",
".",
"process_data_thread",
".",
"start",
"(",
")",
"def",
"shutdown",
"(",
"self",
")",
":",
"\"\"\"\n Shutdown the two threads.\n :return:\n \"\"\"",
"self",
".",
"add_data_thread",
".",
"shutdown",
"(",
")",
"self",
".",
"process_data_thread",
".",
"shutdown",
"(",
")",
"@",
"event",
"def",
"ensemble_event",
"(",
"self",
",",
"ens",
")",
":",
"\"\"\"\n Event to subscribe to receive the latest ensemble data.\n :param ens: Ensemble object\n :return:\n \"\"\"",
"if",
"ens",
".",
"IsEnsembleData",
":",
"logging",
".",
"debug",
"(",
"str",
"(",
"ens",
".",
"EnsembleData",
".",
"EnsembleNumber",
")",
")",
"def",
"receive_ens",
"(",
"self",
",",
"sender",
",",
"ens",
")",
":",
"\"\"\"\n Event handler for ProcessDataThread to receive the latest ensembles.\n :param sender: Not Used\n :param ens: Ensemble data\n :return:\n \"\"\"",
"self",
".",
"ensemble_event",
"(",
"ens",
")",
"def",
"add",
"(",
"self",
",",
"data",
")",
":",
"\"\"\"\n Add data to the AddDataThread. This will start the\n processing of the data.\n :param data: Data to start decoding.\n :return:\n \"\"\"",
"self",
".",
"add_data_thread",
".",
"add",
"(",
"data",
")",
"def",
"buffer_size",
"(",
"self",
")",
":",
"\"\"\"\n Monitor the buffer size.\n :return: Buffer size to monitor.\n \"\"\"",
"global",
"buffer",
"return",
"len",
"(",
"buffer",
")",
"@",
"staticmethod",
"def",
"verify_ens_data",
"(",
"ens_data",
",",
"ens_start",
"=",
"0",
")",
":",
"\"\"\"\n This will check the checksum and verify it is correct.\n :param ens_data: Ensemble data.\n :param ens_start: Start location in the ens_data\n \"\"\"",
"try",
":",
"ens_len",
"=",
"len",
"(",
"ens_data",
")",
"if",
"ens_len",
"<=",
"Ensemble",
".",
"HeaderSize",
"+",
"Ensemble",
".",
"ChecksumSize",
":",
"return",
"False",
"ens_num",
"=",
"struct",
".",
"unpack",
"(",
"\"I\"",
",",
"ens_data",
"[",
"ens_start",
"+",
"16",
":",
"ens_start",
"+",
"20",
"]",
")",
"payload_size",
"=",
"struct",
".",
"unpack",
"(",
"\"I\"",
",",
"ens_data",
"[",
"ens_start",
"+",
"24",
":",
"ens_start",
"+",
"28",
"]",
")",
"if",
"(",
"ens_len",
">=",
"ens_start",
"+",
"Ensemble",
".",
"HeaderSize",
"+",
"payload_size",
"[",
"0",
"]",
"+",
"Ensemble",
".",
"ChecksumSize",
")",
":",
"checksum_loc",
"=",
"ens_start",
"+",
"Ensemble",
".",
"HeaderSize",
"+",
"payload_size",
"[",
"0",
"]",
"checksum",
"=",
"struct",
".",
"unpack",
"(",
"\"I\"",
",",
"ens_data",
"[",
"checksum_loc",
":",
"checksum_loc",
"+",
"Ensemble",
".",
"ChecksumSize",
"]",
")",
"ens",
"=",
"ens_data",
"[",
"ens_start",
"+",
"Ensemble",
".",
"HeaderSize",
":",
"ens_start",
"+",
"Ensemble",
".",
"HeaderSize",
"+",
"payload_size",
"[",
"0",
"]",
"]",
"calc_checksum",
"=",
"binascii",
".",
"crc_hqx",
"(",
"ens",
",",
"0",
")",
"if",
"checksum",
"[",
"0",
"]",
"==",
"calc_checksum",
":",
"logging",
".",
"debug",
"(",
"ens_num",
"[",
"0",
"]",
")",
"return",
"True",
"else",
":",
"logging",
".",
"warning",
"(",
"\"Ensemble fails checksum. {:#04x} {:#04x}\"",
".",
"format",
"(",
"checksum",
"[",
"0",
"]",
",",
"calc_checksum",
")",
")",
"return",
"False",
"else",
":",
"logging",
".",
"warning",
"(",
"\"Incomplete ensemble.\"",
")",
"return",
"False",
"except",
"Exception",
"as",
"e",
":",
"logging",
".",
"error",
"(",
"\"Error verifying Ensemble. \"",
"+",
"str",
"(",
"e",
")",
")",
"return",
"False",
"@",
"staticmethod",
"def",
"decode_data_sets",
"(",
"ens",
")",
":",
"\"\"\"\n Decode the datasets in the ensemble.\n\n Use verify_ens_data if you are using this\n as a static method to verify the data is correct.\n :param ens: Ensemble data. Decode the dataset.\n :return: Return the decoded ensemble.\n \"\"\"",
"packetPointer",
"=",
"Ensemble",
".",
"HeaderSize",
"type",
"=",
"0",
"numElements",
"=",
"0",
"elementMultiplier",
"=",
"0",
"imag",
"=",
"0",
"nameLen",
"=",
"0",
"name",
"=",
"\"\"",
"dataSetSize",
"=",
"0",
"ens_len",
"=",
"len",
"(",
"ens",
")",
"ensemble",
"=",
"Ensemble",
"(",
")",
"try",
":",
"for",
"x",
"in",
"range",
"(",
"Ensemble",
".",
"MaxNumDataSets",
")",
":",
"if",
"(",
"packetPointer",
">=",
"ens_len",
"-",
"Ensemble",
".",
"ChecksumSize",
"-",
"Ensemble",
".",
"HeaderSize",
")",
":",
"break",
"try",
":",
"ds_type",
"=",
"Ensemble",
".",
"GetInt32",
"(",
"packetPointer",
"+",
"(",
"Ensemble",
".",
"BytesInInt32",
"*",
"0",
")",
",",
"Ensemble",
".",
"BytesInInt32",
",",
"ens",
",",
")",
"num_elements",
"=",
"Ensemble",
".",
"GetInt32",
"(",
"packetPointer",
"+",
"(",
"Ensemble",
".",
"BytesInInt32",
"*",
"1",
")",
",",
"Ensemble",
".",
"BytesInInt32",
",",
"ens",
",",
")",
"element_multiplier",
"=",
"Ensemble",
".",
"GetInt32",
"(",
"packetPointer",
"+",
"(",
"Ensemble",
".",
"BytesInInt32",
"*",
"2",
")",
",",
"Ensemble",
".",
"BytesInInt32",
",",
"ens",
",",
")",
"image",
"=",
"Ensemble",
".",
"GetInt32",
"(",
"packetPointer",
"+",
"(",
"Ensemble",
".",
"BytesInInt32",
"*",
"3",
")",
",",
"Ensemble",
".",
"BytesInInt32",
",",
"ens",
",",
")",
"name_len",
"=",
"Ensemble",
".",
"GetInt32",
"(",
"packetPointer",
"+",
"(",
"Ensemble",
".",
"BytesInInt32",
"*",
"4",
")",
",",
"Ensemble",
".",
"BytesInInt32",
",",
"ens",
",",
")",
"name",
"=",
"str",
"(",
"ens",
"[",
"packetPointer",
"+",
"(",
"Ensemble",
".",
"BytesInInt32",
"*",
"5",
")",
":",
"packetPointer",
"+",
"(",
"Ensemble",
".",
"BytesInInt32",
"*",
"5",
")",
"+",
"8",
"]",
",",
"\"UTF-8\"",
",",
")",
"except",
"Exception",
"as",
"e",
":",
"logging",
".",
"warning",
"(",
"\"Bad Ensemble header\"",
"+",
"str",
"(",
"e",
")",
")",
"break",
"data_set_size",
"=",
"Ensemble",
".",
"GetDataSetSize",
"(",
"ds_type",
",",
"name_len",
",",
"num_elements",
",",
"element_multiplier",
")",
"if",
"\"E000001\"",
"in",
"name",
":",
"logging",
".",
"debug",
"(",
"name",
")",
"bv",
"=",
"BeamVelocity",
"(",
"num_elements",
",",
"element_multiplier",
")",
"bv",
".",
"decode",
"(",
"ens",
"[",
"packetPointer",
":",
"packetPointer",
"+",
"data_set_size",
"]",
")",
"ensemble",
".",
"AddBeamVelocity",
"(",
"bv",
")",
"if",
"\"E000002\"",
"in",
"name",
":",
"logging",
".",
"debug",
"(",
"name",
")",
"iv",
"=",
"InstrumentVelocity",
"(",
"num_elements",
",",
"element_multiplier",
")",
"iv",
".",
"decode",
"(",
"ens",
"[",
"packetPointer",
":",
"packetPointer",
"+",
"data_set_size",
"]",
")",
"ensemble",
".",
"AddInstrumentVelocity",
"(",
"iv",
")",
"if",
"\"E000003\"",
"in",
"name",
":",
"logging",
".",
"debug",
"(",
"name",
")",
"ev",
"=",
"EarthVelocity",
"(",
"num_elements",
",",
"element_multiplier",
")",
"ev",
".",
"decode",
"(",
"ens",
"[",
"packetPointer",
":",
"packetPointer",
"+",
"data_set_size",
"]",
")",
"ensemble",
".",
"AddEarthVelocity",
"(",
"ev",
")",
"if",
"\"E000004\"",
"in",
"name",
":",
"logging",
".",
"debug",
"(",
"name",
")",
"amp",
"=",
"Amplitude",
"(",
"num_elements",
",",
"element_multiplier",
")",
"amp",
".",
"decode",
"(",
"ens",
"[",
"packetPointer",
":",
"packetPointer",
"+",
"data_set_size",
"]",
")",
"ensemble",
".",
"AddAmplitude",
"(",
"amp",
")",
"if",
"\"E000005\"",
"in",
"name",
":",
"logging",
".",
"debug",
"(",
"name",
")",
"corr",
"=",
"Correlation",
"(",
"num_elements",
",",
"element_multiplier",
")",
"corr",
".",
"decode",
"(",
"ens",
"[",
"packetPointer",
":",
"packetPointer",
"+",
"data_set_size",
"]",
")",
"ensemble",
".",
"AddCorrelation",
"(",
"corr",
")",
"if",
"\"E000006\"",
"in",
"name",
":",
"logging",
".",
"debug",
"(",
"name",
")",
"gb",
"=",
"GoodBeam",
"(",
"num_elements",
",",
"element_multiplier",
")",
"gb",
".",
"decode",
"(",
"ens",
"[",
"packetPointer",
":",
"packetPointer",
"+",
"data_set_size",
"]",
")",
"ensemble",
".",
"AddGoodBeam",
"(",
"gb",
")",
"if",
"\"E000007\"",
"in",
"name",
":",
"logging",
".",
"debug",
"(",
"name",
")",
"ge",
"=",
"GoodEarth",
"(",
"num_elements",
",",
"element_multiplier",
")",
"ge",
".",
"decode",
"(",
"ens",
"[",
"packetPointer",
":",
"packetPointer",
"+",
"data_set_size",
"]",
")",
"ensemble",
".",
"AddGoodEarth",
"(",
"ge",
")",
"if",
"\"E000008\"",
"in",
"name",
":",
"logging",
".",
"debug",
"(",
"name",
")",
"ed",
"=",
"EnsembleData",
"(",
"num_elements",
",",
"element_multiplier",
")",
"ed",
".",
"decode",
"(",
"ens",
"[",
"packetPointer",
":",
"packetPointer",
"+",
"data_set_size",
"]",
")",
"ensemble",
".",
"AddEnsembleData",
"(",
"ed",
")",
"if",
"\"E000009\"",
"in",
"name",
":",
"logging",
".",
"debug",
"(",
"name",
")",
"ad",
"=",
"AncillaryData",
"(",
"num_elements",
",",
"element_multiplier",
")",
"ad",
".",
"decode",
"(",
"ens",
"[",
"packetPointer",
":",
"packetPointer",
"+",
"data_set_size",
"]",
")",
"ensemble",
".",
"AddAncillaryData",
"(",
"ad",
")",
"if",
"\"E000010\"",
"in",
"name",
":",
"logging",
".",
"debug",
"(",
"name",
")",
"bt",
"=",
"BottomTrack",
"(",
"num_elements",
",",
"element_multiplier",
")",
"bt",
".",
"decode",
"(",
"ens",
"[",
"packetPointer",
":",
"packetPointer",
"+",
"data_set_size",
"]",
")",
"ensemble",
".",
"AddBottomTrack",
"(",
"bt",
")",
"if",
"\"E000011\"",
"in",
"name",
":",
"logging",
".",
"debug",
"(",
"name",
")",
"nd",
"=",
"NmeaData",
"(",
"num_elements",
",",
"element_multiplier",
")",
"nd",
".",
"decode",
"(",
"ens",
"[",
"packetPointer",
":",
"packetPointer",
"+",
"data_set_size",
"]",
")",
"ensemble",
".",
"AddNmeaData",
"(",
"nd",
")",
"if",
"\"E000014\"",
"in",
"name",
":",
"logging",
".",
"debug",
"(",
"name",
")",
"ss",
"=",
"SystemSetup",
"(",
"num_elements",
",",
"element_multiplier",
")",
"ss",
".",
"decode",
"(",
"ens",
"[",
"packetPointer",
":",
"packetPointer",
"+",
"data_set_size",
"]",
")",
"ensemble",
".",
"AddSystemSetup",
"(",
"ss",
")",
"if",
"\"E000015\"",
"in",
"name",
":",
"logging",
".",
"debug",
"(",
"name",
")",
"rt",
"=",
"RangeTracking",
"(",
"num_elements",
",",
"element_multiplier",
")",
"rt",
".",
"decode",
"(",
"ens",
"[",
"packetPointer",
":",
"packetPointer",
"+",
"data_set_size",
"]",
")",
"ensemble",
".",
"AddRangeTracking",
"(",
"rt",
")",
"packetPointer",
"+=",
"data_set_size",
"except",
"Exception",
"as",
"e",
":",
"logging",
".",
"warning",
"(",
"\"Error decoding the ensemble. \"",
"+",
"str",
"(",
"e",
")",
")",
"return",
"None",
"return",
"ensemble"
] |
Use the 2 threads, AddDataThread and ProcessDataThread
to buffer the streaming data and decode it.
|
[
"Use",
"the",
"2",
"threads",
"AddDataThread",
"and",
"ProcessDataThread",
"to",
"buffer",
"the",
"streaming",
"data",
"and",
"decode",
"it",
"."
] |
[
"\"\"\"\n Use the 2 threads, AddDataThread and ProcessDataThread\n to buffer the streaming data and decode it.\n\n Subscribe to ensemble_event to receive the latest\n decoded data.\n bin_codec.ensemble_event += event_handler\n\n event_handler(self, sender, ens)\n\n AddDataThread will buffer the data.\n ProcessDataThread will decode the buffer.\n \"\"\"",
"\"\"\"\n Start the two threads.\n \"\"\"",
"# Start the Add Data Thread",
"# Start the Processing Data Thread",
"\"\"\"\n Shutdown the two threads.\n :return:\n \"\"\"",
"\"\"\"\n Event to subscribe to receive the latest ensemble data.\n :param ens: Ensemble object\n :return:\n \"\"\"",
"\"\"\"\n Event handler for ProcessDataThread to receive the latest ensembles.\n :param sender: Not Used\n :param ens: Ensemble data\n :return:\n \"\"\"",
"# Pass to the ensemble to subscribers of this object",
"\"\"\"\n Add data to the AddDataThread. This will start the\n processing of the data.\n :param data: Data to start decoding.\n :return:\n \"\"\"",
"\"\"\"\n Monitor the buffer size.\n :return: Buffer size to monitor.\n \"\"\"",
"\"\"\"\n This will check the checksum and verify it is correct.\n :param ens_data: Ensemble data.\n :param ens_start: Start location in the ens_data\n \"\"\"",
"# Ensemble Length",
"# Verify at least the minimum number of bytes are available to verify the ensemble",
"# Check Ensemble number",
"# Check ensemble size",
"# Ensure the entire ensemble is in the buffer",
"# Check checksum",
"# Calculate Checksum",
"# Use only the payload for the checksum",
"# Verify checksum",
"\"\"\"\n Decode the datasets in the ensemble.\n\n Use verify_ens_data if you are using this\n as a static method to verify the data is correct.\n :param ens: Ensemble data. Decode the dataset.\n :return: Return the decoded ensemble.\n \"\"\"",
"# print(ens)",
"# Create the ensemble",
"# Add the raw data to the ensemble",
"# ensemble.AddRawData(ens)",
"# Decode the ensemble datasets",
"# Check if we are at the end of the payload",
"# Get the dataset info",
"# Calculate the dataset size",
"# Beam Velocity",
"# Instrument Velocity",
"# Earth Velocity",
"# Amplitude",
"# Correlation",
"# Good Beam",
"# Good Earth",
"# Ensemble Data",
"# Ancillary Data",
"# Bottom Track",
"# NMEA data",
"# System Setup",
"# Range Tracking",
"# Move to the next dataset"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 23
| 2,204
| 78
|
8068b486b6e28e6e115d2353aa09ed8f5c24a476
|
Jotschi/mesh
|
databases/orientdb/src/main/java/com/syncleus/ferma/ext/orientdb3/OrientDBTx.java
|
[
"Apache-2.0"
] |
Java
|
OrientDBTx
|
/**
* Implementation of an OrientDB transaction.
*
* This implementation cares care of various aspects including:
* <ul>
* <li>Handling of nested/wrapped transactions</li>
* <li>Collecting metrics on Tx duration</li>
* <li>Providing access to various dao methods</li>
* <li>Providing access to {@link TxData} via {@link #txData}</li>
* <li>Handling topology locks before commit via {@link Database#blockingTopologyLockCheck()}</li>
* <li>Register and Unregister of active Tx via {@link TxCleanupTask}</li>
* <li>Making Tx accessible via threadlocal {@link Tx#setActive(Tx)}
* </ul>
*/
|
Implementation of an OrientDB transaction.
This implementation cares care of various aspects including:
Handling of nested/wrapped transactions
Collecting metrics on Tx duration
Providing access to various dao methods
Providing access to TxData via #txData
Handling topology locks before commit via Database#blockingTopologyLockCheck()
Register and Unregister of active Tx via TxCleanupTask
Making Tx accessible via threadlocal Tx#setActive(Tx)
|
[
"Implementation",
"of",
"an",
"OrientDB",
"transaction",
".",
"This",
"implementation",
"cares",
"care",
"of",
"various",
"aspects",
"including",
":",
"Handling",
"of",
"nested",
"/",
"wrapped",
"transactions",
"Collecting",
"metrics",
"on",
"Tx",
"duration",
"Providing",
"access",
"to",
"various",
"dao",
"methods",
"Providing",
"access",
"to",
"TxData",
"via",
"#txData",
"Handling",
"topology",
"locks",
"before",
"commit",
"via",
"Database#blockingTopologyLockCheck",
"()",
"Register",
"and",
"Unregister",
"of",
"active",
"Tx",
"via",
"TxCleanupTask",
"Making",
"Tx",
"accessible",
"via",
"threadlocal",
"Tx#setActive",
"(",
"Tx",
")"
] |
public class OrientDBTx extends AbstractTx<FramedTransactionalGraph> {
private static final Logger log = LoggerFactory.getLogger(OrientDBTx.class);
boolean isWrapped = false;
private final TypeResolver typeResolver;
private final Database db;
private final BootstrapInitializer boot;
private final TxData txData;
private final ContextDataRegistry contextDataRegistry;
private final DaoCollection daos;
private final Binaries binaries;
private Timer commitTimer;
@Inject
public OrientDBTx(MeshOptions options, Database db, BootstrapInitializer boot, DaoCollection daos, OrientStorage provider,
TypeResolver typeResolver, MetricsService metrics, PermissionRoots permissionRoots, ContextDataRegistry contextDataRegistry,
Binaries binaries) {
this.db = db;
this.boot = boot;
this.typeResolver = typeResolver;
if (metrics != null) {
this.commitTimer = metrics.timer(COMMIT_TIME);
}
// Check if an active transaction already exists.
Tx activeTx = Tx.get();
if (activeTx != null) {
// TODO Use this spot here to check for nested / wrapped transactions. Nested Tx must not be used when using MDM / Hibernate
isWrapped = true;
init(activeTx.getGraph());
} else {
DelegatingFramedOrientGraph transaction = new DelegatingFramedOrientGraph((OrientGraph) provider.rawTx(), typeResolver);
init(transaction);
}
this.txData = new TxDataImpl(options, boot, permissionRoots);
this.contextDataRegistry = contextDataRegistry;
this.daos = daos;
this.binaries = binaries;
}
@Override
public void close() {
try {
if (isSuccess()) {
try {
db.blockingTopologyLockCheck();
Thread t = Thread.currentThread();
TxCleanupTask.register(t);
Timer.Sample sample = Timer.start();
try {
commit();
} finally {
sample.stop(commitTimer);
TxCleanupTask.unregister(t);
}
} catch (Exception e) {
rollback();
throw e;
}
} else {
rollback();
}
} catch (ONeedRetryException e) {
throw e;
} finally {
if (!isWrapped) {
// Restore the old graph that was previously swapped with the current graph
getGraph().shutdown();
Tx.setActive(null);
}
}
}
@Override
public <T extends RawTraversalResult<?>> T traversal(Function<GraphTraversalSource, GraphTraversal<?, ?>> traverser) {
return (T) new RawTraversalResultImpl(traverser.apply(rawTraverse()), typeResolver);
}
@Override
public GraphTraversalSource rawTraverse() {
// TODO Auto-generated method stub
return null;
}
@Override
public <T> T createVertex(Class<T> clazzOfR) {
// TODO Auto-generated method stub
return null;
}
@Override
public <E extends Element> E getElement(Object id) {
// TODO Auto-generated method stub
return null;
}
@Override
public int txId() {
// TODO Auto-generated method stub
return 0;
}
@Override
protected void init(FramedTransactionalGraph transactionalGraph) {
Mesh mesh = boot.mesh();
if (mesh != null) {
transactionalGraph.setAttribute(MESH_COMPONENT, mesh.internal());
} else {
log.error("Could not set mesh component attribute. Followup errors may happen.");
}
super.init(transactionalGraph);
}
@Override
public TxData data() {
return txData;
}
@Override
public HibBranch getBranch(InternalActionContext ac) {
return contextDataRegistry.getBranch(ac);
}
@Override
public HibBranch getBranch(InternalActionContext ac, HibProject project) {
return contextDataRegistry.getBranch(ac, project);
}
@Override
public HibProject getProject(InternalActionContext ac) {
return contextDataRegistry.getProject(ac);
}
// DAOs
@Override
public UserDaoWrapper userDao() {
return daos.userDao();
}
@Override
public UserDAOActions userActions() {
return daos.userActions();
}
@Override
public GroupDAOActions groupActions() {
return daos.groupActions();
}
@Override
public RoleDAOActions roleActions() {
return daos.roleActions();
}
@Override
public ProjectDAOActions projectActions() {
return daos.projectActions();
}
@Override
public TagFamilyDAOActions tagFamilyActions() {
return daos.tagFamilyActions();
}
@Override
public TagDAOActions tagActions() {
return daos.tagActions();
}
@Override
public BranchDAOActions branchActions() {
return daos.branchActions();
}
@Override
public MicroschemaDAOActions microschemaActions() {
return daos.microschemaActions();
}
@Override
public SchemaDAOActions schemaActions() {
return daos.schemaActions();
}
@Override
public GroupDaoWrapper groupDao() {
return daos.groupDao();
}
@Override
public RoleDaoWrapper roleDao() {
return daos.roleDao();
}
@Override
public ProjectDaoWrapper projectDao() {
return daos.projectDao();
}
@Override
public JobDaoWrapper jobDao() {
return daos.jobDao();
}
@Override
public LanguageDaoWrapper languageDao() {
return daos.languageDao();
}
@Override
public SchemaDaoWrapper schemaDao() {
return daos.schemaDao();
}
@Override
public TagDaoWrapper tagDao() {
return daos.tagDao();
}
@Override
public TagFamilyDaoWrapper tagFamilyDao() {
return daos.tagFamilyDao();
}
@Override
public MicroschemaDaoWrapper microschemaDao() {
return daos.microschemaDao();
}
@Override
public BinaryDaoWrapper binaryDao() {
return daos.binaryDao();
}
@Override
public BranchDaoWrapper branchDao() {
return daos.branchDao();
}
@Override
public NodeDaoWrapper nodeDao() {
return daos.nodeDao();
}
@Override
public ContentDaoWrapper contentDao() {
return daos.contentDao();
}
@Override
public Binaries binaries() {
return binaries;
}
}
|
[
"public",
"class",
"OrientDBTx",
"extends",
"AbstractTx",
"<",
"FramedTransactionalGraph",
">",
"{",
"private",
"static",
"final",
"Logger",
"log",
"=",
"LoggerFactory",
".",
"getLogger",
"(",
"OrientDBTx",
".",
"class",
")",
";",
"boolean",
"isWrapped",
"=",
"false",
";",
"private",
"final",
"TypeResolver",
"typeResolver",
";",
"private",
"final",
"Database",
"db",
";",
"private",
"final",
"BootstrapInitializer",
"boot",
";",
"private",
"final",
"TxData",
"txData",
";",
"private",
"final",
"ContextDataRegistry",
"contextDataRegistry",
";",
"private",
"final",
"DaoCollection",
"daos",
";",
"private",
"final",
"Binaries",
"binaries",
";",
"private",
"Timer",
"commitTimer",
";",
"@",
"Inject",
"public",
"OrientDBTx",
"(",
"MeshOptions",
"options",
",",
"Database",
"db",
",",
"BootstrapInitializer",
"boot",
",",
"DaoCollection",
"daos",
",",
"OrientStorage",
"provider",
",",
"TypeResolver",
"typeResolver",
",",
"MetricsService",
"metrics",
",",
"PermissionRoots",
"permissionRoots",
",",
"ContextDataRegistry",
"contextDataRegistry",
",",
"Binaries",
"binaries",
")",
"{",
"this",
".",
"db",
"=",
"db",
";",
"this",
".",
"boot",
"=",
"boot",
";",
"this",
".",
"typeResolver",
"=",
"typeResolver",
";",
"if",
"(",
"metrics",
"!=",
"null",
")",
"{",
"this",
".",
"commitTimer",
"=",
"metrics",
".",
"timer",
"(",
"COMMIT_TIME",
")",
";",
"}",
"Tx",
"activeTx",
"=",
"Tx",
".",
"get",
"(",
")",
";",
"if",
"(",
"activeTx",
"!=",
"null",
")",
"{",
"isWrapped",
"=",
"true",
";",
"init",
"(",
"activeTx",
".",
"getGraph",
"(",
")",
")",
";",
"}",
"else",
"{",
"DelegatingFramedOrientGraph",
"transaction",
"=",
"new",
"DelegatingFramedOrientGraph",
"(",
"(",
"OrientGraph",
")",
"provider",
".",
"rawTx",
"(",
")",
",",
"typeResolver",
")",
";",
"init",
"(",
"transaction",
")",
";",
"}",
"this",
".",
"txData",
"=",
"new",
"TxDataImpl",
"(",
"options",
",",
"boot",
",",
"permissionRoots",
")",
";",
"this",
".",
"contextDataRegistry",
"=",
"contextDataRegistry",
";",
"this",
".",
"daos",
"=",
"daos",
";",
"this",
".",
"binaries",
"=",
"binaries",
";",
"}",
"@",
"Override",
"public",
"void",
"close",
"(",
")",
"{",
"try",
"{",
"if",
"(",
"isSuccess",
"(",
")",
")",
"{",
"try",
"{",
"db",
".",
"blockingTopologyLockCheck",
"(",
")",
";",
"Thread",
"t",
"=",
"Thread",
".",
"currentThread",
"(",
")",
";",
"TxCleanupTask",
".",
"register",
"(",
"t",
")",
";",
"Timer",
".",
"Sample",
"sample",
"=",
"Timer",
".",
"start",
"(",
")",
";",
"try",
"{",
"commit",
"(",
")",
";",
"}",
"finally",
"{",
"sample",
".",
"stop",
"(",
"commitTimer",
")",
";",
"TxCleanupTask",
".",
"unregister",
"(",
"t",
")",
";",
"}",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"rollback",
"(",
")",
";",
"throw",
"e",
";",
"}",
"}",
"else",
"{",
"rollback",
"(",
")",
";",
"}",
"}",
"catch",
"(",
"ONeedRetryException",
"e",
")",
"{",
"throw",
"e",
";",
"}",
"finally",
"{",
"if",
"(",
"!",
"isWrapped",
")",
"{",
"getGraph",
"(",
")",
".",
"shutdown",
"(",
")",
";",
"Tx",
".",
"setActive",
"(",
"null",
")",
";",
"}",
"}",
"}",
"@",
"Override",
"public",
"<",
"T",
"extends",
"RawTraversalResult",
"<",
"?",
">",
">",
"T",
"traversal",
"(",
"Function",
"<",
"GraphTraversalSource",
",",
"GraphTraversal",
"<",
"?",
",",
"?",
">",
">",
"traverser",
")",
"{",
"return",
"(",
"T",
")",
"new",
"RawTraversalResultImpl",
"(",
"traverser",
".",
"apply",
"(",
"rawTraverse",
"(",
")",
")",
",",
"typeResolver",
")",
";",
"}",
"@",
"Override",
"public",
"GraphTraversalSource",
"rawTraverse",
"(",
")",
"{",
"return",
"null",
";",
"}",
"@",
"Override",
"public",
"<",
"T",
">",
"T",
"createVertex",
"(",
"Class",
"<",
"T",
">",
"clazzOfR",
")",
"{",
"return",
"null",
";",
"}",
"@",
"Override",
"public",
"<",
"E",
"extends",
"Element",
">",
"E",
"getElement",
"(",
"Object",
"id",
")",
"{",
"return",
"null",
";",
"}",
"@",
"Override",
"public",
"int",
"txId",
"(",
")",
"{",
"return",
"0",
";",
"}",
"@",
"Override",
"protected",
"void",
"init",
"(",
"FramedTransactionalGraph",
"transactionalGraph",
")",
"{",
"Mesh",
"mesh",
"=",
"boot",
".",
"mesh",
"(",
")",
";",
"if",
"(",
"mesh",
"!=",
"null",
")",
"{",
"transactionalGraph",
".",
"setAttribute",
"(",
"MESH_COMPONENT",
",",
"mesh",
".",
"internal",
"(",
")",
")",
";",
"}",
"else",
"{",
"log",
".",
"error",
"(",
"\"",
"Could not set mesh component attribute. Followup errors may happen.",
"\"",
")",
";",
"}",
"super",
".",
"init",
"(",
"transactionalGraph",
")",
";",
"}",
"@",
"Override",
"public",
"TxData",
"data",
"(",
")",
"{",
"return",
"txData",
";",
"}",
"@",
"Override",
"public",
"HibBranch",
"getBranch",
"(",
"InternalActionContext",
"ac",
")",
"{",
"return",
"contextDataRegistry",
".",
"getBranch",
"(",
"ac",
")",
";",
"}",
"@",
"Override",
"public",
"HibBranch",
"getBranch",
"(",
"InternalActionContext",
"ac",
",",
"HibProject",
"project",
")",
"{",
"return",
"contextDataRegistry",
".",
"getBranch",
"(",
"ac",
",",
"project",
")",
";",
"}",
"@",
"Override",
"public",
"HibProject",
"getProject",
"(",
"InternalActionContext",
"ac",
")",
"{",
"return",
"contextDataRegistry",
".",
"getProject",
"(",
"ac",
")",
";",
"}",
"@",
"Override",
"public",
"UserDaoWrapper",
"userDao",
"(",
")",
"{",
"return",
"daos",
".",
"userDao",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"UserDAOActions",
"userActions",
"(",
")",
"{",
"return",
"daos",
".",
"userActions",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"GroupDAOActions",
"groupActions",
"(",
")",
"{",
"return",
"daos",
".",
"groupActions",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"RoleDAOActions",
"roleActions",
"(",
")",
"{",
"return",
"daos",
".",
"roleActions",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"ProjectDAOActions",
"projectActions",
"(",
")",
"{",
"return",
"daos",
".",
"projectActions",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"TagFamilyDAOActions",
"tagFamilyActions",
"(",
")",
"{",
"return",
"daos",
".",
"tagFamilyActions",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"TagDAOActions",
"tagActions",
"(",
")",
"{",
"return",
"daos",
".",
"tagActions",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"BranchDAOActions",
"branchActions",
"(",
")",
"{",
"return",
"daos",
".",
"branchActions",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"MicroschemaDAOActions",
"microschemaActions",
"(",
")",
"{",
"return",
"daos",
".",
"microschemaActions",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"SchemaDAOActions",
"schemaActions",
"(",
")",
"{",
"return",
"daos",
".",
"schemaActions",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"GroupDaoWrapper",
"groupDao",
"(",
")",
"{",
"return",
"daos",
".",
"groupDao",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"RoleDaoWrapper",
"roleDao",
"(",
")",
"{",
"return",
"daos",
".",
"roleDao",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"ProjectDaoWrapper",
"projectDao",
"(",
")",
"{",
"return",
"daos",
".",
"projectDao",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"JobDaoWrapper",
"jobDao",
"(",
")",
"{",
"return",
"daos",
".",
"jobDao",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"LanguageDaoWrapper",
"languageDao",
"(",
")",
"{",
"return",
"daos",
".",
"languageDao",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"SchemaDaoWrapper",
"schemaDao",
"(",
")",
"{",
"return",
"daos",
".",
"schemaDao",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"TagDaoWrapper",
"tagDao",
"(",
")",
"{",
"return",
"daos",
".",
"tagDao",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"TagFamilyDaoWrapper",
"tagFamilyDao",
"(",
")",
"{",
"return",
"daos",
".",
"tagFamilyDao",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"MicroschemaDaoWrapper",
"microschemaDao",
"(",
")",
"{",
"return",
"daos",
".",
"microschemaDao",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"BinaryDaoWrapper",
"binaryDao",
"(",
")",
"{",
"return",
"daos",
".",
"binaryDao",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"BranchDaoWrapper",
"branchDao",
"(",
")",
"{",
"return",
"daos",
".",
"branchDao",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"NodeDaoWrapper",
"nodeDao",
"(",
")",
"{",
"return",
"daos",
".",
"nodeDao",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"ContentDaoWrapper",
"contentDao",
"(",
")",
"{",
"return",
"daos",
".",
"contentDao",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"Binaries",
"binaries",
"(",
")",
"{",
"return",
"binaries",
";",
"}",
"}"
] |
Implementation of an OrientDB transaction.
|
[
"Implementation",
"of",
"an",
"OrientDB",
"transaction",
"."
] |
[
"// Check if an active transaction already exists.",
"// TODO Use this spot here to check for nested / wrapped transactions. Nested Tx must not be used when using MDM / Hibernate",
"// Restore the old graph that was previously swapped with the current graph",
"// TODO Auto-generated method stub",
"// TODO Auto-generated method stub",
"// TODO Auto-generated method stub",
"// TODO Auto-generated method stub",
"// DAOs"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 17
| 1,364
| 153
|
eda4d4a6427eca689193d922241627f53f5fe02d
|
Tombmyst/Empire
|
Python/empire/aws/s3/structs/file_to_fetch.py
|
[
"Apache-2.0"
] |
Python
|
FileToFetch
|
Maps the following fields:
- _destination: The local destination. If None, the file will be downloaded in memory, in fetch_items dictionary
- bucket_name: The source bucket name
- object_key: The source object key
- object_version: Optional. Object version
- write_type: Optional, defaults to 'w'. Specifies the open type when writing to disk the downloaded file.
- auto_extract: Optional. If the downloaded file is an archive, you put the path where to automatically extract the archive to.
- ignore_errors: Optional. When set to true, calls try_get_object instead of get_object
- command: Optional. A command to execute (BASH) while fetching item, in fact, when item has been downloaded, and if specified, before extraction
- duration: ?
|
Maps the following fields:
_destination: The local destination. If None, the file will be downloaded in memory, in fetch_items dictionary
bucket_name: The source bucket name
object_key: The source object key
object_version: Optional. Object version
write_type: Optional, defaults to 'w'. Specifies the open type when writing to disk the downloaded file.
|
[
"Maps",
"the",
"following",
"fields",
":",
"_destination",
":",
"The",
"local",
"destination",
".",
"If",
"None",
"the",
"file",
"will",
"be",
"downloaded",
"in",
"memory",
"in",
"fetch_items",
"dictionary",
"bucket_name",
":",
"The",
"source",
"bucket",
"name",
"object_key",
":",
"The",
"source",
"object",
"key",
"object_version",
":",
"Optional",
".",
"Object",
"version",
"write_type",
":",
"Optional",
"defaults",
"to",
"'",
"w",
"'",
".",
"Specifies",
"the",
"open",
"type",
"when",
"writing",
"to",
"disk",
"the",
"downloaded",
"file",
"."
] |
class FileToFetch:
"""
Maps the following fields:
- _destination: The local destination. If None, the file will be downloaded in memory, in fetch_items dictionary
- bucket_name: The source bucket name
- object_key: The source object key
- object_version: Optional. Object version
- write_type: Optional, defaults to 'w'. Specifies the open type when writing to disk the downloaded file.
- auto_extract: Optional. If the downloaded file is an archive, you put the path where to automatically extract the archive to.
- ignore_errors: Optional. When set to true, calls try_get_object instead of get_object
- command: Optional. A command to execute (BASH) while fetching item, in fact, when item has been downloaded, and if specified, before extraction
- duration: ?
"""
def __init__(self, **kwargs):
self._bucket: str = kwargs['bucket']
self._object_key: str = kwargs['key']
self._object_version: Union[str, None] = kwargs['version']
self._destination: str = kwargs['dest']
self._state: int = kwargs['state']
self._write_type: str = kwargs['write_type']
self._auto_extract: Union[str, None] = kwargs['auto_extract']
self._ignore_errors: bool = kwargs['ignore_errors']
self._command: Union[str, None] = kwargs['command']
self._command_pipes: JSON = {'out': None, 'err': None}
self._duration: int = kwargs['duration']
self._in_memory_file_contents: Union[str, JSON, None] = None
self._keys_to_keep: List[str] = kwargs.get('keys_to_keep', []) or []
@property
def bucket(self) -> str:
return self._bucket
@property
def key(self) -> str:
return self._object_key
@property
def version(self) -> Union[str, None]:
return self._object_version
@version.setter
def version(self, version: Union[str, None]) -> None:
self._object_version = version
@property
def dest(self) -> str:
return self._destination
@property
def state(self) -> int:
return self._state
@state.setter
def state(self, state: int) -> None:
self._state = state
@property
def write_type(self) -> str:
return self._write_type
@property
def auto_extract(self) -> Union[str, None]:
return self._auto_extract
@property
def ignore_errors(self) -> bool:
return self._ignore_errors
@property
def command(self) -> Union[str, None]:
return self._command
@property
def duration(self) -> int:
return self._duration
@duration.setter
def duration(self, duration: int) -> None:
self._duration = duration
@property
def in_memory_file_contents(self) -> Union[str, JSON, None]:
return self._in_memory_file_contents
@in_memory_file_contents.setter
def in_memory_file_contents(self, contents: Union[str, JSON]) -> None:
self._in_memory_file_contents = contents
@property
def command_pipe_out(self) -> Any:
return self._command_pipes['out']
@command_pipe_out.setter
def command_pipe_out(self, out: Any) -> None:
self._command_pipes['out'] = out
@property
def command_pipe_err(self) -> Any:
return self._command_pipes['err']
@command_pipe_err.setter
def command_pipe_err(self, err: Any) -> None:
self._command_pipes['err'] = err
@property
def keys_to_keep(self) -> List[str]:
return self._keys_to_keep
def __eq__(self, other) -> bool:
try:
return self._duration == other.duration and self._command == other.command and self._ignore_errors == other.ignore_errors and \
self._auto_extract == other.auto_extract and self._write_type == other.write_type and self._state == other.state and \
self._destination == other.dest and self._object_version == other.version and self._object_key == other.key and \
self._bucket == other.bucket
except Exception:
return False
def __ne__(self, other) -> bool:
return not (self == other)
def __str__(self) -> str:
s: str = ''
s += f'\rBucket Name: {self._bucket}'
s += f'\rObject Key: {self._object_key}'
s += f'\rObject Version: {self._object_version}'
s += f'\rDestination: {self._destination}'
s += '\rState: {}'.format(FetchingStates.to_string(self._state))
s += f'\rWrite type: {self._write_type}'
s += f'\rAuto Extract to: {self._auto_extract}'
s += f'\rIgnore Errors? {self._ignore_errors}'
s += f'\rCommand: {self._command}'
s += f'\rDuration: {self._duration}'
s += '\rHas File Contents In-Mem? {}'.format(self._in_memory_file_contents is not None)
return s
def __repr__(self) -> str:
return str(self)
def __hash__(self):
return hash((self._bucket, self._object_key, self._object_version if self._object_version is not None else 'LATEST'))
|
[
"class",
"FileToFetch",
":",
"def",
"__init__",
"(",
"self",
",",
"**",
"kwargs",
")",
":",
"self",
".",
"_bucket",
":",
"str",
"=",
"kwargs",
"[",
"'bucket'",
"]",
"self",
".",
"_object_key",
":",
"str",
"=",
"kwargs",
"[",
"'key'",
"]",
"self",
".",
"_object_version",
":",
"Union",
"[",
"str",
",",
"None",
"]",
"=",
"kwargs",
"[",
"'version'",
"]",
"self",
".",
"_destination",
":",
"str",
"=",
"kwargs",
"[",
"'dest'",
"]",
"self",
".",
"_state",
":",
"int",
"=",
"kwargs",
"[",
"'state'",
"]",
"self",
".",
"_write_type",
":",
"str",
"=",
"kwargs",
"[",
"'write_type'",
"]",
"self",
".",
"_auto_extract",
":",
"Union",
"[",
"str",
",",
"None",
"]",
"=",
"kwargs",
"[",
"'auto_extract'",
"]",
"self",
".",
"_ignore_errors",
":",
"bool",
"=",
"kwargs",
"[",
"'ignore_errors'",
"]",
"self",
".",
"_command",
":",
"Union",
"[",
"str",
",",
"None",
"]",
"=",
"kwargs",
"[",
"'command'",
"]",
"self",
".",
"_command_pipes",
":",
"JSON",
"=",
"{",
"'out'",
":",
"None",
",",
"'err'",
":",
"None",
"}",
"self",
".",
"_duration",
":",
"int",
"=",
"kwargs",
"[",
"'duration'",
"]",
"self",
".",
"_in_memory_file_contents",
":",
"Union",
"[",
"str",
",",
"JSON",
",",
"None",
"]",
"=",
"None",
"self",
".",
"_keys_to_keep",
":",
"List",
"[",
"str",
"]",
"=",
"kwargs",
".",
"get",
"(",
"'keys_to_keep'",
",",
"[",
"]",
")",
"or",
"[",
"]",
"@",
"property",
"def",
"bucket",
"(",
"self",
")",
"->",
"str",
":",
"return",
"self",
".",
"_bucket",
"@",
"property",
"def",
"key",
"(",
"self",
")",
"->",
"str",
":",
"return",
"self",
".",
"_object_key",
"@",
"property",
"def",
"version",
"(",
"self",
")",
"->",
"Union",
"[",
"str",
",",
"None",
"]",
":",
"return",
"self",
".",
"_object_version",
"@",
"version",
".",
"setter",
"def",
"version",
"(",
"self",
",",
"version",
":",
"Union",
"[",
"str",
",",
"None",
"]",
")",
"->",
"None",
":",
"self",
".",
"_object_version",
"=",
"version",
"@",
"property",
"def",
"dest",
"(",
"self",
")",
"->",
"str",
":",
"return",
"self",
".",
"_destination",
"@",
"property",
"def",
"state",
"(",
"self",
")",
"->",
"int",
":",
"return",
"self",
".",
"_state",
"@",
"state",
".",
"setter",
"def",
"state",
"(",
"self",
",",
"state",
":",
"int",
")",
"->",
"None",
":",
"self",
".",
"_state",
"=",
"state",
"@",
"property",
"def",
"write_type",
"(",
"self",
")",
"->",
"str",
":",
"return",
"self",
".",
"_write_type",
"@",
"property",
"def",
"auto_extract",
"(",
"self",
")",
"->",
"Union",
"[",
"str",
",",
"None",
"]",
":",
"return",
"self",
".",
"_auto_extract",
"@",
"property",
"def",
"ignore_errors",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"self",
".",
"_ignore_errors",
"@",
"property",
"def",
"command",
"(",
"self",
")",
"->",
"Union",
"[",
"str",
",",
"None",
"]",
":",
"return",
"self",
".",
"_command",
"@",
"property",
"def",
"duration",
"(",
"self",
")",
"->",
"int",
":",
"return",
"self",
".",
"_duration",
"@",
"duration",
".",
"setter",
"def",
"duration",
"(",
"self",
",",
"duration",
":",
"int",
")",
"->",
"None",
":",
"self",
".",
"_duration",
"=",
"duration",
"@",
"property",
"def",
"in_memory_file_contents",
"(",
"self",
")",
"->",
"Union",
"[",
"str",
",",
"JSON",
",",
"None",
"]",
":",
"return",
"self",
".",
"_in_memory_file_contents",
"@",
"in_memory_file_contents",
".",
"setter",
"def",
"in_memory_file_contents",
"(",
"self",
",",
"contents",
":",
"Union",
"[",
"str",
",",
"JSON",
"]",
")",
"->",
"None",
":",
"self",
".",
"_in_memory_file_contents",
"=",
"contents",
"@",
"property",
"def",
"command_pipe_out",
"(",
"self",
")",
"->",
"Any",
":",
"return",
"self",
".",
"_command_pipes",
"[",
"'out'",
"]",
"@",
"command_pipe_out",
".",
"setter",
"def",
"command_pipe_out",
"(",
"self",
",",
"out",
":",
"Any",
")",
"->",
"None",
":",
"self",
".",
"_command_pipes",
"[",
"'out'",
"]",
"=",
"out",
"@",
"property",
"def",
"command_pipe_err",
"(",
"self",
")",
"->",
"Any",
":",
"return",
"self",
".",
"_command_pipes",
"[",
"'err'",
"]",
"@",
"command_pipe_err",
".",
"setter",
"def",
"command_pipe_err",
"(",
"self",
",",
"err",
":",
"Any",
")",
"->",
"None",
":",
"self",
".",
"_command_pipes",
"[",
"'err'",
"]",
"=",
"err",
"@",
"property",
"def",
"keys_to_keep",
"(",
"self",
")",
"->",
"List",
"[",
"str",
"]",
":",
"return",
"self",
".",
"_keys_to_keep",
"def",
"__eq__",
"(",
"self",
",",
"other",
")",
"->",
"bool",
":",
"try",
":",
"return",
"self",
".",
"_duration",
"==",
"other",
".",
"duration",
"and",
"self",
".",
"_command",
"==",
"other",
".",
"command",
"and",
"self",
".",
"_ignore_errors",
"==",
"other",
".",
"ignore_errors",
"and",
"self",
".",
"_auto_extract",
"==",
"other",
".",
"auto_extract",
"and",
"self",
".",
"_write_type",
"==",
"other",
".",
"write_type",
"and",
"self",
".",
"_state",
"==",
"other",
".",
"state",
"and",
"self",
".",
"_destination",
"==",
"other",
".",
"dest",
"and",
"self",
".",
"_object_version",
"==",
"other",
".",
"version",
"and",
"self",
".",
"_object_key",
"==",
"other",
".",
"key",
"and",
"self",
".",
"_bucket",
"==",
"other",
".",
"bucket",
"except",
"Exception",
":",
"return",
"False",
"def",
"__ne__",
"(",
"self",
",",
"other",
")",
"->",
"bool",
":",
"return",
"not",
"(",
"self",
"==",
"other",
")",
"def",
"__str__",
"(",
"self",
")",
"->",
"str",
":",
"s",
":",
"str",
"=",
"''",
"s",
"+=",
"f'\\rBucket Name: {self._bucket}'",
"s",
"+=",
"f'\\rObject Key: {self._object_key}'",
"s",
"+=",
"f'\\rObject Version: {self._object_version}'",
"s",
"+=",
"f'\\rDestination: {self._destination}'",
"s",
"+=",
"'\\rState: {}'",
".",
"format",
"(",
"FetchingStates",
".",
"to_string",
"(",
"self",
".",
"_state",
")",
")",
"s",
"+=",
"f'\\rWrite type: {self._write_type}'",
"s",
"+=",
"f'\\rAuto Extract to: {self._auto_extract}'",
"s",
"+=",
"f'\\rIgnore Errors? {self._ignore_errors}'",
"s",
"+=",
"f'\\rCommand: {self._command}'",
"s",
"+=",
"f'\\rDuration: {self._duration}'",
"s",
"+=",
"'\\rHas File Contents In-Mem? {}'",
".",
"format",
"(",
"self",
".",
"_in_memory_file_contents",
"is",
"not",
"None",
")",
"return",
"s",
"def",
"__repr__",
"(",
"self",
")",
"->",
"str",
":",
"return",
"str",
"(",
"self",
")",
"def",
"__hash__",
"(",
"self",
")",
":",
"return",
"hash",
"(",
"(",
"self",
".",
"_bucket",
",",
"self",
".",
"_object_key",
",",
"self",
".",
"_object_version",
"if",
"self",
".",
"_object_version",
"is",
"not",
"None",
"else",
"'LATEST'",
")",
")"
] |
Maps the following fields:
_destination: The local destination.
|
[
"Maps",
"the",
"following",
"fields",
":",
"_destination",
":",
"The",
"local",
"destination",
"."
] |
[
"\"\"\"\r\n Maps the following fields:\r\n\r\n - _destination: The local destination. If None, the file will be downloaded in memory, in fetch_items dictionary\r\n - bucket_name: The source bucket name\r\n - object_key: The source object key\r\n - object_version: Optional. Object version\r\n - write_type: Optional, defaults to 'w'. Specifies the open type when writing to disk the downloaded file.\r\n - auto_extract: Optional. If the downloaded file is an archive, you put the path where to automatically extract the archive to.\r\n - ignore_errors: Optional. When set to true, calls try_get_object instead of get_object\r\n - command: Optional. A command to execute (BASH) while fetching item, in fact, when item has been downloaded, and if specified, before extraction\r\n - duration: ?\r\n \"\"\""
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 19
| 1,236
| 174
|
4ac3fd494a829487cba74ef04e8d4d9ebc783998
|
dzmitry-lahoda/NRegFreeCom
|
src/NRegFreeCom/Threading/StaComCrossThreadInvoker.cs
|
[
"CC0-1.0"
] |
C#
|
StaComCrossThreadInvoker
|
///<summary>
/// Rejected COM calls will retry automatically in current thread when instance of this object is used.
/// </summary>
///<example>
/// Clients of STA COM servers (Excel,Word,etc.) should use it before calling any methods from thread other then in which COM was created.
/// <code>
/// using (new StaComCrossThreadInvoker())
/// {
/// ...
/// }
/// </code>
/// </example>
///<remarks>
/// Provides <see cref="IMessageFilter"/> implementation with interface oriented on .NET CLIENTS to COM STA SERVERS only.
/// </remarks>
///<seealso href="http://blogs.msdn.com/b/andreww/archive/2008/11/19/implementing-imessagefilter-in-an-office-add-in.aspx"/>
/// <seealso href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms693740.aspx"/>
|
Rejected COM calls will retry automatically in current thread when instance of this object is used.
|
[
"Rejected",
"COM",
"calls",
"will",
"retry",
"automatically",
"in",
"current",
"thread",
"when",
"instance",
"of",
"this",
"object",
"is",
"used",
"."
] |
public class StaComCrossThreadInvoker : IMessageFilter, IDisposable
{
private IMessageFilter _oldFilter;
private bool _disposed;
private uint _maximumTotalWaitTimeInMilliseconds;
public const int DEFAULT_RETRY_TIMEOUT = 1;
public const int CANCEL = -1;
public const int S_OK = 0x0000;
public int AffinedThreadId { get; private set; }
public StaComCrossThreadInvoker()
: this(uint.MaxValue)
{
}
public StaComCrossThreadInvoker(uint maximumTotalWaitTimeInMilliseconds)
{
var t = Thread.CurrentThread;
if (t.GetApartmentState() != ApartmentState.STA) throw new InvalidOperationException("StaComCrossThreadInvoker can be used only from STA thread.");
AffinedThreadId = t.ManagedThreadId;
_maximumTotalWaitTimeInMilliseconds = maximumTotalWaitTimeInMilliseconds;
_oldFilter = null;
int hr = NativeMethods.CoRegisterMessageFilter(this, out _oldFilter);
if (hr != S_OK) throw new COMException("Failed to create message filter",hr);
}
public void Dispose()
{
if (!_disposed)
{
if (AffinedThreadId != Thread.CurrentThread.ManagedThreadId) throw new InvalidOperationException("Trying to dispose in other thread than object was created.");
IMessageFilter shouldBeCommonFilter = null;
int hr = NativeMethods.CoRegisterMessageFilter(_oldFilter, out shouldBeCommonFilter);
if (shouldBeCommonFilter != this) throw new InvalidOperationException("Trying to dispose unknown message filter. Other message filter was registered inside common filter without returning back common filter after usage.");
if (hr != S_OK) throw new COMException("Failed to dispose message filter", hr);
_disposed = true;
}
}
~StaComCrossThreadInvoker()
{
}
protected virtual bool ShouldRetry(uint elapsedTotalWaitTimeInMilliseconds)
{
return true;
}
int IMessageFilter.HandleInComingCall(uint dwCallType, IntPtr htaskCaller, uint dwTickCount, INTERFACEINFO[] lpInterfaceInfo)
{
return 1;
}
int IMessageFilter.RetryRejectedCall(IntPtr htaskCallee, uint dwTickCount, uint dwRejectType)
{
if (dwTickCount > _maximumTotalWaitTimeInMilliseconds)
{
return CANCEL;
}
if (ShouldRetry(dwTickCount))
{
return DEFAULT_RETRY_TIMEOUT;
}
return CANCEL;
}
int IMessageFilter.MessagePending(IntPtr htaskCallee, uint dwTickCount, uint dwPendingType)
{
return 1;
}
}
|
[
"public",
"class",
"StaComCrossThreadInvoker",
":",
"IMessageFilter",
",",
"IDisposable",
"{",
"private",
"IMessageFilter",
"_oldFilter",
";",
"private",
"bool",
"_disposed",
";",
"private",
"uint",
"_maximumTotalWaitTimeInMilliseconds",
";",
"public",
"const",
"int",
"DEFAULT_RETRY_TIMEOUT",
"=",
"1",
";",
"public",
"const",
"int",
"CANCEL",
"=",
"-",
"1",
";",
"public",
"const",
"int",
"S_OK",
"=",
"0x0000",
";",
"public",
"int",
"AffinedThreadId",
"{",
"get",
";",
"private",
"set",
";",
"}",
"public",
"StaComCrossThreadInvoker",
"(",
")",
":",
"this",
"(",
"uint",
".",
"MaxValue",
")",
"{",
"}",
"public",
"StaComCrossThreadInvoker",
"(",
"uint",
"maximumTotalWaitTimeInMilliseconds",
")",
"{",
"var",
"t",
"=",
"Thread",
".",
"CurrentThread",
";",
"if",
"(",
"t",
".",
"GetApartmentState",
"(",
")",
"!=",
"ApartmentState",
".",
"STA",
")",
"throw",
"new",
"InvalidOperationException",
"(",
"\"",
"StaComCrossThreadInvoker can be used only from STA thread.",
"\"",
")",
";",
"AffinedThreadId",
"=",
"t",
".",
"ManagedThreadId",
";",
"_maximumTotalWaitTimeInMilliseconds",
"=",
"maximumTotalWaitTimeInMilliseconds",
";",
"_oldFilter",
"=",
"null",
";",
"int",
"hr",
"=",
"NativeMethods",
".",
"CoRegisterMessageFilter",
"(",
"this",
",",
"out",
"_oldFilter",
")",
";",
"if",
"(",
"hr",
"!=",
"S_OK",
")",
"throw",
"new",
"COMException",
"(",
"\"",
"Failed to create message filter",
"\"",
",",
"hr",
")",
";",
"}",
"public",
"void",
"Dispose",
"(",
")",
"{",
"if",
"(",
"!",
"_disposed",
")",
"{",
"if",
"(",
"AffinedThreadId",
"!=",
"Thread",
".",
"CurrentThread",
".",
"ManagedThreadId",
")",
"throw",
"new",
"InvalidOperationException",
"(",
"\"",
"Trying to dispose in other thread than object was created.",
"\"",
")",
";",
"IMessageFilter",
"shouldBeCommonFilter",
"=",
"null",
";",
"int",
"hr",
"=",
"NativeMethods",
".",
"CoRegisterMessageFilter",
"(",
"_oldFilter",
",",
"out",
"shouldBeCommonFilter",
")",
";",
"if",
"(",
"shouldBeCommonFilter",
"!=",
"this",
")",
"throw",
"new",
"InvalidOperationException",
"(",
"\"",
"Trying to dispose unknown message filter. Other message filter was registered inside common filter without returning back common filter after usage.",
"\"",
")",
";",
"if",
"(",
"hr",
"!=",
"S_OK",
")",
"throw",
"new",
"COMException",
"(",
"\"",
"Failed to dispose message filter",
"\"",
",",
"hr",
")",
";",
"_disposed",
"=",
"true",
";",
"}",
"}",
"~",
"StaComCrossThreadInvoker",
"(",
")",
"{",
"}",
"protected",
"virtual",
"bool",
"ShouldRetry",
"(",
"uint",
"elapsedTotalWaitTimeInMilliseconds",
")",
"{",
"return",
"true",
";",
"}",
"int",
"IMessageFilter",
".",
"HandleInComingCall",
"(",
"uint",
"dwCallType",
",",
"IntPtr",
"htaskCaller",
",",
"uint",
"dwTickCount",
",",
"INTERFACEINFO",
"[",
"]",
"lpInterfaceInfo",
")",
"{",
"return",
"1",
";",
"}",
"int",
"IMessageFilter",
".",
"RetryRejectedCall",
"(",
"IntPtr",
"htaskCallee",
",",
"uint",
"dwTickCount",
",",
"uint",
"dwRejectType",
")",
"{",
"if",
"(",
"dwTickCount",
">",
"_maximumTotalWaitTimeInMilliseconds",
")",
"{",
"return",
"CANCEL",
";",
"}",
"if",
"(",
"ShouldRetry",
"(",
"dwTickCount",
")",
")",
"{",
"return",
"DEFAULT_RETRY_TIMEOUT",
";",
"}",
"return",
"CANCEL",
";",
"}",
"int",
"IMessageFilter",
".",
"MessagePending",
"(",
"IntPtr",
"htaskCallee",
",",
"uint",
"dwTickCount",
",",
"uint",
"dwPendingType",
")",
"{",
"return",
"1",
";",
"}",
"}"
] |
Rejected COM calls will retry automatically in current thread when instance of this object is used.
|
[
"Rejected",
"COM",
"calls",
"will",
"retry",
"automatically",
"in",
"current",
"thread",
"when",
"instance",
"of",
"this",
"object",
"is",
"used",
"."
] |
[
"/// <summary>",
"/// <see cref=\"Thread.ManagedThreadId\"/> were this object was created, can be used and should be disposed.",
"/// </summary>",
"/// <summary>",
"/// Creates and registers this filter.",
"/// </summary>",
"/// <summary>",
"/// Creates and registers this filter.",
"/// </summary>",
"/// <param name=\"maximumTotalWaitTimeInMilliseconds\">",
"/// Number of milliseconds before message filter stops spin waiting call to finish, call canceled and COM exceptions popup.",
"/// </param>",
"/// <summary>",
"/// Unregisters common filter and returns back previous one.",
"/// </summary>",
"// do nothing - cannot dispose in finalizer thread because of creation thread affinity",
"/// <summary>",
"/// Override to provide custom logic when retry happens. Can be used to show some notification to user.",
"/// </summary>",
"/// <param name=\"elpasedTotalWaitTimeInMilliseconds\">Total time user already waited call to finish in milliseconds</param>",
"/// <returns></returns>"
] |
[
{
"param": "IMessageFilter",
"type": null
},
{
"param": "IDisposable",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "IMessageFilter",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "IDisposable",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": [
{
"identifier": "example",
"docstring": "Clients of STA COM servers (Excel,Word,etc.) should use it before calling any methods from thread other then in which COM was created.\n\nusing (new StaComCrossThreadInvoker())\n{\n\n}",
"docstring_tokens": [
"Clients",
"of",
"STA",
"COM",
"servers",
"(",
"Excel",
"Word",
"etc",
".",
")",
"should",
"use",
"it",
"before",
"calling",
"any",
"methods",
"from",
"thread",
"other",
"then",
"in",
"which",
"COM",
"was",
"created",
".",
"using",
"(",
"new",
"StaComCrossThreadInvoker",
"()",
")",
"{",
"}"
]
},
{
"identifier": "remarks",
"docstring": null,
"docstring_tokens": [
"None"
]
},
{
"identifier": "seealso",
"docstring": null,
"docstring_tokens": [
"None"
]
},
{
"identifier": "seealso",
"docstring": null,
"docstring_tokens": [
"None"
]
}
]
}
| false
| 13
| 560
| 188
|
72eee8633006f9015c288b41399ae29de85ee59f
|
weicao/galaxysql
|
polardbx-executor/src/main/java/com/alibaba/polardbx/executor/balancer/splitpartition/IndexBasedSplitter.java
|
[
"Apache-2.0"
] |
Java
|
IndexBasedSplitter
|
/**
* IndexBasedSplitter
* <p>
* The basic idea of this splitter is employ the index to split partition-space.
* For example, to `partition by range(id)`, just scan the `id` index to split
* the partition space into pieces.
* <p>
* But to hash partition or functional partition, the index could not help, since
* the index is still `btree(id)` even if partition is `hash(year(id))`.
* <p>
* As a workaround, the splitter scan the sharding-key index with a bit more data,
* , and sample the result to estimate split-point.
*
* @author moyi
* @since 2021/04
*/
|
IndexBasedSplitter
The basic idea of this splitter is employ the index to split partition-space.
For example, to `partition by range(id)`, just scan the `id` index to split
the partition space into pieces.
But to hash partition or functional partition, the index could not help, since
the index is still `btree(id)` even if partition is `hash(year(id))`.
As a workaround, the splitter scan the sharding-key index with a bit more data,
, and sample the result to estimate split-point.
|
[
"IndexBasedSplitter",
"The",
"basic",
"idea",
"of",
"this",
"splitter",
"is",
"employ",
"the",
"index",
"to",
"split",
"partition",
"-",
"space",
".",
"For",
"example",
"to",
"`",
"partition",
"by",
"range",
"(",
"id",
")",
"`",
"just",
"scan",
"the",
"`",
"id",
"`",
"index",
"to",
"split",
"the",
"partition",
"space",
"into",
"pieces",
".",
"But",
"to",
"hash",
"partition",
"or",
"functional",
"partition",
"the",
"index",
"could",
"not",
"help",
"since",
"the",
"index",
"is",
"still",
"`",
"btree",
"(",
"id",
")",
"`",
"even",
"if",
"partition",
"is",
"`",
"hash",
"(",
"year",
"(",
"id",
"))",
"`",
".",
"As",
"a",
"workaround",
"the",
"splitter",
"scan",
"the",
"sharding",
"-",
"key",
"index",
"with",
"a",
"bit",
"more",
"data",
"and",
"sample",
"the",
"result",
"to",
"estimate",
"split",
"-",
"point",
"."
] |
public class IndexBasedSplitter implements SplitPointBuilder {
private static final Logger LOG = LoggerFactory.getLogger(IndexBasedSplitter.class);
/**
* Batch-size of index scan
*/
private static final long SCAN_BATCH_SIZE = 16;
private final ExecutionContext ec;
public IndexBasedSplitter(ExecutionContext ec) {
this.ec = ec;
}
/**
* Split partition-group:
* 1. estimate rows based on all partitions
* 2. build query key based on the first partition
*/
@Override
public List<SplitPoint> buildSplitPoint(PartitionGroupStat pg, BalanceOptions options) {
assert options.maxPartitionSize > 0;
if (pg.getTotalDiskSize() < options.maxPartitionSize) {
return Collections.emptyList();
}
PartitionStat firstPartition = pg.getFirstPartition();
long splitRowsEachPartition = estimateSplitRows(pg, options);
return buildSplitPoint(firstPartition, options, splitRowsEachPartition);
}
private List<SplitPoint> buildSplitPoint(PartitionStat partition,
BalanceOptions options,
long expectedRowsOfPartition) {
List<SplitPoint> splitPoints = new ArrayList<>();
SplitNameBuilder snb = new SplitNameBuilder(partition.getPartitionName());
for (long offset = expectedRowsOfPartition;
offset < partition.getPartitionRows();
offset += expectedRowsOfPartition) {
List<SearchDatumInfo> userKeys = queryActualPartitionKey(partition, SCAN_BATCH_SIZE, offset);
LOG.debug(String.format("real partition-key for partition %s at offset %d: %s",
partition.getPartitionName(), offset, userKeys));
if (userKeys == null) {
continue;
}
for (SearchDatumInfo userKey : userKeys) {
SearchDatumInfo splitKey = SplitPointUtils.generateSplitBound(partition.getPartitionBy(), userKey);
SplitPoint sp = snb.build(splitKey);
splitPoints.add(sp);
}
}
if (splitPoints.isEmpty()) {
return splitPoints;
}
// sort and duplicate partition-keys
List<SplitPoint> sorted = SplitPointUtils.sortAndDuplicate(partition, splitPoints);
List<SplitPoint> sample =
SplitPointUtils.sample(partition.getPartitionName(), sorted, BalanceOptions.SPLIT_PARTITION_MAX_COUNT);
LOG.info(String.format("build split-point for partition %s: %s", partition.getPartitionName(), sample));
return sample;
}
/**
* Query the data-node to retrieve the actual partition key of partition at specified offset
*/
private List<SearchDatumInfo> queryActualPartitionKey(PartitionStat partition, long limit, long offset) {
TableGroupRecord tg = partition.getTableGroupRecord();
List<String> shardingKeys = partition.getPartitionBy().getPartitionColumnNameList();
String physicalDb = partition.getPartitionGroupRecord().phy_db;
String physicalTable = partition.getLocation().getPhyTableName();
String sql = generateQueryPartitionKeySQL(shardingKeys, physicalDb, physicalTable, limit, offset);
List<DataType> dataTypes = partition.getPartitionBy().getPartitionColumnTypeList();
List<SearchDatumInfo> rows = StatsUtils.queryGroupTyped(tg.schema, physicalDb, dataTypes, sql);
if (rows.size() == 0) {
return null;
} else if (rows.size() > limit) {
throw new TddlRuntimeException(ErrorCode.ERR_PARTITION_MANAGEMENT, "too many rows");
}
return rows;
}
/**
* Build a SQL to query partition key at specified offset of partition-space.
* FIXME(moyi) split hash-value space, instead of origin value space
* <p>
* The expected order is like this:
* RANGE(id): order by id
* RANGE(year(id)): order by year(id)
* HASH(id): order by hash(id)
* HASH(year(id)): order by hash(year(id))
* <p>
* But actually, there's no index like year(id), hash(id), so we could not use this order.
*/
private String generateQueryPartitionKeySQL(List<String> shardingKeys,
String physicalDb,
String physicalTable,
long limit,
long offset) {
String columnStr = StringUtils.join(shardingKeys, ", ");
return String.format("select %s from %s.%s order by %s limit %d offset %d",
columnStr, physicalDb, physicalTable, columnStr, limit, offset);
}
}
|
[
"public",
"class",
"IndexBasedSplitter",
"implements",
"SplitPointBuilder",
"{",
"private",
"static",
"final",
"Logger",
"LOG",
"=",
"LoggerFactory",
".",
"getLogger",
"(",
"IndexBasedSplitter",
".",
"class",
")",
";",
"/**\n * Batch-size of index scan\n */",
"private",
"static",
"final",
"long",
"SCAN_BATCH_SIZE",
"=",
"16",
";",
"private",
"final",
"ExecutionContext",
"ec",
";",
"public",
"IndexBasedSplitter",
"(",
"ExecutionContext",
"ec",
")",
"{",
"this",
".",
"ec",
"=",
"ec",
";",
"}",
"/**\n * Split partition-group:\n * 1. estimate rows based on all partitions\n * 2. build query key based on the first partition\n */",
"@",
"Override",
"public",
"List",
"<",
"SplitPoint",
">",
"buildSplitPoint",
"(",
"PartitionGroupStat",
"pg",
",",
"BalanceOptions",
"options",
")",
"{",
"assert",
"options",
".",
"maxPartitionSize",
">",
"0",
";",
"if",
"(",
"pg",
".",
"getTotalDiskSize",
"(",
")",
"<",
"options",
".",
"maxPartitionSize",
")",
"{",
"return",
"Collections",
".",
"emptyList",
"(",
")",
";",
"}",
"PartitionStat",
"firstPartition",
"=",
"pg",
".",
"getFirstPartition",
"(",
")",
";",
"long",
"splitRowsEachPartition",
"=",
"estimateSplitRows",
"(",
"pg",
",",
"options",
")",
";",
"return",
"buildSplitPoint",
"(",
"firstPartition",
",",
"options",
",",
"splitRowsEachPartition",
")",
";",
"}",
"private",
"List",
"<",
"SplitPoint",
">",
"buildSplitPoint",
"(",
"PartitionStat",
"partition",
",",
"BalanceOptions",
"options",
",",
"long",
"expectedRowsOfPartition",
")",
"{",
"List",
"<",
"SplitPoint",
">",
"splitPoints",
"=",
"new",
"ArrayList",
"<",
">",
"(",
")",
";",
"SplitNameBuilder",
"snb",
"=",
"new",
"SplitNameBuilder",
"(",
"partition",
".",
"getPartitionName",
"(",
")",
")",
";",
"for",
"(",
"long",
"offset",
"=",
"expectedRowsOfPartition",
";",
"offset",
"<",
"partition",
".",
"getPartitionRows",
"(",
")",
";",
"offset",
"+=",
"expectedRowsOfPartition",
")",
"{",
"List",
"<",
"SearchDatumInfo",
">",
"userKeys",
"=",
"queryActualPartitionKey",
"(",
"partition",
",",
"SCAN_BATCH_SIZE",
",",
"offset",
")",
";",
"LOG",
".",
"debug",
"(",
"String",
".",
"format",
"(",
"\"",
"real partition-key for partition %s at offset %d: %s",
"\"",
",",
"partition",
".",
"getPartitionName",
"(",
")",
",",
"offset",
",",
"userKeys",
")",
")",
";",
"if",
"(",
"userKeys",
"==",
"null",
")",
"{",
"continue",
";",
"}",
"for",
"(",
"SearchDatumInfo",
"userKey",
":",
"userKeys",
")",
"{",
"SearchDatumInfo",
"splitKey",
"=",
"SplitPointUtils",
".",
"generateSplitBound",
"(",
"partition",
".",
"getPartitionBy",
"(",
")",
",",
"userKey",
")",
";",
"SplitPoint",
"sp",
"=",
"snb",
".",
"build",
"(",
"splitKey",
")",
";",
"splitPoints",
".",
"add",
"(",
"sp",
")",
";",
"}",
"}",
"if",
"(",
"splitPoints",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
"splitPoints",
";",
"}",
"List",
"<",
"SplitPoint",
">",
"sorted",
"=",
"SplitPointUtils",
".",
"sortAndDuplicate",
"(",
"partition",
",",
"splitPoints",
")",
";",
"List",
"<",
"SplitPoint",
">",
"sample",
"=",
"SplitPointUtils",
".",
"sample",
"(",
"partition",
".",
"getPartitionName",
"(",
")",
",",
"sorted",
",",
"BalanceOptions",
".",
"SPLIT_PARTITION_MAX_COUNT",
")",
";",
"LOG",
".",
"info",
"(",
"String",
".",
"format",
"(",
"\"",
"build split-point for partition %s: %s",
"\"",
",",
"partition",
".",
"getPartitionName",
"(",
")",
",",
"sample",
")",
")",
";",
"return",
"sample",
";",
"}",
"/**\n * Query the data-node to retrieve the actual partition key of partition at specified offset\n */",
"private",
"List",
"<",
"SearchDatumInfo",
">",
"queryActualPartitionKey",
"(",
"PartitionStat",
"partition",
",",
"long",
"limit",
",",
"long",
"offset",
")",
"{",
"TableGroupRecord",
"tg",
"=",
"partition",
".",
"getTableGroupRecord",
"(",
")",
";",
"List",
"<",
"String",
">",
"shardingKeys",
"=",
"partition",
".",
"getPartitionBy",
"(",
")",
".",
"getPartitionColumnNameList",
"(",
")",
";",
"String",
"physicalDb",
"=",
"partition",
".",
"getPartitionGroupRecord",
"(",
")",
".",
"phy_db",
";",
"String",
"physicalTable",
"=",
"partition",
".",
"getLocation",
"(",
")",
".",
"getPhyTableName",
"(",
")",
";",
"String",
"sql",
"=",
"generateQueryPartitionKeySQL",
"(",
"shardingKeys",
",",
"physicalDb",
",",
"physicalTable",
",",
"limit",
",",
"offset",
")",
";",
"List",
"<",
"DataType",
">",
"dataTypes",
"=",
"partition",
".",
"getPartitionBy",
"(",
")",
".",
"getPartitionColumnTypeList",
"(",
")",
";",
"List",
"<",
"SearchDatumInfo",
">",
"rows",
"=",
"StatsUtils",
".",
"queryGroupTyped",
"(",
"tg",
".",
"schema",
",",
"physicalDb",
",",
"dataTypes",
",",
"sql",
")",
";",
"if",
"(",
"rows",
".",
"size",
"(",
")",
"==",
"0",
")",
"{",
"return",
"null",
";",
"}",
"else",
"if",
"(",
"rows",
".",
"size",
"(",
")",
">",
"limit",
")",
"{",
"throw",
"new",
"TddlRuntimeException",
"(",
"ErrorCode",
".",
"ERR_PARTITION_MANAGEMENT",
",",
"\"",
"too many rows",
"\"",
")",
";",
"}",
"return",
"rows",
";",
"}",
"/**\n * Build a SQL to query partition key at specified offset of partition-space.\n * FIXME(moyi) split hash-value space, instead of origin value space\n * <p>\n * The expected order is like this:\n * RANGE(id): order by id\n * RANGE(year(id)): order by year(id)\n * HASH(id): order by hash(id)\n * HASH(year(id)): order by hash(year(id))\n * <p>\n * But actually, there's no index like year(id), hash(id), so we could not use this order.\n */",
"private",
"String",
"generateQueryPartitionKeySQL",
"(",
"List",
"<",
"String",
">",
"shardingKeys",
",",
"String",
"physicalDb",
",",
"String",
"physicalTable",
",",
"long",
"limit",
",",
"long",
"offset",
")",
"{",
"String",
"columnStr",
"=",
"StringUtils",
".",
"join",
"(",
"shardingKeys",
",",
"\"",
", ",
"\"",
")",
";",
"return",
"String",
".",
"format",
"(",
"\"",
"select %s from %s.%s order by %s limit %d offset %d",
"\"",
",",
"columnStr",
",",
"physicalDb",
",",
"physicalTable",
",",
"columnStr",
",",
"limit",
",",
"offset",
")",
";",
"}",
"}"
] |
IndexBasedSplitter
<p>
The basic idea of this splitter is employ the index to split partition-space.
|
[
"IndexBasedSplitter",
"<p",
">",
"The",
"basic",
"idea",
"of",
"this",
"splitter",
"is",
"employ",
"the",
"index",
"to",
"split",
"partition",
"-",
"space",
"."
] |
[
"// sort and duplicate partition-keys"
] |
[
{
"param": "SplitPointBuilder",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "SplitPointBuilder",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 15
| 961
| 151
|
145e129650195b9a81dc2c826003e04323c02cec
|
elmendavies/ldaptive
|
core/src/main/java/org/ldaptive/ModifyRequest.java
|
[
"Apache-2.0"
] |
Java
|
ModifyRequest
|
/**
* LDAP modify request defined as:
*
* <pre>
ModifyRequest ::= [APPLICATION 6] SEQUENCE {
object LDAPDN,
changes SEQUENCE OF change SEQUENCE {
operation ENUMERATED {
add (0),
delete (1),
replace (2),
... },
modification PartialAttribute } }
PartialAttribute ::= SEQUENCE {
type AttributeDescription,
vals SET OF value AttributeValue }
Attribute ::= PartialAttribute(WITH COMPONENTS {
...,
vals (SIZE(1..MAX))})
* </pre>
*
* @author Middleware Services
*/
|
LDAP modify request defined as:
ModifyRequest ::= [APPLICATION 6] SEQUENCE {
object LDAPDN,
changes SEQUENCE OF change SEQUENCE {
operation ENUMERATED {
add (0),
delete (1),
replace (2),
},
modification PartialAttribute } }
PartialAttribute ::= SEQUENCE {
type AttributeDescription,
vals SET OF value AttributeValue }
@author Middleware Services
|
[
"LDAP",
"modify",
"request",
"defined",
"as",
":",
"ModifyRequest",
"::",
"=",
"[",
"APPLICATION",
"6",
"]",
"SEQUENCE",
"{",
"object",
"LDAPDN",
"changes",
"SEQUENCE",
"OF",
"change",
"SEQUENCE",
"{",
"operation",
"ENUMERATED",
"{",
"add",
"(",
"0",
")",
"delete",
"(",
"1",
")",
"replace",
"(",
"2",
")",
"}",
"modification",
"PartialAttribute",
"}",
"}",
"PartialAttribute",
"::",
"=",
"SEQUENCE",
"{",
"type",
"AttributeDescription",
"vals",
"SET",
"OF",
"value",
"AttributeValue",
"}",
"@author",
"Middleware",
"Services"
] |
public class ModifyRequest extends AbstractRequestMessage
{
/** BER protocol number. */
public static final int PROTOCOL_OP = 6;
/** Empty byte. */
private static final byte[] EMPTY_BYTE = new byte[0];
/** LDAP DN to modify. */
private String ldapDn;
/** Modifications to perform. */
private AttributeModification[] modifications;
/**
* Default constructor.
*/
private ModifyRequest() {}
/**
* Creates a new modify request.
*
* @param entry DN to modify
* @param mod to make on the object
*/
public ModifyRequest(final String entry, final AttributeModification... mod)
{
ldapDn = entry;
modifications = mod;
}
/**
* Returns the DN.
*
* @return DN
*/
public String getDn()
{
return ldapDn;
}
/**
* Returns the attribute modifications.
*
* @return attributes modifications
*/
public AttributeModification[] getModifications()
{
return modifications;
}
@Override
protected DEREncoder[] getRequestEncoders(final int id)
{
return new DEREncoder[] {
new IntegerType(id),
new ConstructedDEREncoder(
new ApplicationDERTag(PROTOCOL_OP, true),
new OctetStringType(ldapDn),
new ConstructedDEREncoder(
UniversalDERTag.SEQ,
Stream.of(modifications).map(m ->
new ConstructedDEREncoder(
UniversalDERTag.SEQ,
new IntegerType(UniversalDERTag.ENUM, m.getOperation().ordinal()),
new ConstructedDEREncoder(
UniversalDERTag.SEQ,
new OctetStringType(m.getAttribute().getName()),
new ConstructedDEREncoder(
UniversalDERTag.SET,
getAttributeValueEncoders(m.getAttribute().getBinaryValues())))))
.toArray(DEREncoder[]::new))),
};
}
/**
* Returns attribute value encoders for the supplied values.
*
* @param values to create encoders for
*
* @return attribute value encoders
*/
private DEREncoder[] getAttributeValueEncoders(final Collection<byte[]> values)
{
if (values == null || values.size() == 0) {
return new DEREncoder[] {() -> EMPTY_BYTE};
}
return values.stream().map(OctetStringType::new).toArray(DEREncoder[]::new);
}
@Override
public String toString()
{
return new StringBuilder(super.toString()).append(", ")
.append("dn=").append(ldapDn).append(", ")
.append("modifications=").append(Arrays.toString(modifications)).toString();
}
/**
* Creates a builder for this class.
*
* @return new builder
*/
public static Builder builder()
{
return new Builder();
}
/** Modify request builder. */
public static class Builder extends AbstractRequestMessage.AbstractBuilder<ModifyRequest.Builder, ModifyRequest>
{
/**
* Default constructor.
*/
protected Builder()
{
super(new ModifyRequest());
}
@Override
protected Builder self()
{
return this;
}
/**
* Sets the ldap DN.
*
* @param dn ldap DN
*
* @return this builder
*/
public Builder dn(final String dn)
{
object.ldapDn = dn;
return self();
}
/**
* Sets the modifications.
*
* @param mod modifications
*
* @return this builder
*/
public Builder modificiations(final AttributeModification... mod)
{
object.modifications = mod;
return self();
}
/**
* Sets the modifications.
*
* @param mod modifications
*
* @return this builder
*/
public Builder modificiations(final Collection<AttributeModification> mod)
{
object.modifications = mod.toArray(AttributeModification[]::new);
return self();
}
}
}
|
[
"public",
"class",
"ModifyRequest",
"extends",
"AbstractRequestMessage",
"{",
"/** BER protocol number. */",
"public",
"static",
"final",
"int",
"PROTOCOL_OP",
"=",
"6",
";",
"/** Empty byte. */",
"private",
"static",
"final",
"byte",
"[",
"]",
"EMPTY_BYTE",
"=",
"new",
"byte",
"[",
"0",
"]",
";",
"/** LDAP DN to modify. */",
"private",
"String",
"ldapDn",
";",
"/** Modifications to perform. */",
"private",
"AttributeModification",
"[",
"]",
"modifications",
";",
"/**\n * Default constructor.\n */",
"private",
"ModifyRequest",
"(",
")",
"{",
"}",
"/**\n * Creates a new modify request.\n *\n * @param entry DN to modify\n * @param mod to make on the object\n */",
"public",
"ModifyRequest",
"(",
"final",
"String",
"entry",
",",
"final",
"AttributeModification",
"...",
"mod",
")",
"{",
"ldapDn",
"=",
"entry",
";",
"modifications",
"=",
"mod",
";",
"}",
"/**\n * Returns the DN.\n *\n * @return DN\n */",
"public",
"String",
"getDn",
"(",
")",
"{",
"return",
"ldapDn",
";",
"}",
"/**\n * Returns the attribute modifications.\n *\n * @return attributes modifications\n */",
"public",
"AttributeModification",
"[",
"]",
"getModifications",
"(",
")",
"{",
"return",
"modifications",
";",
"}",
"@",
"Override",
"protected",
"DEREncoder",
"[",
"]",
"getRequestEncoders",
"(",
"final",
"int",
"id",
")",
"{",
"return",
"new",
"DEREncoder",
"[",
"]",
"{",
"new",
"IntegerType",
"(",
"id",
")",
",",
"new",
"ConstructedDEREncoder",
"(",
"new",
"ApplicationDERTag",
"(",
"PROTOCOL_OP",
",",
"true",
")",
",",
"new",
"OctetStringType",
"(",
"ldapDn",
")",
",",
"new",
"ConstructedDEREncoder",
"(",
"UniversalDERTag",
".",
"SEQ",
",",
"Stream",
".",
"of",
"(",
"modifications",
")",
".",
"map",
"(",
"m",
"->",
"new",
"ConstructedDEREncoder",
"(",
"UniversalDERTag",
".",
"SEQ",
",",
"new",
"IntegerType",
"(",
"UniversalDERTag",
".",
"ENUM",
",",
"m",
".",
"getOperation",
"(",
")",
".",
"ordinal",
"(",
")",
")",
",",
"new",
"ConstructedDEREncoder",
"(",
"UniversalDERTag",
".",
"SEQ",
",",
"new",
"OctetStringType",
"(",
"m",
".",
"getAttribute",
"(",
")",
".",
"getName",
"(",
")",
")",
",",
"new",
"ConstructedDEREncoder",
"(",
"UniversalDERTag",
".",
"SET",
",",
"getAttributeValueEncoders",
"(",
"m",
".",
"getAttribute",
"(",
")",
".",
"getBinaryValues",
"(",
")",
")",
")",
")",
")",
")",
".",
"toArray",
"(",
"DEREncoder",
"[",
"]",
"::",
"new",
")",
")",
")",
",",
"}",
";",
"}",
"/**\n * Returns attribute value encoders for the supplied values.\n *\n * @param values to create encoders for\n *\n * @return attribute value encoders\n */",
"private",
"DEREncoder",
"[",
"]",
"getAttributeValueEncoders",
"(",
"final",
"Collection",
"<",
"byte",
"[",
"]",
">",
"values",
")",
"{",
"if",
"(",
"values",
"==",
"null",
"||",
"values",
".",
"size",
"(",
")",
"==",
"0",
")",
"{",
"return",
"new",
"DEREncoder",
"[",
"]",
"{",
"(",
")",
"->",
"EMPTY_BYTE",
"}",
";",
"}",
"return",
"values",
".",
"stream",
"(",
")",
".",
"map",
"(",
"OctetStringType",
"::",
"new",
")",
".",
"toArray",
"(",
"DEREncoder",
"[",
"]",
"::",
"new",
")",
";",
"}",
"@",
"Override",
"public",
"String",
"toString",
"(",
")",
"{",
"return",
"new",
"StringBuilder",
"(",
"super",
".",
"toString",
"(",
")",
")",
".",
"append",
"(",
"\"",
", ",
"\"",
")",
".",
"append",
"(",
"\"",
"dn=",
"\"",
")",
".",
"append",
"(",
"ldapDn",
")",
".",
"append",
"(",
"\"",
", ",
"\"",
")",
".",
"append",
"(",
"\"",
"modifications=",
"\"",
")",
".",
"append",
"(",
"Arrays",
".",
"toString",
"(",
"modifications",
")",
")",
".",
"toString",
"(",
")",
";",
"}",
"/**\n * Creates a builder for this class.\n *\n * @return new builder\n */",
"public",
"static",
"Builder",
"builder",
"(",
")",
"{",
"return",
"new",
"Builder",
"(",
")",
";",
"}",
"/** Modify request builder. */",
"public",
"static",
"class",
"Builder",
"extends",
"AbstractRequestMessage",
".",
"AbstractBuilder",
"<",
"ModifyRequest",
".",
"Builder",
",",
"ModifyRequest",
">",
"{",
"/**\n * Default constructor.\n */",
"protected",
"Builder",
"(",
")",
"{",
"super",
"(",
"new",
"ModifyRequest",
"(",
")",
")",
";",
"}",
"@",
"Override",
"protected",
"Builder",
"self",
"(",
")",
"{",
"return",
"this",
";",
"}",
"/**\n * Sets the ldap DN.\n *\n * @param dn ldap DN\n *\n * @return this builder\n */",
"public",
"Builder",
"dn",
"(",
"final",
"String",
"dn",
")",
"{",
"object",
".",
"ldapDn",
"=",
"dn",
";",
"return",
"self",
"(",
")",
";",
"}",
"/**\n * Sets the modifications.\n *\n * @param mod modifications\n *\n * @return this builder\n */",
"public",
"Builder",
"modificiations",
"(",
"final",
"AttributeModification",
"...",
"mod",
")",
"{",
"object",
".",
"modifications",
"=",
"mod",
";",
"return",
"self",
"(",
")",
";",
"}",
"/**\n * Sets the modifications.\n *\n * @param mod modifications\n *\n * @return this builder\n */",
"public",
"Builder",
"modificiations",
"(",
"final",
"Collection",
"<",
"AttributeModification",
">",
"mod",
")",
"{",
"object",
".",
"modifications",
"=",
"mod",
".",
"toArray",
"(",
"AttributeModification",
"[",
"]",
"::",
"new",
")",
";",
"return",
"self",
"(",
")",
";",
"}",
"}",
"}"
] |
LDAP modify request defined as:
<pre>
ModifyRequest ::= [APPLICATION 6] SEQUENCE {
object LDAPDN,
changes SEQUENCE OF change SEQUENCE {
operation ENUMERATED {
add (0),
delete (1),
replace (2),
... },
modification PartialAttribute } }
|
[
"LDAP",
"modify",
"request",
"defined",
"as",
":",
"<pre",
">",
"ModifyRequest",
"::",
"=",
"[",
"APPLICATION",
"6",
"]",
"SEQUENCE",
"{",
"object",
"LDAPDN",
"changes",
"SEQUENCE",
"OF",
"change",
"SEQUENCE",
"{",
"operation",
"ENUMERATED",
"{",
"add",
"(",
"0",
")",
"delete",
"(",
"1",
")",
"replace",
"(",
"2",
")",
"...",
"}",
"modification",
"PartialAttribute",
"}",
"}"
] |
[] |
[
{
"param": "AbstractRequestMessage",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "AbstractRequestMessage",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 27
| 875
| 134
|
ee8f963cf048665839ebec8cd8eb4439d7337b2b
|
shubham1436/Gerrit
|
gerrit-server/src/main/java/com/google/gerrit/server/plugins/AbstractPreloadedPluginScanner.java
|
[
"Apache-2.0"
] |
Java
|
AbstractPreloadedPluginScanner
|
/**
* Base plugin scanner for a set of pre-loaded classes.
*
* Utility base class for simplifying the development of Server plugin scanner
* based on a set of externally pre-loaded classes.
*
* Extending this class you can implement very easily a PluginContentScanner
* from a set of pre-loaded Java Classes and an API Type.
* The convention used by this class is:
* - there is at most one Guice module per Gerrit module type (SysModule, HttpModule, SshModule)
* - plugin is set to be restartable in Gerrit Plugin MANIFEST
* - only Export and Listen annotated classes can be self-discovered
*/
|
Base plugin scanner for a set of pre-loaded classes.
Utility base class for simplifying the development of Server plugin scanner
based on a set of externally pre-loaded classes.
Extending this class you can implement very easily a PluginContentScanner
from a set of pre-loaded Java Classes and an API Type.
The convention used by this class is:
- there is at most one Guice module per Gerrit module type (SysModule, HttpModule, SshModule)
- plugin is set to be restartable in Gerrit Plugin MANIFEST
- only Export and Listen annotated classes can be self-discovered
|
[
"Base",
"plugin",
"scanner",
"for",
"a",
"set",
"of",
"pre",
"-",
"loaded",
"classes",
".",
"Utility",
"base",
"class",
"for",
"simplifying",
"the",
"development",
"of",
"Server",
"plugin",
"scanner",
"based",
"on",
"a",
"set",
"of",
"externally",
"pre",
"-",
"loaded",
"classes",
".",
"Extending",
"this",
"class",
"you",
"can",
"implement",
"very",
"easily",
"a",
"PluginContentScanner",
"from",
"a",
"set",
"of",
"pre",
"-",
"loaded",
"Java",
"Classes",
"and",
"an",
"API",
"Type",
".",
"The",
"convention",
"used",
"by",
"this",
"class",
"is",
":",
"-",
"there",
"is",
"at",
"most",
"one",
"Guice",
"module",
"per",
"Gerrit",
"module",
"type",
"(",
"SysModule",
"HttpModule",
"SshModule",
")",
"-",
"plugin",
"is",
"set",
"to",
"be",
"restartable",
"in",
"Gerrit",
"Plugin",
"MANIFEST",
"-",
"only",
"Export",
"and",
"Listen",
"annotated",
"classes",
"can",
"be",
"self",
"-",
"discovered"
] |
public abstract class AbstractPreloadedPluginScanner implements
PluginContentScanner {
protected final String pluginName;
protected final String pluginVersion;
protected final Set<Class<?>> preloadedClasses;
protected final ApiType apiType;
private Class<?> sshModuleClass;
private Class<?> httpModuleClass;
private Class<?> sysModuleClass;
public AbstractPreloadedPluginScanner(String pluginName, String pluginVersion,
Set<Class<?>> preloadedClasses, Plugin.ApiType apiType) {
this.pluginName = pluginName;
this.pluginVersion = pluginVersion;
this.preloadedClasses = preloadedClasses;
this.apiType = apiType;
}
@Override
public Manifest getManifest() throws IOException {
scanGuiceModules(preloadedClasses);
StringBuilder manifestString =
new StringBuilder("PluginName: " + pluginName + "\n"
+ "Implementation-Version: " + pluginVersion + "\n"
+ "Gerrit-ReloadMode: restart\n"
+ "Gerrit-ApiType: " + apiType + "\n");
appendIfNotNull(manifestString, "Gerrit-SshModule: ", sshModuleClass);
appendIfNotNull(manifestString, "Gerrit-HttpModule: ", httpModuleClass);
appendIfNotNull(manifestString, "Gerrit-Module: ", sysModuleClass);
return new Manifest(new ByteArrayInputStream(manifestString.toString()
.getBytes()));
}
@Override
public Map<Class<? extends Annotation>, Iterable<ExtensionMetaData>> scan(
String pluginName, Iterable<Class<? extends Annotation>> annotations)
throws InvalidPluginException {
ImmutableMap.Builder<Class<? extends Annotation>, Iterable<ExtensionMetaData>> result =
ImmutableMap.builder();
for (Class<? extends Annotation> annotation : annotations) {
Set<ExtensionMetaData> classMetaDataSet = new HashSet<>();
result.put(annotation, classMetaDataSet);
for (Class<?> clazz : preloadedClasses) {
if (!Modifier.isAbstract(clazz.getModifiers())
&& clazz.getAnnotation(annotation) != null) {
classMetaDataSet.add(new ExtensionMetaData(clazz.getName(),
getExportAnnotationValue(clazz, annotation)));
}
}
}
return result.build();
}
private void appendIfNotNull(StringBuilder string, String header,
Class<?> guiceModuleClass) {
if (guiceModuleClass != null) {
string.append(header);
string.append(guiceModuleClass.getName());
string.append("\n");
}
}
private void scanGuiceModules(Set<Class<?>> classes) throws IOException {
try {
Class<?> sysModuleBaseClass = Module.class;
Class<?> httpModuleBaseClass =
Class.forName("com.google.inject.servlet.ServletModule");
Class<?> sshModuleBaseClass =
Class.forName("com.google.gerrit.sshd.CommandModule");
sshModuleClass = null;
httpModuleClass = null;
sysModuleClass = null;
for (Class<?> clazz : classes) {
if (clazz.isLocalClass()) {
continue;
}
if (sshModuleBaseClass.isAssignableFrom(clazz)) {
sshModuleClass =
getUniqueGuiceModule(sshModuleBaseClass, sshModuleClass, clazz);
} else if (httpModuleBaseClass.isAssignableFrom(clazz)) {
httpModuleClass =
getUniqueGuiceModule(httpModuleBaseClass, httpModuleClass, clazz);
} else if (sysModuleBaseClass.isAssignableFrom(clazz)) {
sysModuleClass =
getUniqueGuiceModule(sysModuleBaseClass, sysModuleClass, clazz);
}
}
} catch (ClassNotFoundException e) {
throw new IOException(
"Cannot find base Gerrit classes for Guice Plugin Modules", e);
}
}
private Class<?> getUniqueGuiceModule(Class<?> guiceModuleBaseClass,
Class<?> existingGuiceModuleName, Class<?> newGuiceModuleClass) {
checkState(existingGuiceModuleName == null,
"Multiple %s implementations: %s, %s", guiceModuleBaseClass,
existingGuiceModuleName, newGuiceModuleClass);
return newGuiceModuleClass;
}
private String getExportAnnotationValue(Class<?> scriptClass,
Class<? extends Annotation> annotation) {
return annotation == Export.class ? scriptClass.getAnnotation(Export.class)
.value() : "";
}
}
|
[
"public",
"abstract",
"class",
"AbstractPreloadedPluginScanner",
"implements",
"PluginContentScanner",
"{",
"protected",
"final",
"String",
"pluginName",
";",
"protected",
"final",
"String",
"pluginVersion",
";",
"protected",
"final",
"Set",
"<",
"Class",
"<",
"?",
">",
">",
"preloadedClasses",
";",
"protected",
"final",
"ApiType",
"apiType",
";",
"private",
"Class",
"<",
"?",
">",
"sshModuleClass",
";",
"private",
"Class",
"<",
"?",
">",
"httpModuleClass",
";",
"private",
"Class",
"<",
"?",
">",
"sysModuleClass",
";",
"public",
"AbstractPreloadedPluginScanner",
"(",
"String",
"pluginName",
",",
"String",
"pluginVersion",
",",
"Set",
"<",
"Class",
"<",
"?",
">",
">",
"preloadedClasses",
",",
"Plugin",
".",
"ApiType",
"apiType",
")",
"{",
"this",
".",
"pluginName",
"=",
"pluginName",
";",
"this",
".",
"pluginVersion",
"=",
"pluginVersion",
";",
"this",
".",
"preloadedClasses",
"=",
"preloadedClasses",
";",
"this",
".",
"apiType",
"=",
"apiType",
";",
"}",
"@",
"Override",
"public",
"Manifest",
"getManifest",
"(",
")",
"throws",
"IOException",
"{",
"scanGuiceModules",
"(",
"preloadedClasses",
")",
";",
"StringBuilder",
"manifestString",
"=",
"new",
"StringBuilder",
"(",
"\"",
"PluginName: ",
"\"",
"+",
"pluginName",
"+",
"\"",
"\\n",
"\"",
"+",
"\"",
"Implementation-Version: ",
"\"",
"+",
"pluginVersion",
"+",
"\"",
"\\n",
"\"",
"+",
"\"",
"Gerrit-ReloadMode: restart",
"\\n",
"\"",
"+",
"\"",
"Gerrit-ApiType: ",
"\"",
"+",
"apiType",
"+",
"\"",
"\\n",
"\"",
")",
";",
"appendIfNotNull",
"(",
"manifestString",
",",
"\"",
"Gerrit-SshModule: ",
"\"",
",",
"sshModuleClass",
")",
";",
"appendIfNotNull",
"(",
"manifestString",
",",
"\"",
"Gerrit-HttpModule: ",
"\"",
",",
"httpModuleClass",
")",
";",
"appendIfNotNull",
"(",
"manifestString",
",",
"\"",
"Gerrit-Module: ",
"\"",
",",
"sysModuleClass",
")",
";",
"return",
"new",
"Manifest",
"(",
"new",
"ByteArrayInputStream",
"(",
"manifestString",
".",
"toString",
"(",
")",
".",
"getBytes",
"(",
")",
")",
")",
";",
"}",
"@",
"Override",
"public",
"Map",
"<",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
",",
"Iterable",
"<",
"ExtensionMetaData",
">",
">",
"scan",
"(",
"String",
"pluginName",
",",
"Iterable",
"<",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
">",
"annotations",
")",
"throws",
"InvalidPluginException",
"{",
"ImmutableMap",
".",
"Builder",
"<",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
",",
"Iterable",
"<",
"ExtensionMetaData",
">",
">",
"result",
"=",
"ImmutableMap",
".",
"builder",
"(",
")",
";",
"for",
"(",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
"annotation",
":",
"annotations",
")",
"{",
"Set",
"<",
"ExtensionMetaData",
">",
"classMetaDataSet",
"=",
"new",
"HashSet",
"<",
">",
"(",
")",
";",
"result",
".",
"put",
"(",
"annotation",
",",
"classMetaDataSet",
")",
";",
"for",
"(",
"Class",
"<",
"?",
">",
"clazz",
":",
"preloadedClasses",
")",
"{",
"if",
"(",
"!",
"Modifier",
".",
"isAbstract",
"(",
"clazz",
".",
"getModifiers",
"(",
")",
")",
"&&",
"clazz",
".",
"getAnnotation",
"(",
"annotation",
")",
"!=",
"null",
")",
"{",
"classMetaDataSet",
".",
"add",
"(",
"new",
"ExtensionMetaData",
"(",
"clazz",
".",
"getName",
"(",
")",
",",
"getExportAnnotationValue",
"(",
"clazz",
",",
"annotation",
")",
")",
")",
";",
"}",
"}",
"}",
"return",
"result",
".",
"build",
"(",
")",
";",
"}",
"private",
"void",
"appendIfNotNull",
"(",
"StringBuilder",
"string",
",",
"String",
"header",
",",
"Class",
"<",
"?",
">",
"guiceModuleClass",
")",
"{",
"if",
"(",
"guiceModuleClass",
"!=",
"null",
")",
"{",
"string",
".",
"append",
"(",
"header",
")",
";",
"string",
".",
"append",
"(",
"guiceModuleClass",
".",
"getName",
"(",
")",
")",
";",
"string",
".",
"append",
"(",
"\"",
"\\n",
"\"",
")",
";",
"}",
"}",
"private",
"void",
"scanGuiceModules",
"(",
"Set",
"<",
"Class",
"<",
"?",
">",
">",
"classes",
")",
"throws",
"IOException",
"{",
"try",
"{",
"Class",
"<",
"?",
">",
"sysModuleBaseClass",
"=",
"Module",
".",
"class",
";",
"Class",
"<",
"?",
">",
"httpModuleBaseClass",
"=",
"Class",
".",
"forName",
"(",
"\"",
"com.google.inject.servlet.ServletModule",
"\"",
")",
";",
"Class",
"<",
"?",
">",
"sshModuleBaseClass",
"=",
"Class",
".",
"forName",
"(",
"\"",
"com.google.gerrit.sshd.CommandModule",
"\"",
")",
";",
"sshModuleClass",
"=",
"null",
";",
"httpModuleClass",
"=",
"null",
";",
"sysModuleClass",
"=",
"null",
";",
"for",
"(",
"Class",
"<",
"?",
">",
"clazz",
":",
"classes",
")",
"{",
"if",
"(",
"clazz",
".",
"isLocalClass",
"(",
")",
")",
"{",
"continue",
";",
"}",
"if",
"(",
"sshModuleBaseClass",
".",
"isAssignableFrom",
"(",
"clazz",
")",
")",
"{",
"sshModuleClass",
"=",
"getUniqueGuiceModule",
"(",
"sshModuleBaseClass",
",",
"sshModuleClass",
",",
"clazz",
")",
";",
"}",
"else",
"if",
"(",
"httpModuleBaseClass",
".",
"isAssignableFrom",
"(",
"clazz",
")",
")",
"{",
"httpModuleClass",
"=",
"getUniqueGuiceModule",
"(",
"httpModuleBaseClass",
",",
"httpModuleClass",
",",
"clazz",
")",
";",
"}",
"else",
"if",
"(",
"sysModuleBaseClass",
".",
"isAssignableFrom",
"(",
"clazz",
")",
")",
"{",
"sysModuleClass",
"=",
"getUniqueGuiceModule",
"(",
"sysModuleBaseClass",
",",
"sysModuleClass",
",",
"clazz",
")",
";",
"}",
"}",
"}",
"catch",
"(",
"ClassNotFoundException",
"e",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"",
"Cannot find base Gerrit classes for Guice Plugin Modules",
"\"",
",",
"e",
")",
";",
"}",
"}",
"private",
"Class",
"<",
"?",
">",
"getUniqueGuiceModule",
"(",
"Class",
"<",
"?",
">",
"guiceModuleBaseClass",
",",
"Class",
"<",
"?",
">",
"existingGuiceModuleName",
",",
"Class",
"<",
"?",
">",
"newGuiceModuleClass",
")",
"{",
"checkState",
"(",
"existingGuiceModuleName",
"==",
"null",
",",
"\"",
"Multiple %s implementations: %s, %s",
"\"",
",",
"guiceModuleBaseClass",
",",
"existingGuiceModuleName",
",",
"newGuiceModuleClass",
")",
";",
"return",
"newGuiceModuleClass",
";",
"}",
"private",
"String",
"getExportAnnotationValue",
"(",
"Class",
"<",
"?",
">",
"scriptClass",
",",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
"annotation",
")",
"{",
"return",
"annotation",
"==",
"Export",
".",
"class",
"?",
"scriptClass",
".",
"getAnnotation",
"(",
"Export",
".",
"class",
")",
".",
"value",
"(",
")",
":",
"\"",
"\"",
";",
"}",
"}"
] |
Base plugin scanner for a set of pre-loaded classes.
|
[
"Base",
"plugin",
"scanner",
"for",
"a",
"set",
"of",
"pre",
"-",
"loaded",
"classes",
"."
] |
[] |
[
{
"param": "PluginContentScanner",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "PluginContentScanner",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 19
| 911
| 135
|
ee3a642a1502e5bb18d25f2d3a45e8a5599a7fc8
|
xufeiclamc/redmine-3.3.2-2
|
apps/redmine/htdocs/app/models/issue_relation.rb
|
[
"Apache-2.0"
] |
Ruby
|
IssueRelation
|
# Redmine - project management software
# Copyright (C) 2006-2016 Jean-Philippe Lang
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
project management software
Copyright (C) 2006-2016 Jean-Philippe Lang
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
[
"project",
"management",
"software",
"Copyright",
"(",
"C",
")",
"2006",
"-",
"2016",
"Jean",
"-",
"Philippe",
"Lang",
"This",
"program",
"is",
"free",
"software",
";",
"you",
"can",
"redistribute",
"it",
"and",
"/",
"or",
"modify",
"it",
"under",
"the",
"terms",
"of",
"the",
"GNU",
"General",
"Public",
"License",
"as",
"published",
"by",
"the",
"Free",
"Software",
"Foundation",
";",
"either",
"version",
"2",
"of",
"the",
"License",
"or",
"(",
"at",
"your",
"option",
")",
"any",
"later",
"version",
".",
"This",
"program",
"is",
"distributed",
"in",
"the",
"hope",
"that",
"it",
"will",
"be",
"useful",
"but",
"WITHOUT",
"ANY",
"WARRANTY",
";",
"without",
"even",
"the",
"implied",
"warranty",
"of",
"MERCHANTABILITY",
"or",
"FITNESS",
"FOR",
"A",
"PARTICULAR",
"PURPOSE",
".",
"See",
"the",
"GNU",
"General",
"Public",
"License",
"for",
"more",
"details",
".",
"You",
"should",
"have",
"received",
"a",
"copy",
"of",
"the",
"GNU",
"General",
"Public",
"License",
"along",
"with",
"this",
"program",
";",
"if",
"not",
"write",
"to",
"the",
"Free",
"Software",
"Foundation",
"Inc",
".",
"51",
"Franklin",
"Street",
"Fifth",
"Floor",
"Boston",
"MA",
"02110",
"-",
"1301",
"USA",
"."
] |
class IssueRelation < ActiveRecord::Base
# Class used to represent the relations of an issue
class Relations < Array
include Redmine::I18n
def initialize(issue, *args)
@issue = issue
super(*args)
end
def to_s(*args)
map {|relation| relation.to_s(@issue)}.join(', ')
end
end
include Redmine::SafeAttributes
belongs_to :issue_from, :class_name => 'Issue'
belongs_to :issue_to, :class_name => 'Issue'
TYPE_RELATES = "relates"
TYPE_DUPLICATES = "duplicates"
TYPE_DUPLICATED = "duplicated"
TYPE_BLOCKS = "blocks"
TYPE_BLOCKED = "blocked"
TYPE_PRECEDES = "precedes"
TYPE_FOLLOWS = "follows"
TYPE_COPIED_TO = "copied_to"
TYPE_COPIED_FROM = "copied_from"
TYPES = {
TYPE_RELATES => { :name => :label_relates_to, :sym_name => :label_relates_to,
:order => 1, :sym => TYPE_RELATES },
TYPE_DUPLICATES => { :name => :label_duplicates, :sym_name => :label_duplicated_by,
:order => 2, :sym => TYPE_DUPLICATED },
TYPE_DUPLICATED => { :name => :label_duplicated_by, :sym_name => :label_duplicates,
:order => 3, :sym => TYPE_DUPLICATES, :reverse => TYPE_DUPLICATES },
TYPE_BLOCKS => { :name => :label_blocks, :sym_name => :label_blocked_by,
:order => 4, :sym => TYPE_BLOCKED },
TYPE_BLOCKED => { :name => :label_blocked_by, :sym_name => :label_blocks,
:order => 5, :sym => TYPE_BLOCKS, :reverse => TYPE_BLOCKS },
TYPE_PRECEDES => { :name => :label_precedes, :sym_name => :label_follows,
:order => 6, :sym => TYPE_FOLLOWS },
TYPE_FOLLOWS => { :name => :label_follows, :sym_name => :label_precedes,
:order => 7, :sym => TYPE_PRECEDES, :reverse => TYPE_PRECEDES },
TYPE_COPIED_TO => { :name => :label_copied_to, :sym_name => :label_copied_from,
:order => 8, :sym => TYPE_COPIED_FROM },
TYPE_COPIED_FROM => { :name => :label_copied_from, :sym_name => :label_copied_to,
:order => 9, :sym => TYPE_COPIED_TO, :reverse => TYPE_COPIED_TO }
}.freeze
validates_presence_of :issue_from, :issue_to, :relation_type
validates_inclusion_of :relation_type, :in => TYPES.keys
validates_numericality_of :delay, :allow_nil => true
validates_uniqueness_of :issue_to_id, :scope => :issue_from_id
validate :validate_issue_relation
attr_protected :issue_from_id, :issue_to_id
before_save :handle_issue_order
after_create :call_issues_relation_added_callback
after_destroy :call_issues_relation_removed_callback
safe_attributes 'relation_type',
'delay',
'issue_to_id'
def safe_attributes=(attrs, user=User.current)
return unless attrs.is_a?(Hash)
attrs = attrs.deep_dup
if issue_id = attrs.delete('issue_to_id')
if issue_id.to_s.strip.match(/\A#?(\d+)\z/)
issue_id = $1.to_i
self.issue_to = Issue.visible(user).find_by_id(issue_id)
end
end
super(attrs)
end
def visible?(user=User.current)
(issue_from.nil? || issue_from.visible?(user)) && (issue_to.nil? || issue_to.visible?(user))
end
def deletable?(user=User.current)
visible?(user) &&
((issue_from.nil? || user.allowed_to?(:manage_issue_relations, issue_from.project)) ||
(issue_to.nil? || user.allowed_to?(:manage_issue_relations, issue_to.project)))
end
def initialize(attributes=nil, *args)
super
if new_record?
if relation_type.blank?
self.relation_type = IssueRelation::TYPE_RELATES
end
end
end
def validate_issue_relation
if issue_from && issue_to
errors.add :issue_to_id, :invalid if issue_from_id == issue_to_id
unless issue_from.project_id == issue_to.project_id ||
Setting.cross_project_issue_relations?
errors.add :issue_to_id, :not_same_project
end
if circular_dependency?
errors.add :base, :circular_dependency
end
if issue_from.is_descendant_of?(issue_to) || issue_from.is_ancestor_of?(issue_to)
errors.add :base, :cant_link_an_issue_with_a_descendant
end
end
end
def other_issue(issue)
(self.issue_from_id == issue.id) ? issue_to : issue_from
end
# Returns the relation type for +issue+
def relation_type_for(issue)
if TYPES[relation_type]
if self.issue_from_id == issue.id
relation_type
else
TYPES[relation_type][:sym]
end
end
end
def label_for(issue)
TYPES[relation_type] ?
TYPES[relation_type][(self.issue_from_id == issue.id) ? :name : :sym_name] :
:unknow
end
def to_s(issue=nil)
issue ||= issue_from
issue_text = block_given? ? yield(other_issue(issue)) : "##{other_issue(issue).try(:id)}"
s = []
s << l(label_for(issue))
s << "(#{l('datetime.distance_in_words.x_days', :count => delay)})" if delay && delay != 0
s << issue_text
s.join(' ')
end
def css_classes_for(issue)
"rel-#{relation_type_for(issue)}"
end
def handle_issue_order
reverse_if_needed
if TYPE_PRECEDES == relation_type
self.delay ||= 0
else
self.delay = nil
end
set_issue_to_dates
end
def set_issue_to_dates
soonest_start = self.successor_soonest_start
if soonest_start && issue_to
issue_to.reschedule_on!(soonest_start)
end
end
def successor_soonest_start
if (TYPE_PRECEDES == self.relation_type) && delay && issue_from &&
(issue_from.start_date || issue_from.due_date)
(issue_from.due_date || issue_from.start_date) + 1 + delay
end
end
def <=>(relation)
r = TYPES[self.relation_type][:order] <=> TYPES[relation.relation_type][:order]
r == 0 ? id <=> relation.id : r
end
def init_journals(user)
issue_from.init_journal(user) if issue_from
issue_to.init_journal(user) if issue_to
end
private
# Reverses the relation if needed so that it gets stored in the proper way
# Should not be reversed before validation so that it can be displayed back
# as entered on new relation form
def reverse_if_needed
if TYPES.has_key?(relation_type) && TYPES[relation_type][:reverse]
issue_tmp = issue_to
self.issue_to = issue_from
self.issue_from = issue_tmp
self.relation_type = TYPES[relation_type][:reverse]
end
end
# Returns true if the relation would create a circular dependency
def circular_dependency?
case relation_type
when 'follows'
issue_from.would_reschedule? issue_to
when 'precedes'
issue_to.would_reschedule? issue_from
when 'blocked'
issue_from.blocks? issue_to
when 'blocks'
issue_to.blocks? issue_from
else
false
end
end
def call_issues_relation_added_callback
call_issues_callback :relation_added
end
def call_issues_relation_removed_callback
call_issues_callback :relation_removed
end
def call_issues_callback(name)
[issue_from, issue_to].each do |issue|
if issue
issue.send name, self
end
end
end
end
|
[
"class",
"IssueRelation",
"<",
"ActiveRecord",
"::",
"Base",
"class",
"Relations",
"<",
"Array",
"include",
"Redmine",
"::",
"I18n",
"def",
"initialize",
"(",
"issue",
",",
"*",
"args",
")",
"@issue",
"=",
"issue",
"super",
"(",
"*",
"args",
")",
"end",
"def",
"to_s",
"(",
"*",
"args",
")",
"map",
"{",
"|",
"relation",
"|",
"relation",
".",
"to_s",
"(",
"@issue",
")",
"}",
".",
"join",
"(",
"', '",
")",
"end",
"end",
"include",
"Redmine",
"::",
"SafeAttributes",
"belongs_to",
":issue_from",
",",
":class_name",
"=>",
"'Issue'",
"belongs_to",
":issue_to",
",",
":class_name",
"=>",
"'Issue'",
"TYPE_RELATES",
"=",
"\"relates\"",
"TYPE_DUPLICATES",
"=",
"\"duplicates\"",
"TYPE_DUPLICATED",
"=",
"\"duplicated\"",
"TYPE_BLOCKS",
"=",
"\"blocks\"",
"TYPE_BLOCKED",
"=",
"\"blocked\"",
"TYPE_PRECEDES",
"=",
"\"precedes\"",
"TYPE_FOLLOWS",
"=",
"\"follows\"",
"TYPE_COPIED_TO",
"=",
"\"copied_to\"",
"TYPE_COPIED_FROM",
"=",
"\"copied_from\"",
"TYPES",
"=",
"{",
"TYPE_RELATES",
"=>",
"{",
":name",
"=>",
":label_relates_to",
",",
":sym_name",
"=>",
":label_relates_to",
",",
":order",
"=>",
"1",
",",
":sym",
"=>",
"TYPE_RELATES",
"}",
",",
"TYPE_DUPLICATES",
"=>",
"{",
":name",
"=>",
":label_duplicates",
",",
":sym_name",
"=>",
":label_duplicated_by",
",",
":order",
"=>",
"2",
",",
":sym",
"=>",
"TYPE_DUPLICATED",
"}",
",",
"TYPE_DUPLICATED",
"=>",
"{",
":name",
"=>",
":label_duplicated_by",
",",
":sym_name",
"=>",
":label_duplicates",
",",
":order",
"=>",
"3",
",",
":sym",
"=>",
"TYPE_DUPLICATES",
",",
":reverse",
"=>",
"TYPE_DUPLICATES",
"}",
",",
"TYPE_BLOCKS",
"=>",
"{",
":name",
"=>",
":label_blocks",
",",
":sym_name",
"=>",
":label_blocked_by",
",",
":order",
"=>",
"4",
",",
":sym",
"=>",
"TYPE_BLOCKED",
"}",
",",
"TYPE_BLOCKED",
"=>",
"{",
":name",
"=>",
":label_blocked_by",
",",
":sym_name",
"=>",
":label_blocks",
",",
":order",
"=>",
"5",
",",
":sym",
"=>",
"TYPE_BLOCKS",
",",
":reverse",
"=>",
"TYPE_BLOCKS",
"}",
",",
"TYPE_PRECEDES",
"=>",
"{",
":name",
"=>",
":label_precedes",
",",
":sym_name",
"=>",
":label_follows",
",",
":order",
"=>",
"6",
",",
":sym",
"=>",
"TYPE_FOLLOWS",
"}",
",",
"TYPE_FOLLOWS",
"=>",
"{",
":name",
"=>",
":label_follows",
",",
":sym_name",
"=>",
":label_precedes",
",",
":order",
"=>",
"7",
",",
":sym",
"=>",
"TYPE_PRECEDES",
",",
":reverse",
"=>",
"TYPE_PRECEDES",
"}",
",",
"TYPE_COPIED_TO",
"=>",
"{",
":name",
"=>",
":label_copied_to",
",",
":sym_name",
"=>",
":label_copied_from",
",",
":order",
"=>",
"8",
",",
":sym",
"=>",
"TYPE_COPIED_FROM",
"}",
",",
"TYPE_COPIED_FROM",
"=>",
"{",
":name",
"=>",
":label_copied_from",
",",
":sym_name",
"=>",
":label_copied_to",
",",
":order",
"=>",
"9",
",",
":sym",
"=>",
"TYPE_COPIED_TO",
",",
":reverse",
"=>",
"TYPE_COPIED_TO",
"}",
"}",
".",
"freeze",
"validates_presence_of",
":issue_from",
",",
":issue_to",
",",
":relation_type",
"validates_inclusion_of",
":relation_type",
",",
":in",
"=>",
"TYPES",
".",
"keys",
"validates_numericality_of",
":delay",
",",
":allow_nil",
"=>",
"true",
"validates_uniqueness_of",
":issue_to_id",
",",
":scope",
"=>",
":issue_from_id",
"validate",
":validate_issue_relation",
"attr_protected",
":issue_from_id",
",",
":issue_to_id",
"before_save",
":handle_issue_order",
"after_create",
":call_issues_relation_added_callback",
"after_destroy",
":call_issues_relation_removed_callback",
"safe_attributes",
"'relation_type'",
",",
"'delay'",
",",
"'issue_to_id'",
"def",
"safe_attributes",
"=",
"(",
"attrs",
",",
"user",
"=",
"User",
".",
"current",
")",
"return",
"unless",
"attrs",
".",
"is_a?",
"(",
"Hash",
")",
"attrs",
"=",
"attrs",
".",
"deep_dup",
"if",
"issue_id",
"=",
"attrs",
".",
"delete",
"(",
"'issue_to_id'",
")",
"if",
"issue_id",
".",
"to_s",
".",
"strip",
".",
"match",
"(",
"/",
"\\A",
"#?(",
"\\d",
"+)",
"\\z",
"/",
")",
"issue_id",
"=",
"$1",
".",
"to_i",
"self",
".",
"issue_to",
"=",
"Issue",
".",
"visible",
"(",
"user",
")",
".",
"find_by_id",
"(",
"issue_id",
")",
"end",
"end",
"super",
"(",
"attrs",
")",
"end",
"def",
"visible?",
"(",
"user",
"=",
"User",
".",
"current",
")",
"(",
"issue_from",
".",
"nil?",
"||",
"issue_from",
".",
"visible?",
"(",
"user",
")",
")",
"&&",
"(",
"issue_to",
".",
"nil?",
"||",
"issue_to",
".",
"visible?",
"(",
"user",
")",
")",
"end",
"def",
"deletable?",
"(",
"user",
"=",
"User",
".",
"current",
")",
"visible?",
"(",
"user",
")",
"&&",
"(",
"(",
"issue_from",
".",
"nil?",
"||",
"user",
".",
"allowed_to?",
"(",
":manage_issue_relations",
",",
"issue_from",
".",
"project",
")",
")",
"||",
"(",
"issue_to",
".",
"nil?",
"||",
"user",
".",
"allowed_to?",
"(",
":manage_issue_relations",
",",
"issue_to",
".",
"project",
")",
")",
")",
"end",
"def",
"initialize",
"(",
"attributes",
"=",
"nil",
",",
"*",
"args",
")",
"super",
"if",
"new_record?",
"if",
"relation_type",
".",
"blank?",
"self",
".",
"relation_type",
"=",
"IssueRelation",
"::",
"TYPE_RELATES",
"end",
"end",
"end",
"def",
"validate_issue_relation",
"if",
"issue_from",
"&&",
"issue_to",
"errors",
".",
"add",
":issue_to_id",
",",
":invalid",
"if",
"issue_from_id",
"==",
"issue_to_id",
"unless",
"issue_from",
".",
"project_id",
"==",
"issue_to",
".",
"project_id",
"||",
"Setting",
".",
"cross_project_issue_relations?",
"errors",
".",
"add",
":issue_to_id",
",",
":not_same_project",
"end",
"if",
"circular_dependency?",
"errors",
".",
"add",
":base",
",",
":circular_dependency",
"end",
"if",
"issue_from",
".",
"is_descendant_of?",
"(",
"issue_to",
")",
"||",
"issue_from",
".",
"is_ancestor_of?",
"(",
"issue_to",
")",
"errors",
".",
"add",
":base",
",",
":cant_link_an_issue_with_a_descendant",
"end",
"end",
"end",
"def",
"other_issue",
"(",
"issue",
")",
"(",
"self",
".",
"issue_from_id",
"==",
"issue",
".",
"id",
")",
"?",
"issue_to",
":",
"issue_from",
"end",
"def",
"relation_type_for",
"(",
"issue",
")",
"if",
"TYPES",
"[",
"relation_type",
"]",
"if",
"self",
".",
"issue_from_id",
"==",
"issue",
".",
"id",
"relation_type",
"else",
"TYPES",
"[",
"relation_type",
"]",
"[",
":sym",
"]",
"end",
"end",
"end",
"def",
"label_for",
"(",
"issue",
")",
"TYPES",
"[",
"relation_type",
"]",
"?",
"TYPES",
"[",
"relation_type",
"]",
"[",
"(",
"self",
".",
"issue_from_id",
"==",
"issue",
".",
"id",
")",
"?",
":name",
":",
":sym_name",
"]",
":",
":unknow",
"end",
"def",
"to_s",
"(",
"issue",
"=",
"nil",
")",
"issue",
"||=",
"issue_from",
"issue_text",
"=",
"block_given?",
"?",
"yield",
"(",
"other_issue",
"(",
"issue",
")",
")",
":",
"\"##{other_issue(issue).try(:id)}\"",
"s",
"=",
"[",
"]",
"s",
"<<",
"l",
"(",
"label_for",
"(",
"issue",
")",
")",
"s",
"<<",
"\"(#{l('datetime.distance_in_words.x_days', :count => delay)})\"",
"if",
"delay",
"&&",
"delay",
"!=",
"0",
"s",
"<<",
"issue_text",
"s",
".",
"join",
"(",
"' '",
")",
"end",
"def",
"css_classes_for",
"(",
"issue",
")",
"\"rel-#{relation_type_for(issue)}\"",
"end",
"def",
"handle_issue_order",
"reverse_if_needed",
"if",
"TYPE_PRECEDES",
"==",
"relation_type",
"self",
".",
"delay",
"||=",
"0",
"else",
"self",
".",
"delay",
"=",
"nil",
"end",
"set_issue_to_dates",
"end",
"def",
"set_issue_to_dates",
"soonest_start",
"=",
"self",
".",
"successor_soonest_start",
"if",
"soonest_start",
"&&",
"issue_to",
"issue_to",
".",
"reschedule_on!",
"(",
"soonest_start",
")",
"end",
"end",
"def",
"successor_soonest_start",
"if",
"(",
"TYPE_PRECEDES",
"==",
"self",
".",
"relation_type",
")",
"&&",
"delay",
"&&",
"issue_from",
"&&",
"(",
"issue_from",
".",
"start_date",
"||",
"issue_from",
".",
"due_date",
")",
"(",
"issue_from",
".",
"due_date",
"||",
"issue_from",
".",
"start_date",
")",
"+",
"1",
"+",
"delay",
"end",
"end",
"def",
"<=>",
"(",
"relation",
")",
"r",
"=",
"TYPES",
"[",
"self",
".",
"relation_type",
"]",
"[",
":order",
"]",
"<=>",
"TYPES",
"[",
"relation",
".",
"relation_type",
"]",
"[",
":order",
"]",
"r",
"==",
"0",
"?",
"id",
"<=>",
"relation",
".",
"id",
":",
"r",
"end",
"def",
"init_journals",
"(",
"user",
")",
"issue_from",
".",
"init_journal",
"(",
"user",
")",
"if",
"issue_from",
"issue_to",
".",
"init_journal",
"(",
"user",
")",
"if",
"issue_to",
"end",
"private",
"def",
"reverse_if_needed",
"if",
"TYPES",
".",
"has_key?",
"(",
"relation_type",
")",
"&&",
"TYPES",
"[",
"relation_type",
"]",
"[",
":reverse",
"]",
"issue_tmp",
"=",
"issue_to",
"self",
".",
"issue_to",
"=",
"issue_from",
"self",
".",
"issue_from",
"=",
"issue_tmp",
"self",
".",
"relation_type",
"=",
"TYPES",
"[",
"relation_type",
"]",
"[",
":reverse",
"]",
"end",
"end",
"def",
"circular_dependency?",
"case",
"relation_type",
"when",
"'follows'",
"issue_from",
".",
"would_reschedule?",
"issue_to",
"when",
"'precedes'",
"issue_to",
".",
"would_reschedule?",
"issue_from",
"when",
"'blocked'",
"issue_from",
".",
"blocks?",
"issue_to",
"when",
"'blocks'",
"issue_to",
".",
"blocks?",
"issue_from",
"else",
"false",
"end",
"end",
"def",
"call_issues_relation_added_callback",
"call_issues_callback",
":relation_added",
"end",
"def",
"call_issues_relation_removed_callback",
"call_issues_callback",
":relation_removed",
"end",
"def",
"call_issues_callback",
"(",
"name",
")",
"[",
"issue_from",
",",
"issue_to",
"]",
".",
"each",
"do",
"|",
"issue",
"|",
"if",
"issue",
"issue",
".",
"send",
"name",
",",
"self",
"end",
"end",
"end",
"end"
] |
Redmine - project management software
Copyright (C) 2006-2016 Jean-Philippe Lang
|
[
"Redmine",
"-",
"project",
"management",
"software",
"Copyright",
"(",
"C",
")",
"2006",
"-",
"2016",
"Jean",
"-",
"Philippe",
"Lang"
] |
[
"# Class used to represent the relations of an issue",
"# Returns the relation type for +issue+",
"# Reverses the relation if needed so that it gets stored in the proper way",
"# Should not be reversed before validation so that it can be displayed back",
"# as entered on new relation form",
"# Returns true if the relation would create a circular dependency"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 13
| 1,883
| 199
|
566614aacbedf90bb6829369f44b316b5c824892
|
esparta/codetriage
|
app/models/doc_mailer_maker.rb
|
[
"MIT"
] |
Ruby
|
DocMailerMaker
|
# Creates a mailer for +user+ with +subs+.
# +user+ is a User object, +subs+ is a collection of +Repo_Subscription+ objects tied to +user+
# +Repo_Subscription+ objects contain int +user_id+, int +repo_id+,
# datetime +last_sent_at+ (for email), int +email_limit+, bool +write+,
# bool +read+, int +write_limit+, and int +read_limit+.
#
# +#subs+ is an accessor for the collection of +Repo_Subscription+ objects pass to the class.
|
Creates a mailer for +user+ with +subs+.
+#subs+ is an accessor for the collection of +Repo_Subscription+ objects pass to the class.
|
[
"Creates",
"a",
"mailer",
"for",
"+",
"user",
"+",
"with",
"+",
"subs",
"+",
".",
"+",
"#subs",
"+",
"is",
"an",
"accessor",
"for",
"the",
"collection",
"of",
"+",
"Repo_Subscription",
"+",
"objects",
"pass",
"to",
"the",
"class",
"."
] |
class DocMailerMaker
attr_accessor :user, :subs, :write_docs, :read_docs
READY_FOR_NEXT_DEFAULT = Proc.new { |_s| true }
def initialize(user, subs, _options = {}, &send_next)
@user = user
@subs = subs
@write_docs = []
@read_docs = []
assign_docs(&(send_next || READY_FOR_NEXT_DEFAULT))
end
def empty?
!any?
end
def any?
@write_docs.present? || @read_docs.present?
end
# Updates documentation task metadata (+last_sent_at+) and assigns the doc to
# the subscription.
def assign_doc_to_subscription(doc, sub)
return if doc.blank?
return doc if sub.doc_assignments.where(doc_method_id: doc.id).first
ActiveRecord::Base.transaction do
sub.doc_assignments.create!(doc_method_id: doc.id)
sub.update_attributes(last_sent_at: Time.now)
end
doc
end
# Assigns documentation tasks to a subscription
def assign_docs()
subs.flat_map do |sub|
if !yield(sub)
Rails.logger.debug "Filtered: #{sub.inspect}"
next
end
# Both +sub.read?+ and +sub.write?+ statements will assign their respective type
# to the appropriate subscription queue.
if sub.read?
sub.unassigned_read_doc_methods.each do |doc|
@read_docs << assign_doc_to_subscription(doc, sub)
end
end
if sub.write?
sub.unassigned_write_doc_methods.each do |doc|
@write_docs << assign_doc_to_subscription(doc, sub)
end
end
end
end
# Modifies accessor +write_docs+ to compact on access.
def write_docs
@write_docs.compact
end
# Modifies accessor +read_docs+ to compact on access.
def read_docs
@read_docs.compact
end
# Sends email to +user+ containing current batch of +read_docs+ and +write_docs+.
def mail
UserMailer.daily_docs(user: user, write_docs: write_docs, read_docs: read_docs)
end
# Triggers mail delivery unless there are no +read_docs+ or +write_docs+ to mail
# to the user. Returns +false+ if there are no docs, else triggers mail delivery.
def deliver
if write_docs.blank? && read_docs.blank?
Rails.logger.debug "No docs to send"
return false
end
mail.deliver_later
end
def deliver_later
if write_docs.blank? && read_docs.blank?
Rails.logger.debug "No docs to send"
return false
end
mail.deliver_later
end
end
|
[
"class",
"DocMailerMaker",
"attr_accessor",
":user",
",",
":subs",
",",
":write_docs",
",",
":read_docs",
"READY_FOR_NEXT_DEFAULT",
"=",
"Proc",
".",
"new",
"{",
"|",
"_s",
"|",
"true",
"}",
"def",
"initialize",
"(",
"user",
",",
"subs",
",",
"_options",
"=",
"{",
"}",
",",
"&",
"send_next",
")",
"@user",
"=",
"user",
"@subs",
"=",
"subs",
"@write_docs",
"=",
"[",
"]",
"@read_docs",
"=",
"[",
"]",
"assign_docs",
"(",
"&",
"(",
"send_next",
"||",
"READY_FOR_NEXT_DEFAULT",
")",
")",
"end",
"def",
"empty?",
"!",
"any?",
"end",
"def",
"any?",
"@write_docs",
".",
"present?",
"||",
"@read_docs",
".",
"present?",
"end",
"def",
"assign_doc_to_subscription",
"(",
"doc",
",",
"sub",
")",
"return",
"if",
"doc",
".",
"blank?",
"return",
"doc",
"if",
"sub",
".",
"doc_assignments",
".",
"where",
"(",
"doc_method_id",
":",
"doc",
".",
"id",
")",
".",
"first",
"ActiveRecord",
"::",
"Base",
".",
"transaction",
"do",
"sub",
".",
"doc_assignments",
".",
"create!",
"(",
"doc_method_id",
":",
"doc",
".",
"id",
")",
"sub",
".",
"update_attributes",
"(",
"last_sent_at",
":",
"Time",
".",
"now",
")",
"end",
"doc",
"end",
"def",
"assign_docs",
"(",
")",
"subs",
".",
"flat_map",
"do",
"|",
"sub",
"|",
"if",
"!",
"yield",
"(",
"sub",
")",
"Rails",
".",
"logger",
".",
"debug",
"\"Filtered: #{sub.inspect}\"",
"next",
"end",
"if",
"sub",
".",
"read?",
"sub",
".",
"unassigned_read_doc_methods",
".",
"each",
"do",
"|",
"doc",
"|",
"@read_docs",
"<<",
"assign_doc_to_subscription",
"(",
"doc",
",",
"sub",
")",
"end",
"end",
"if",
"sub",
".",
"write?",
"sub",
".",
"unassigned_write_doc_methods",
".",
"each",
"do",
"|",
"doc",
"|",
"@write_docs",
"<<",
"assign_doc_to_subscription",
"(",
"doc",
",",
"sub",
")",
"end",
"end",
"end",
"end",
"def",
"write_docs",
"@write_docs",
".",
"compact",
"end",
"def",
"read_docs",
"@read_docs",
".",
"compact",
"end",
"def",
"mail",
"UserMailer",
".",
"daily_docs",
"(",
"user",
":",
"user",
",",
"write_docs",
":",
"write_docs",
",",
"read_docs",
":",
"read_docs",
")",
"end",
"def",
"deliver",
"if",
"write_docs",
".",
"blank?",
"&&",
"read_docs",
".",
"blank?",
"Rails",
".",
"logger",
".",
"debug",
"\"No docs to send\"",
"return",
"false",
"end",
"mail",
".",
"deliver_later",
"end",
"def",
"deliver_later",
"if",
"write_docs",
".",
"blank?",
"&&",
"read_docs",
".",
"blank?",
"Rails",
".",
"logger",
".",
"debug",
"\"No docs to send\"",
"return",
"false",
"end",
"mail",
".",
"deliver_later",
"end",
"end"
] |
Creates a mailer for +user+ with +subs+.
|
[
"Creates",
"a",
"mailer",
"for",
"+",
"user",
"+",
"with",
"+",
"subs",
"+",
"."
] |
[
"# Updates documentation task metadata (+last_sent_at+) and assigns the doc to",
"# the subscription.",
"# Assigns documentation tasks to a subscription",
"# Both +sub.read?+ and +sub.write?+ statements will assign their respective type",
"# to the appropriate subscription queue.",
"# Modifies accessor +write_docs+ to compact on access.",
"# Modifies accessor +read_docs+ to compact on access.",
"# Sends email to +user+ containing current batch of +read_docs+ and +write_docs+.",
"# Triggers mail delivery unless there are no +read_docs+ or +write_docs+ to mail",
"# to the user. Returns +false+ if there are no docs, else triggers mail delivery."
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 16
| 613
| 121
|
7e78b760c2252bd93706215863c4d4845703058a
|
danielt998/poster
|
Extract.java
|
[
"MIT"
] |
Java
|
Extract
|
/*TODO:
tidy up formatting (e.g. trailing \)
ensure that split(" /") does not miss anything
give some thought to how we can implement search for characters/English too...
maybe create some sort of hashmap
search should not require exact matches, if whole provided string is a substring of pinyin
should be something like:
if it's a (partial) match:
traverse the list both backwards and forwards as far as possible and add all the matches
(starting at same place), this should be a match too.
also,** multiple words have same pinyin** - for themoment, this will return only the first result
Capitals are causing issues too...
*/
|
tidy up formatting
ensure that split(" /") does not miss anything
give some thought to how we can implement search for characters/English too
maybe create some sort of hashmap
search should not require exact matches, if whole provided string is a substring of pinyin
should be something like:
if it's a (partial) match:
traverse the list both backwards and forwards as far as possible and add all the matches
(starting at same place), this should be a match too.
also,** multiple words have same pinyin** - for themoment, this will return only the first result
Capitals are causing issues too
|
[
"tidy",
"up",
"formatting",
"ensure",
"that",
"split",
"(",
"\"",
"/",
"\"",
")",
"does",
"not",
"miss",
"anything",
"give",
"some",
"thought",
"to",
"how",
"we",
"can",
"implement",
"search",
"for",
"characters",
"/",
"English",
"too",
"maybe",
"create",
"some",
"sort",
"of",
"hashmap",
"search",
"should",
"not",
"require",
"exact",
"matches",
"if",
"whole",
"provided",
"string",
"is",
"a",
"substring",
"of",
"pinyin",
"should",
"be",
"something",
"like",
":",
"if",
"it",
"'",
"s",
"a",
"(",
"partial",
")",
"match",
":",
"traverse",
"the",
"list",
"both",
"backwards",
"and",
"forwards",
"as",
"far",
"as",
"possible",
"and",
"add",
"all",
"the",
"matches",
"(",
"starting",
"at",
"same",
"place",
")",
"this",
"should",
"be",
"a",
"match",
"too",
".",
"also",
"**",
"multiple",
"words",
"have",
"same",
"pinyin",
"**",
"-",
"for",
"themoment",
"this",
"will",
"return",
"only",
"the",
"first",
"result",
"Capitals",
"are",
"causing",
"issues",
"too"
] |
public class Extract{
private static final String DEFAULT_DICTIONARY_FILENAME= "cedict_ts.u8";
private static final char COMMENT_CHARACTER='#';
private static Map<String,Word> simplifiedMapping = new HashMap<String,Word>();
private static Map<String,Word> traditionalMapping = new HashMap<String,Word>();
public static void readInDictionary(){
readInDictionary(DEFAULT_DICTIONARY_FILENAME);
}
public static void readInDictionary(String filename){
try (BufferedReader br = new BufferedReader(new FileReader(new File(filename)))) {
String line;
while ((line = br.readLine()) != null) {
if(line.charAt(0)==COMMENT_CHARACTER){
continue;
}
Word word = new Word();
String[] str=line.split(" /");
word.setDefinition(str[1]);
String[] rem=str[0].split("\\[");
word.setPinyinNoTones(rem[1].replaceAll("[\\[\\]12345 ]", "").toLowerCase());
word.setPinyinWithTones(rem[1].replaceAll("[\\[\\]]","").toLowerCase());
String[] remRem=rem[0].split(" ");
word.setTraditionalChinese(remRem[0]);
word.setSimplifiedChinese(remRem[1]);
simplifiedMapping.put(word.getSimplifiedChinese(),word);
traditionalMapping.put(word.getTraditionalChinese(),word);
}
} catch (Exception e){
e.printStackTrace();
}
}
public static Word getWordFromChinese(char c){
return getWordFromChinese(""+c);
}
public static Word getWordFromChinese(String chineseWord){
Word simplified=getWordFromSimplifiedChinese(chineseWord);
if(simplified!=null){
return simplified;
}
return getWordFromTraditionalChinese(chineseWord);
}
public static Word getWordFromTraditionalChinese(String chineseWord){
return traditionalMapping.get(chineseWord);
}
public static Word getWordFromSimplifiedChinese(String chineseWord){
return simplifiedMapping.get(chineseWord);
}
/*TODO:resurrect
//LINEAR COMPLEXITY
public static String getEnglish(String chineseWord){
for (Word word : dictionary){
if(word.getSimplifiedChinese().equals(chineseWord)
|| word.getTraditionalChinese().equals(chineseWord)){
return word.getDefinition();
}
}
return "Chinese word not found";
}
public static String getPinyinWithTones(String chineseWord){
for (Word word : dictionary){
if(word.getSimplifiedChinese().equals(chineseWord)
|| word.getTraditionalChinese().equals(chineseWord)){
return word.getPinyinWithTones();
}
}
return "Chinese word not found";
}
*/
}
|
[
"public",
"class",
"Extract",
"{",
"private",
"static",
"final",
"String",
"DEFAULT_DICTIONARY_FILENAME",
"=",
"\"",
"cedict_ts.u8",
"\"",
";",
"private",
"static",
"final",
"char",
"COMMENT_CHARACTER",
"=",
"'#'",
";",
"private",
"static",
"Map",
"<",
"String",
",",
"Word",
">",
"simplifiedMapping",
"=",
"new",
"HashMap",
"<",
"String",
",",
"Word",
">",
"(",
")",
";",
"private",
"static",
"Map",
"<",
"String",
",",
"Word",
">",
"traditionalMapping",
"=",
"new",
"HashMap",
"<",
"String",
",",
"Word",
">",
"(",
")",
";",
"public",
"static",
"void",
"readInDictionary",
"(",
")",
"{",
"readInDictionary",
"(",
"DEFAULT_DICTIONARY_FILENAME",
")",
";",
"}",
"public",
"static",
"void",
"readInDictionary",
"(",
"String",
"filename",
")",
"{",
"try",
"(",
"BufferedReader",
"br",
"=",
"new",
"BufferedReader",
"(",
"new",
"FileReader",
"(",
"new",
"File",
"(",
"filename",
")",
")",
")",
")",
"{",
"String",
"line",
";",
"while",
"(",
"(",
"line",
"=",
"br",
".",
"readLine",
"(",
")",
")",
"!=",
"null",
")",
"{",
"if",
"(",
"line",
".",
"charAt",
"(",
"0",
")",
"==",
"COMMENT_CHARACTER",
")",
"{",
"continue",
";",
"}",
"Word",
"word",
"=",
"new",
"Word",
"(",
")",
";",
"String",
"[",
"]",
"str",
"=",
"line",
".",
"split",
"(",
"\"",
" /",
"\"",
")",
";",
"word",
".",
"setDefinition",
"(",
"str",
"[",
"1",
"]",
")",
";",
"String",
"[",
"]",
"rem",
"=",
"str",
"[",
"0",
"]",
".",
"split",
"(",
"\"",
"\\\\",
"[",
"\"",
")",
";",
"word",
".",
"setPinyinNoTones",
"(",
"rem",
"[",
"1",
"]",
".",
"replaceAll",
"(",
"\"",
"[",
"\\\\",
"[",
"\\\\",
"]12345 ]",
"\"",
",",
"\"",
"\"",
")",
".",
"toLowerCase",
"(",
")",
")",
";",
"word",
".",
"setPinyinWithTones",
"(",
"rem",
"[",
"1",
"]",
".",
"replaceAll",
"(",
"\"",
"[",
"\\\\",
"[",
"\\\\",
"]]",
"\"",
",",
"\"",
"\"",
")",
".",
"toLowerCase",
"(",
")",
")",
";",
"String",
"[",
"]",
"remRem",
"=",
"rem",
"[",
"0",
"]",
".",
"split",
"(",
"\"",
" ",
"\"",
")",
";",
"word",
".",
"setTraditionalChinese",
"(",
"remRem",
"[",
"0",
"]",
")",
";",
"word",
".",
"setSimplifiedChinese",
"(",
"remRem",
"[",
"1",
"]",
")",
";",
"simplifiedMapping",
".",
"put",
"(",
"word",
".",
"getSimplifiedChinese",
"(",
")",
",",
"word",
")",
";",
"traditionalMapping",
".",
"put",
"(",
"word",
".",
"getTraditionalChinese",
"(",
")",
",",
"word",
")",
";",
"}",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"}",
"}",
"public",
"static",
"Word",
"getWordFromChinese",
"(",
"char",
"c",
")",
"{",
"return",
"getWordFromChinese",
"(",
"\"",
"\"",
"+",
"c",
")",
";",
"}",
"public",
"static",
"Word",
"getWordFromChinese",
"(",
"String",
"chineseWord",
")",
"{",
"Word",
"simplified",
"=",
"getWordFromSimplifiedChinese",
"(",
"chineseWord",
")",
";",
"if",
"(",
"simplified",
"!=",
"null",
")",
"{",
"return",
"simplified",
";",
"}",
"return",
"getWordFromTraditionalChinese",
"(",
"chineseWord",
")",
";",
"}",
"public",
"static",
"Word",
"getWordFromTraditionalChinese",
"(",
"String",
"chineseWord",
")",
"{",
"return",
"traditionalMapping",
".",
"get",
"(",
"chineseWord",
")",
";",
"}",
"public",
"static",
"Word",
"getWordFromSimplifiedChinese",
"(",
"String",
"chineseWord",
")",
"{",
"return",
"simplifiedMapping",
".",
"get",
"(",
"chineseWord",
")",
";",
"}",
"/*TODO:resurrect\n //LINEAR COMPLEXITY\n public static String getEnglish(String chineseWord){\n for (Word word : dictionary){\n if(word.getSimplifiedChinese().equals(chineseWord)\n || word.getTraditionalChinese().equals(chineseWord)){\n return word.getDefinition();\n }\n }\n return \"Chinese word not found\";\n }\n public static String getPinyinWithTones(String chineseWord){\n for (Word word : dictionary){\n if(word.getSimplifiedChinese().equals(chineseWord)\n || word.getTraditionalChinese().equals(chineseWord)){\n return word.getPinyinWithTones();\n }\n }\n return \"Chinese word not found\";\n }\n */",
"}"
] |
TODO:
tidy up formatting (e.g.
|
[
"TODO",
":",
"tidy",
"up",
"formatting",
"(",
"e",
".",
"g",
"."
] |
[] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 16
| 574
| 148
|
bed8bb51e3230d30178c2e1f1b4ba7c564d31130
|
quintel/etengine
|
app/models/qernel/causality/aggregate_curve.rb
|
[
"MIT"
] |
Ruby
|
AggregateCurve
|
# Creates a demand curve for use in the Merit order by combining a total
# demand with a mix of curve "components" which should be mixed together in
# a share defined by the user.
#
# For example
# AggregateCurve.build(10_000, profile_one => 0.3, profile_two => 0.7)
# # => Merit::Curve
#
|
Creates a demand curve for use in the Merit order by combining a total
demand with a mix of curve "components" which should be mixed together in
a share defined by the user.
|
[
"Creates",
"a",
"demand",
"curve",
"for",
"use",
"in",
"the",
"Merit",
"order",
"by",
"combining",
"a",
"total",
"demand",
"with",
"a",
"mix",
"of",
"curve",
"\"",
"components",
"\"",
"which",
"should",
"be",
"mixed",
"together",
"in",
"a",
"share",
"defined",
"by",
"the",
"user",
"."
] |
module AggregateCurve
module_function
# Internal: Sums one or more profiles using the given profile mix.
#
# Returns Merit::Curve.
def build(mix)
return zeroed_profile if mix.empty? || mix.values.sum.zero?
return mix.keys.first if mix.length == 1
Merit::CurveTools.add_curves(
balanced_mix(mix)
.map { |prof, share| prof * share if share.positive? }
.compact
)
end
# Public: Returns a profile of all zeroes.
def zeroed_profile
Merit::Curve.new(Array.new(8760, 0.0))
end
# Internal: Ensures that a mix of profiles sum to 1.0.
#
# Returns a hash.
def balanced_mix(mix)
sum = mix.values.sum
return mix if (1.0 - sum).abs < 1e-5
# The mix of profiles does not come to (nearly) 1.0, therefore we
# rebalance the mix to ensure we have a useable profile.
mix.each_with_object({}) do |(key, value), balanced|
balanced[key] = value / sum
end
end
private_class_method :balanced_mix
end
|
[
"module",
"AggregateCurve",
"module_function",
"def",
"build",
"(",
"mix",
")",
"return",
"zeroed_profile",
"if",
"mix",
".",
"empty?",
"||",
"mix",
".",
"values",
".",
"sum",
".",
"zero?",
"return",
"mix",
".",
"keys",
".",
"first",
"if",
"mix",
".",
"length",
"==",
"1",
"Merit",
"::",
"CurveTools",
".",
"add_curves",
"(",
"balanced_mix",
"(",
"mix",
")",
".",
"map",
"{",
"|",
"prof",
",",
"share",
"|",
"prof",
"*",
"share",
"if",
"share",
".",
"positive?",
"}",
".",
"compact",
")",
"end",
"def",
"zeroed_profile",
"Merit",
"::",
"Curve",
".",
"new",
"(",
"Array",
".",
"new",
"(",
"8760",
",",
"0.0",
")",
")",
"end",
"def",
"balanced_mix",
"(",
"mix",
")",
"sum",
"=",
"mix",
".",
"values",
".",
"sum",
"return",
"mix",
"if",
"(",
"1.0",
"-",
"sum",
")",
".",
"abs",
"<",
"1e-5",
"mix",
".",
"each_with_object",
"(",
"{",
"}",
")",
"do",
"|",
"(",
"key",
",",
"value",
")",
",",
"balanced",
"|",
"balanced",
"[",
"key",
"]",
"=",
"value",
"/",
"sum",
"end",
"end",
"private_class_method",
":balanced_mix",
"end"
] |
Creates a demand curve for use in the Merit order by combining a total
demand with a mix of curve "components" which should be mixed together in
a share defined by the user.
|
[
"Creates",
"a",
"demand",
"curve",
"for",
"use",
"in",
"the",
"Merit",
"order",
"by",
"combining",
"a",
"total",
"demand",
"with",
"a",
"mix",
"of",
"curve",
"\"",
"components",
"\"",
"which",
"should",
"be",
"mixed",
"together",
"in",
"a",
"share",
"defined",
"by",
"the",
"user",
"."
] |
[
"# Internal: Sums one or more profiles using the given profile mix.",
"#",
"# Returns Merit::Curve.",
"# Public: Returns a profile of all zeroes.",
"# Internal: Ensures that a mix of profiles sum to 1.0.",
"#",
"# Returns a hash.",
"# The mix of profiles does not come to (nearly) 1.0, therefore we",
"# rebalance the mix to ensure we have a useable profile."
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 13
| 286
| 86
|
10a6820f7325e566530e0a58907aa51f2ca104ec
|
Team-10397/RobotCode2019
|
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/AutoStartNearCraterWithCamera.java
|
[
"MIT"
] |
Java
|
AutoStartNearCraterWithCamera
|
/**
* This file contains an minimal example of a Linear "OpMode". An OpMode is a 'program' that runs in either
* the autonomous or the teleop period of an FTC match. The names of OpModes appear on the menu
* of the FTC Driver Station. When an selection is made from the menu, the corresponding OpMode
* class is instantiated on the Robot Controller and executed.
*
* This particular OpMode just executes a basic Tank Drive Teleop for a two wheeled robot
* It includes all the skeletal structure that all linear OpModes contain.
*
* Use Android Studios to Copy this Class, and Paste it into your team's code folder with a new name.
* Remove or comment out the @Disabled line to add this opmode to the Driver Station OpMode list
*/
|
This file contains an minimal example of a Linear "OpMode". An OpMode is a 'program' that runs in either
the autonomous or the teleop period of an FTC match. The names of OpModes appear on the menu
of the FTC Driver Station. When an selection is made from the menu, the corresponding OpMode
class is instantiated on the Robot Controller and executed.
This particular OpMode just executes a basic Tank Drive Teleop for a two wheeled robot
It includes all the skeletal structure that all linear OpModes contain.
Use Android Studios to Copy this Class, and Paste it into your team's code folder with a new name.
Remove or comment out the @Disabled line to add this opmode to the Driver Station OpMode list
|
[
"This",
"file",
"contains",
"an",
"minimal",
"example",
"of",
"a",
"Linear",
"\"",
"OpMode",
"\"",
".",
"An",
"OpMode",
"is",
"a",
"'",
"program",
"'",
"that",
"runs",
"in",
"either",
"the",
"autonomous",
"or",
"the",
"teleop",
"period",
"of",
"an",
"FTC",
"match",
".",
"The",
"names",
"of",
"OpModes",
"appear",
"on",
"the",
"menu",
"of",
"the",
"FTC",
"Driver",
"Station",
".",
"When",
"an",
"selection",
"is",
"made",
"from",
"the",
"menu",
"the",
"corresponding",
"OpMode",
"class",
"is",
"instantiated",
"on",
"the",
"Robot",
"Controller",
"and",
"executed",
".",
"This",
"particular",
"OpMode",
"just",
"executes",
"a",
"basic",
"Tank",
"Drive",
"Teleop",
"for",
"a",
"two",
"wheeled",
"robot",
"It",
"includes",
"all",
"the",
"skeletal",
"structure",
"that",
"all",
"linear",
"OpModes",
"contain",
".",
"Use",
"Android",
"Studios",
"to",
"Copy",
"this",
"Class",
"and",
"Paste",
"it",
"into",
"your",
"team",
"'",
"s",
"code",
"folder",
"with",
"a",
"new",
"name",
".",
"Remove",
"or",
"comment",
"out",
"the",
"@Disabled",
"line",
"to",
"add",
"this",
"opmode",
"to",
"the",
"Driver",
"Station",
"OpMode",
"list"
] |
@Autonomous(name="Autonomous Crater With Camera", group="Camera")
public class AutoStartNearCraterWithCamera extends LinearOpMode {
private static final String TFOD_MODEL_ASSET = "RoverRuckus.tflite";
private static final String LABEL_GOLD_MINERAL = "Gold Mineral";
private static final String LABEL_SILVER_MINERAL = "Silver Mineral";
private static final String VUFORIA_KEY = "AdCuaEX/////AAABmXYJgRHZxkB9gj+81cIaX+JZm4W2w3Ee2HhKucJINnuXQ8l214BoCiyEk04zmQ/1VPvo+8PY7Um3eI5rI4WnSJmEXo7jyMz2WZDkkRnA88uBCtbml8CsMSIS7J3aUcgVd9P8ocLLgwqpavhEEaUixEx/16rgzIEtuHcq5ghQzzCkqR1xvAaxnx5lWM+ixf6hBCfZEnaiUM7WjD4gflO55IpoO/CdCWQrGUw2LuUKW2J+4K6ftKwJ+B1Qdy7pt2tDrGZvMyB4AcphPuoJRCSr5NgRoNWZ+WH5LqAdzYEO0Bv7C9LeSgmSPPT7GPPDpjv6+3DO5BE6l+2uMYQQbuF11BWKKq5Xp+D5Y6l2+W97zpgP";
private VuforiaLocalizer vuforia;
private TFObjectDetector tfod;
// Declare OpMode members.
private ElapsedTime runtime = new ElapsedTime();
HardwareRobot iceRobot = new HardwareRobot();
int state = 0; // TODO: use enums
int goldSpot = 0;
int stuffInRoi = 0;
@Override
public void runOpMode() {
telemetry.addData("Status", "Initialized");
telemetry.update();
iceRobot.init(hardwareMap);
// The TFObjectDetector uses the camera frames from the VuforiaLocalizer, so we create that
// first.
initVuforia();
if (ClassFactory.getInstance().canCreateTFObjectDetector()) {
initTfod(); // initializes the camera
} else {
telemetry.addData("Sorry!", "This device is not compatible with TFOD");
}
if (tfod != null) {
tfod.activate(); // initializes the mineral detection
}
waitForStart();
//CameraDevice.getInstance().setFlashTorchMode(true);
this.resetStartTime(); // resets timer (for debugging purposes)
/*
if (opModeIsActive()) {
while (goldSpot == 0 && opModeIsActive()) { //this loop runs until an object is detected or the program stops
telemetry.addData("goldspot", goldSpot);
telemetry.addData("scanning", this.getRuntime()); //updates the display with the time since the scan started
telemetry.update();
if (tfod != null) {
List<Recognition> updatedRecognitions = tfod.getUpdatedRecognitions(); // puts all of the scanned minerals in a list
if (updatedRecognitions != null) {
if (updatedRecognitions.size() <= 2) { // the following code runs if the robot sees 2 or more minerals
int goldMineralX = -1; // defining minerals
int silverMineral1X = -1;
int silverMineral2X = -1;
for (Recognition recognition : updatedRecognitions) { // code loops for every mineral that is detected
if (recognition.getLeft() > 350 && recognition.getTop() > 350) {
if (recognition.getLabel().equals(LABEL_GOLD_MINERAL)) {
goldMineralX = (int) recognition.getTop(); // if a gold mineral is detected, its position is recorded
} else if (silverMineral1X == -1) {
silverMineral1X = (int) recognition.getTop(); // if silver elements are detected, their positions are recorded.
} else {
silverMineral2X = (int) recognition.getTop();
}
}
}
if (silverMineral1X != -1 && silverMineral2X != -1 && goldMineralX == -1) { //if two silver minerals are found, then the gold is on the left [] O O (the robot only scans for the right two minerals)
goldSpot = 1; //left
} else if (goldMineralX < silverMineral1X) { // gold to the left of silver: O [] O
goldSpot = 2; //center
} else if (goldMineralX > silverMineral1X) { // gold to the right of silver: O O []
goldSpot = 3; //right
}
}
}
}
}
}*/
CameraDevice.getInstance().setFlashTorchMode(false) ;
telemetry.addData("gold is", goldSpot); // displays the position of the gold mineral
telemetry.addData("time took", this.getRuntime() + " seconds"); // displays the time taken to scan
telemetry.update();
goldSpot=2;
while (opModeIsActive()) {
switch (state) {
case 0: // drops from the lander
iceRobot.climbMotor.setPower(-1);
if (iceRobot.climbMotor.getCurrentPosition() < -3523) {
iceRobot.climbMotor.setPower(0);
state += 1;
}
break;
case 1: // turns to unlatch from lander
iceRobot.encoderTurn(15);
sleep(500);
iceRobot.encoderMove(-1.5, .50, this);
sleep(500);
state += 1;
break;
case 2: // lowers climbing arm
iceRobot.climbMotor.setPower(1);
double start_time = runtime.milliseconds();
if (iceRobot.climbMotor.getCurrentPosition() > -1000 || runtime.milliseconds() - start_time > 750) {
iceRobot.climbMotor.setPower(0);
sleep(1000);
state += 1;
}
break;
case 3: // turns to right itself
iceRobot.encoderTurn(-30);
sleep(500);
state += 1;
break;
case 4: // backs towards the crater
iceRobot.encoderMove(-10, .5, this);
sleep(500);
state += goldSpot;
break;
case 5:
iceRobot.encoderTurn(45);
sleep(500);
iceRobot.encoderMove(-20, .5, this);
sleep(500);
iceRobot.encoderMove(20, .5, this);
sleep(500);
iceRobot.encoderTurn(70);
state = 8;
break;
case 6:
iceRobot.encoderMove(-9, .5, this);
sleep(500);
iceRobot.encoderMove(9, 0.5, this);
sleep(500);
iceRobot.encoderTurn(100);
state = 8;
break;
case 7:
sleep(500);
iceRobot.encoderTurn(-45);
sleep(500);
iceRobot.encoderMove(-20, .5, this);
sleep(500);
iceRobot.encoderMove(20, 1, this);
sleep(500);
iceRobot.encoderTurn(150);
state = 8;
break;
case 8:
sleep(500);
iceRobot.encoderMove(30, .8, this);
sleep(500);
iceRobot.encoderTurn(-15);
sleep(500);
iceRobot.encoderMove(46, 1, this);
sleep(500);
iceRobot.encoderTurn(-210);
sleep(500);
state += 1;
break;
case 9: // drops the team marker
iceRobot.rightClaw.setPosition(iceRobot.SERVO_CENTER);
sleep(1000);
state += 1;
break;
case 10:
iceRobot.encoderMove(50, .9, this);
sleep(500);
state += 1;
break;
case 11:
iceRobot.moveTime(1,0);
if (iceRobot.frontBumper.isPressed()){
iceRobot.stop();
state += 1;
}
break;
}
}
}
private void initVuforia() {
/*
* Configure Vuforia by creating a Parameter object, and passing it to the Vuforia engine.
*/
VuforiaLocalizer.Parameters parameters = new VuforiaLocalizer.Parameters();
parameters.vuforiaLicenseKey = VUFORIA_KEY;
parameters.cameraDirection = CameraDirection.BACK;
// Instantiate the Vuforia engine
vuforia = ClassFactory.getInstance().createVuforia(parameters);
// Loading trackables is not necessary for the Tensor Flow Object Detection engine.
}
/**
* Initialize the Tensor Flow Object Detection engine.
*/
private void initTfod() {
int tfodMonitorViewId = hardwareMap.appContext.getResources().getIdentifier(
"tfodMonitorViewId", "id", hardwareMap.appContext.getPackageName());
TFObjectDetector.Parameters tfodParameters = new TFObjectDetector.Parameters(tfodMonitorViewId);
tfod = ClassFactory.getInstance().createTFObjectDetector(tfodParameters, vuforia);
tfod.loadModelFromAsset(TFOD_MODEL_ASSET, LABEL_GOLD_MINERAL, LABEL_SILVER_MINERAL);
}
}
|
[
"@",
"Autonomous",
"(",
"name",
"=",
"\"",
"Autonomous Crater With Camera",
"\"",
",",
"group",
"=",
"\"",
"Camera",
"\"",
")",
"public",
"class",
"AutoStartNearCraterWithCamera",
"extends",
"LinearOpMode",
"{",
"private",
"static",
"final",
"String",
"TFOD_MODEL_ASSET",
"=",
"\"",
"RoverRuckus.tflite",
"\"",
";",
"private",
"static",
"final",
"String",
"LABEL_GOLD_MINERAL",
"=",
"\"",
"Gold Mineral",
"\"",
";",
"private",
"static",
"final",
"String",
"LABEL_SILVER_MINERAL",
"=",
"\"",
"Silver Mineral",
"\"",
";",
"private",
"static",
"final",
"String",
"VUFORIA_KEY",
"=",
"\"",
"AdCuaEX/////AAABmXYJgRHZxkB9gj+81cIaX+JZm4W2w3Ee2HhKucJINnuXQ8l214BoCiyEk04zmQ/1VPvo+8PY7Um3eI5rI4WnSJmEXo7jyMz2WZDkkRnA88uBCtbml8CsMSIS7J3aUcgVd9P8ocLLgwqpavhEEaUixEx/16rgzIEtuHcq5ghQzzCkqR1xvAaxnx5lWM+ixf6hBCfZEnaiUM7WjD4gflO55IpoO/CdCWQrGUw2LuUKW2J+4K6ftKwJ+B1Qdy7pt2tDrGZvMyB4AcphPuoJRCSr5NgRoNWZ+WH5LqAdzYEO0Bv7C9LeSgmSPPT7GPPDpjv6+3DO5BE6l+2uMYQQbuF11BWKKq5Xp+D5Y6l2+W97zpgP",
"\"",
";",
"private",
"VuforiaLocalizer",
"vuforia",
";",
"private",
"TFObjectDetector",
"tfod",
";",
"private",
"ElapsedTime",
"runtime",
"=",
"new",
"ElapsedTime",
"(",
")",
";",
"HardwareRobot",
"iceRobot",
"=",
"new",
"HardwareRobot",
"(",
")",
";",
"int",
"state",
"=",
"0",
";",
"int",
"goldSpot",
"=",
"0",
";",
"int",
"stuffInRoi",
"=",
"0",
";",
"@",
"Override",
"public",
"void",
"runOpMode",
"(",
")",
"{",
"telemetry",
".",
"addData",
"(",
"\"",
"Status",
"\"",
",",
"\"",
"Initialized",
"\"",
")",
";",
"telemetry",
".",
"update",
"(",
")",
";",
"iceRobot",
".",
"init",
"(",
"hardwareMap",
")",
";",
"initVuforia",
"(",
")",
";",
"if",
"(",
"ClassFactory",
".",
"getInstance",
"(",
")",
".",
"canCreateTFObjectDetector",
"(",
")",
")",
"{",
"initTfod",
"(",
")",
";",
"}",
"else",
"{",
"telemetry",
".",
"addData",
"(",
"\"",
"Sorry!",
"\"",
",",
"\"",
"This device is not compatible with TFOD",
"\"",
")",
";",
"}",
"if",
"(",
"tfod",
"!=",
"null",
")",
"{",
"tfod",
".",
"activate",
"(",
")",
";",
"}",
"waitForStart",
"(",
")",
";",
"this",
".",
"resetStartTime",
"(",
")",
";",
"/*\n if (opModeIsActive()) {\n while (goldSpot == 0 && opModeIsActive()) { //this loop runs until an object is detected or the program stops\n telemetry.addData(\"goldspot\", goldSpot);\n telemetry.addData(\"scanning\", this.getRuntime()); //updates the display with the time since the scan started\n telemetry.update();\n if (tfod != null) {\n List<Recognition> updatedRecognitions = tfod.getUpdatedRecognitions(); // puts all of the scanned minerals in a list\n if (updatedRecognitions != null) {\n if (updatedRecognitions.size() <= 2) { // the following code runs if the robot sees 2 or more minerals\n int goldMineralX = -1; // defining minerals\n int silverMineral1X = -1;\n int silverMineral2X = -1;\n for (Recognition recognition : updatedRecognitions) { // code loops for every mineral that is detected\n if (recognition.getLeft() > 350 && recognition.getTop() > 350) {\n if (recognition.getLabel().equals(LABEL_GOLD_MINERAL)) {\n goldMineralX = (int) recognition.getTop(); // if a gold mineral is detected, its position is recorded\n } else if (silverMineral1X == -1) {\n silverMineral1X = (int) recognition.getTop(); // if silver elements are detected, their positions are recorded.\n } else {\n silverMineral2X = (int) recognition.getTop();\n }\n }\n }\n if (silverMineral1X != -1 && silverMineral2X != -1 && goldMineralX == -1) { //if two silver minerals are found, then the gold is on the left [] O O (the robot only scans for the right two minerals)\n goldSpot = 1; //left\n } else if (goldMineralX < silverMineral1X) { // gold to the left of silver: O [] O\n goldSpot = 2; //center\n } else if (goldMineralX > silverMineral1X) { // gold to the right of silver: O O []\n goldSpot = 3; //right\n }\n }\n }\n }\n }\n }*/",
"CameraDevice",
".",
"getInstance",
"(",
")",
".",
"setFlashTorchMode",
"(",
"false",
")",
";",
"telemetry",
".",
"addData",
"(",
"\"",
"gold is",
"\"",
",",
"goldSpot",
")",
";",
"telemetry",
".",
"addData",
"(",
"\"",
"time took",
"\"",
",",
"this",
".",
"getRuntime",
"(",
")",
"+",
"\"",
" seconds",
"\"",
")",
";",
"telemetry",
".",
"update",
"(",
")",
";",
"goldSpot",
"=",
"2",
";",
"while",
"(",
"opModeIsActive",
"(",
")",
")",
"{",
"switch",
"(",
"state",
")",
"{",
"case",
"0",
":",
"iceRobot",
".",
"climbMotor",
".",
"setPower",
"(",
"-",
"1",
")",
";",
"if",
"(",
"iceRobot",
".",
"climbMotor",
".",
"getCurrentPosition",
"(",
")",
"<",
"-",
"3523",
")",
"{",
"iceRobot",
".",
"climbMotor",
".",
"setPower",
"(",
"0",
")",
";",
"state",
"+=",
"1",
";",
"}",
"break",
";",
"case",
"1",
":",
"iceRobot",
".",
"encoderTurn",
"(",
"15",
")",
";",
"sleep",
"(",
"500",
")",
";",
"iceRobot",
".",
"encoderMove",
"(",
"-",
"1.5",
",",
".50",
",",
"this",
")",
";",
"sleep",
"(",
"500",
")",
";",
"state",
"+=",
"1",
";",
"break",
";",
"case",
"2",
":",
"iceRobot",
".",
"climbMotor",
".",
"setPower",
"(",
"1",
")",
";",
"double",
"start_time",
"=",
"runtime",
".",
"milliseconds",
"(",
")",
";",
"if",
"(",
"iceRobot",
".",
"climbMotor",
".",
"getCurrentPosition",
"(",
")",
">",
"-",
"1000",
"||",
"runtime",
".",
"milliseconds",
"(",
")",
"-",
"start_time",
">",
"750",
")",
"{",
"iceRobot",
".",
"climbMotor",
".",
"setPower",
"(",
"0",
")",
";",
"sleep",
"(",
"1000",
")",
";",
"state",
"+=",
"1",
";",
"}",
"break",
";",
"case",
"3",
":",
"iceRobot",
".",
"encoderTurn",
"(",
"-",
"30",
")",
";",
"sleep",
"(",
"500",
")",
";",
"state",
"+=",
"1",
";",
"break",
";",
"case",
"4",
":",
"iceRobot",
".",
"encoderMove",
"(",
"-",
"10",
",",
".5",
",",
"this",
")",
";",
"sleep",
"(",
"500",
")",
";",
"state",
"+=",
"goldSpot",
";",
"break",
";",
"case",
"5",
":",
"iceRobot",
".",
"encoderTurn",
"(",
"45",
")",
";",
"sleep",
"(",
"500",
")",
";",
"iceRobot",
".",
"encoderMove",
"(",
"-",
"20",
",",
".5",
",",
"this",
")",
";",
"sleep",
"(",
"500",
")",
";",
"iceRobot",
".",
"encoderMove",
"(",
"20",
",",
".5",
",",
"this",
")",
";",
"sleep",
"(",
"500",
")",
";",
"iceRobot",
".",
"encoderTurn",
"(",
"70",
")",
";",
"state",
"=",
"8",
";",
"break",
";",
"case",
"6",
":",
"iceRobot",
".",
"encoderMove",
"(",
"-",
"9",
",",
".5",
",",
"this",
")",
";",
"sleep",
"(",
"500",
")",
";",
"iceRobot",
".",
"encoderMove",
"(",
"9",
",",
"0.5",
",",
"this",
")",
";",
"sleep",
"(",
"500",
")",
";",
"iceRobot",
".",
"encoderTurn",
"(",
"100",
")",
";",
"state",
"=",
"8",
";",
"break",
";",
"case",
"7",
":",
"sleep",
"(",
"500",
")",
";",
"iceRobot",
".",
"encoderTurn",
"(",
"-",
"45",
")",
";",
"sleep",
"(",
"500",
")",
";",
"iceRobot",
".",
"encoderMove",
"(",
"-",
"20",
",",
".5",
",",
"this",
")",
";",
"sleep",
"(",
"500",
")",
";",
"iceRobot",
".",
"encoderMove",
"(",
"20",
",",
"1",
",",
"this",
")",
";",
"sleep",
"(",
"500",
")",
";",
"iceRobot",
".",
"encoderTurn",
"(",
"150",
")",
";",
"state",
"=",
"8",
";",
"break",
";",
"case",
"8",
":",
"sleep",
"(",
"500",
")",
";",
"iceRobot",
".",
"encoderMove",
"(",
"30",
",",
".8",
",",
"this",
")",
";",
"sleep",
"(",
"500",
")",
";",
"iceRobot",
".",
"encoderTurn",
"(",
"-",
"15",
")",
";",
"sleep",
"(",
"500",
")",
";",
"iceRobot",
".",
"encoderMove",
"(",
"46",
",",
"1",
",",
"this",
")",
";",
"sleep",
"(",
"500",
")",
";",
"iceRobot",
".",
"encoderTurn",
"(",
"-",
"210",
")",
";",
"sleep",
"(",
"500",
")",
";",
"state",
"+=",
"1",
";",
"break",
";",
"case",
"9",
":",
"iceRobot",
".",
"rightClaw",
".",
"setPosition",
"(",
"iceRobot",
".",
"SERVO_CENTER",
")",
";",
"sleep",
"(",
"1000",
")",
";",
"state",
"+=",
"1",
";",
"break",
";",
"case",
"10",
":",
"iceRobot",
".",
"encoderMove",
"(",
"50",
",",
".9",
",",
"this",
")",
";",
"sleep",
"(",
"500",
")",
";",
"state",
"+=",
"1",
";",
"break",
";",
"case",
"11",
":",
"iceRobot",
".",
"moveTime",
"(",
"1",
",",
"0",
")",
";",
"if",
"(",
"iceRobot",
".",
"frontBumper",
".",
"isPressed",
"(",
")",
")",
"{",
"iceRobot",
".",
"stop",
"(",
")",
";",
"state",
"+=",
"1",
";",
"}",
"break",
";",
"}",
"}",
"}",
"private",
"void",
"initVuforia",
"(",
")",
"{",
"/*\n * Configure Vuforia by creating a Parameter object, and passing it to the Vuforia engine.\n */",
"VuforiaLocalizer",
".",
"Parameters",
"parameters",
"=",
"new",
"VuforiaLocalizer",
".",
"Parameters",
"(",
")",
";",
"parameters",
".",
"vuforiaLicenseKey",
"=",
"VUFORIA_KEY",
";",
"parameters",
".",
"cameraDirection",
"=",
"CameraDirection",
".",
"BACK",
";",
"vuforia",
"=",
"ClassFactory",
".",
"getInstance",
"(",
")",
".",
"createVuforia",
"(",
"parameters",
")",
";",
"}",
"/**\n * Initialize the Tensor Flow Object Detection engine.\n */",
"private",
"void",
"initTfod",
"(",
")",
"{",
"int",
"tfodMonitorViewId",
"=",
"hardwareMap",
".",
"appContext",
".",
"getResources",
"(",
")",
".",
"getIdentifier",
"(",
"\"",
"tfodMonitorViewId",
"\"",
",",
"\"",
"id",
"\"",
",",
"hardwareMap",
".",
"appContext",
".",
"getPackageName",
"(",
")",
")",
";",
"TFObjectDetector",
".",
"Parameters",
"tfodParameters",
"=",
"new",
"TFObjectDetector",
".",
"Parameters",
"(",
"tfodMonitorViewId",
")",
";",
"tfod",
"=",
"ClassFactory",
".",
"getInstance",
"(",
")",
".",
"createTFObjectDetector",
"(",
"tfodParameters",
",",
"vuforia",
")",
";",
"tfod",
".",
"loadModelFromAsset",
"(",
"TFOD_MODEL_ASSET",
",",
"LABEL_GOLD_MINERAL",
",",
"LABEL_SILVER_MINERAL",
")",
";",
"}",
"}"
] |
This file contains an minimal example of a Linear "OpMode".
|
[
"This",
"file",
"contains",
"an",
"minimal",
"example",
"of",
"a",
"Linear",
"\"",
"OpMode",
"\"",
"."
] |
[
"// Declare OpMode members.",
"// TODO: use enums",
"// The TFObjectDetector uses the camera frames from the VuforiaLocalizer, so we create that",
"// first.",
"// initializes the camera",
"// initializes the mineral detection",
"//CameraDevice.getInstance().setFlashTorchMode(true);",
"// resets timer (for debugging purposes)",
"// displays the position of the gold mineral",
"// displays the time taken to scan",
"// drops from the lander",
"// turns to unlatch from lander",
"// lowers climbing arm",
"// turns to right itself",
"// backs towards the crater",
"// drops the team marker",
"// Instantiate the Vuforia engine",
"// Loading trackables is not necessary for the Tensor Flow Object Detection engine."
] |
[
{
"param": "LinearOpMode",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "LinearOpMode",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 17
| 2,188
| 165
|
fbc41a38f9bfa0a812830648198650f5176300a0
|
AricHurkman/CSIC190
|
src/CISC190/bookClasses/MovieWriter.java
|
[
"MIT"
] |
Java
|
MovieWriter
|
/**
* Class to write out an AVI or Quicktime movie from
* a series of JPEG (jpg) frames in a directory
*
* @author Barb Ericson [email protected]
* <p>
* Depreciated File.toURL() replaced with File.toURI().toURL()
* by Buck Scharfnorth 22 May 2008
* <p>
* Modified writeQuicktime() and writeAVI() to check
* for appropriate endings (".mov" and ".avi") before
* appending them to the destination path. Also modified
* getOutputURL to check for "%20" in destination path.
* by Brian O'Neill 11 Aug 2008
*/
|
Class to write out an AVI or Quicktime movie from
a series of JPEG (jpg) frames in a directory
@author Barb Ericson [email protected]
Depreciated File.toURL() replaced with File.toURI().toURL()
by Buck Scharfnorth 22 May 2008
Modified writeQuicktime() and writeAVI() to check
for appropriate endings (".mov" and ".avi") before
appending them to the destination path. Also modified
getOutputURL to check for "%20" in destination path.
by Brian O'Neill 11 Aug 2008
|
[
"Class",
"to",
"write",
"out",
"an",
"AVI",
"or",
"Quicktime",
"movie",
"from",
"a",
"series",
"of",
"JPEG",
"(",
"jpg",
")",
"frames",
"in",
"a",
"directory",
"@author",
"Barb",
"Ericson",
"ericson@cc",
".",
"gatech",
".",
"edu",
"Depreciated",
"File",
".",
"toURL",
"()",
"replaced",
"with",
"File",
".",
"toURI",
"()",
".",
"toURL",
"()",
"by",
"Buck",
"Scharfnorth",
"22",
"May",
"2008",
"Modified",
"writeQuicktime",
"()",
"and",
"writeAVI",
"()",
"to",
"check",
"for",
"appropriate",
"endings",
"(",
"\"",
".",
"mov",
"\"",
"and",
"\"",
".",
"avi",
"\"",
")",
"before",
"appending",
"them",
"to",
"the",
"destination",
"path",
".",
"Also",
"modified",
"getOutputURL",
"to",
"check",
"for",
"\"",
"%20",
"\"",
"in",
"destination",
"path",
".",
"by",
"Brian",
"O",
"'",
"Neill",
"11",
"Aug",
"2008"
] |
public class MovieWriter {
///////////////// fields ///////////////////////////
/**
* the directory to read the frames from
*/
private String framesDir = null;
/**
* the number of frames per second
*/
private int frameRate = 16;
/**
* the name of the movie file
*/
private String movieName = null;
/**
* the output url for the movie
*/
private String outputURL = null;
////////////////// constructors //////////////////////
/**
* Constructor that takes no arguments
*/
public MovieWriter() {
framesDir = FileChooser.pickADirectory();
movieName = getMovieName();
outputURL = getOutputURL();
}
/**
* Constructor that takes the directory that
* has the frames
*
* @param dirPath the full path for the directory
* that has the movie frames
*/
public MovieWriter(String dirPath) {
framesDir = dirPath;
if (!framesDir.endsWith(File.separator) && !framesDir.endsWith("/")) //Makes sure framesDir ends with the file separator
framesDir += File.separator;
movieName = getMovieName();
outputURL = getOutputURL();
}
/**
* Constructor that takes the frame rate
*
* @param theFrameRate the number of frames per second
*/
public MovieWriter(int theFrameRate) {
framesDir = FileChooser.pickADirectory();
frameRate = theFrameRate;
movieName = getMovieName();
outputURL = getOutputURL();
}
/**
* Constructor that takes the frame rate and the
* directory that the frames are stored in
*
* @param theFrameRate the number of frames per second
* @param theFramesDir the directory where the frames are
*/
public MovieWriter(int theFrameRate, String theFramesDir) {
this.framesDir = theFramesDir;
if (!framesDir.endsWith(File.separator) && !framesDir.endsWith("/")) //Makes sure framesDir ends with the file separator
framesDir += File.separator;
this.frameRate = theFrameRate;
movieName = getMovieName();
outputURL = getOutputURL();
}
/**
* Constructor that takes the directory with the frames
* the frame rate, and the output url (dir,name,
* and extendsion)
*
* @param theFramesDir the directory that holds the frame
* @param theFrameRate the number of frames per second
* @param theOutputURL the complete path name for the output
* movie
*/
public MovieWriter(String theFramesDir, int theFrameRate, String theOutputURL) {
this.framesDir = theFramesDir;
if (!framesDir.endsWith(File.separator) && !framesDir.endsWith("/")) //Makes sure framesDir ends with the file separator
framesDir += File.separator;
this.frameRate = theFrameRate;
this.outputURL = theOutputURL;
}
/////////////////// methods //////////////////////////
/**
* Method to get the movie name from the directory
* where the frames are stored
*
* @return the name of the movie (like movie1)
*/
private String getMovieName() {
File dir = new File(framesDir);
return dir.getName();
}
/**
* Method to create the output URL from the directory
* the frames are stored in.
*
* @return the URL for the output movie file
*/
private String getOutputURL() {
File dir = null;
URL myURL = null;
if (framesDir != null) {
try {
dir = new File(framesDir + movieName);
myURL = dir.toURI().toURL();
} catch (Exception ex) {
}
}
//return myURL.toString();
return myURL.toString().replace("%20", " ");
}
/**
* Method to get the list of jpeg frames
*
* @return a list of full path names for the frames
* of the movie
*/
public List<String> getFrameNames() {
File dir = new File(framesDir);
String[] filesArray = dir.list();
List<String> files = new ArrayList<String>();
long lenFirst = 0;
for (String fileName : filesArray) {
// only continue if jpg picture
if (fileName.indexOf(".jpg") >= 0) {
File f = new File(framesDir + fileName);
// check for imcomplete image
if (lenFirst == 0 || f.length() > (lenFirst / 2)) {
// image okay so far
try {
BufferedImage i = ImageIO.read(f);
files.add(framesDir + fileName);
} catch (Exception ex) {
// if problem reading don't add it
}
}
if (lenFirst == 0) lenFirst = f.length();
}
}
return files;
}
/**
* Method to write the movie frames in AVI format
*/
public void writeAVI() {
/* JMF Code no longer functioned for writing AVIs.
* Commented out and code below was written to use a
* different AVI writing library.
* BJD: 11-9-09
*
JpegImagesToMovie imageToMovie = new JpegImagesToMovie();
List<String> frameNames = getFrameNames();
Picture p = new Picture((String) frameNames.get(0));
if(!outputURL.endsWith(".avi"))
outputURL = outputURL + ".avi";
imageToMovie.doItAVI(p.getWidth(),p.getHeight(),
frameRate,frameNames,outputURL);
*/
// The code below utilizes Werner Randelshofer's AVIOutputStream
// object to write an AVI movie from the list of frames. His code
// is shared under the Creative Commons Attribution License
// (see http://creativecommons.org/licenses/by/3.0/). More
// information about that code can be found in the AVIDemo.jar
// archive in the jars folder or at http://www.randelshofer.ch
List<String> frameNames = getFrameNames();
if (!outputURL.endsWith(".avi")) outputURL = outputURL + ".avi";
Picture p = new Picture((String) frameNames.get(0));
try {
//Convert the URL into a filename
String filename = (new URL(outputURL)).getFile();
//Setup the output stream
AVIOutputStream AVIout = new AVIOutputStream(new File(filename), AVIOutputStream.VideoFormat.JPG);
AVIout.setVideoCompressionQuality(1);
AVIout.setFrameRate(frameRate);
AVIout.setVideoDimension(p.getWidth(), p.getHeight());
//Write each frame
for (int i = 0; i < frameNames.size(); i++) {
AVIout.writeFrame(new File(frameNames.get(i)));
}
//Close the output stream so the AVI has proper format
AVIout.close();
} catch (Exception e) {
}
}
/**
* Method to write the movie frames as quicktime
*/
public void writeQuicktime() {
JpegImagesToMovie imageToMovie = new JpegImagesToMovie();
List<String> frameNames = getFrameNames();
Picture p = new Picture((String) frameNames.get(0));
if (!outputURL.endsWith(".mov")) outputURL = outputURL + ".mov";
imageToMovie.doItQuicktime(p.getWidth(), p.getHeight(), frameRate, frameNames, outputURL);
}
public static void main(String[] args) {
MovieWriter writer = new MovieWriter("c:/Temp/testmovie/");
writer.writeQuicktime();
writer.writeAVI();
}
}
|
[
"public",
"class",
"MovieWriter",
"{",
"/**\r\n\t * the directory to read the frames from\r\n\t */",
"private",
"String",
"framesDir",
"=",
"null",
";",
"/**\r\n\t * the number of frames per second\r\n\t */",
"private",
"int",
"frameRate",
"=",
"16",
";",
"/**\r\n\t * the name of the movie file\r\n\t */",
"private",
"String",
"movieName",
"=",
"null",
";",
"/**\r\n\t * the output url for the movie\r\n\t */",
"private",
"String",
"outputURL",
"=",
"null",
";",
"/**\r\n\t * Constructor that takes no arguments\r\n\t */",
"public",
"MovieWriter",
"(",
")",
"{",
"framesDir",
"=",
"FileChooser",
".",
"pickADirectory",
"(",
")",
";",
"movieName",
"=",
"getMovieName",
"(",
")",
";",
"outputURL",
"=",
"getOutputURL",
"(",
")",
";",
"}",
"/**\r\n\t * Constructor that takes the directory that\r\n\t * has the frames\r\n\t *\r\n\t * @param dirPath the full path for the directory\r\n\t * that has the movie frames\r\n\t */",
"public",
"MovieWriter",
"(",
"String",
"dirPath",
")",
"{",
"framesDir",
"=",
"dirPath",
";",
"if",
"(",
"!",
"framesDir",
".",
"endsWith",
"(",
"File",
".",
"separator",
")",
"&&",
"!",
"framesDir",
".",
"endsWith",
"(",
"\"",
"/",
"\"",
")",
")",
"framesDir",
"+=",
"File",
".",
"separator",
";",
"movieName",
"=",
"getMovieName",
"(",
")",
";",
"outputURL",
"=",
"getOutputURL",
"(",
")",
";",
"}",
"/**\r\n\t * Constructor that takes the frame rate\r\n\t *\r\n\t * @param theFrameRate the number of frames per second\r\n\t */",
"public",
"MovieWriter",
"(",
"int",
"theFrameRate",
")",
"{",
"framesDir",
"=",
"FileChooser",
".",
"pickADirectory",
"(",
")",
";",
"frameRate",
"=",
"theFrameRate",
";",
"movieName",
"=",
"getMovieName",
"(",
")",
";",
"outputURL",
"=",
"getOutputURL",
"(",
")",
";",
"}",
"/**\r\n\t * Constructor that takes the frame rate and the\r\n\t * directory that the frames are stored in\r\n\t *\r\n\t * @param theFrameRate the number of frames per second\r\n\t * @param theFramesDir the directory where the frames are\r\n\t */",
"public",
"MovieWriter",
"(",
"int",
"theFrameRate",
",",
"String",
"theFramesDir",
")",
"{",
"this",
".",
"framesDir",
"=",
"theFramesDir",
";",
"if",
"(",
"!",
"framesDir",
".",
"endsWith",
"(",
"File",
".",
"separator",
")",
"&&",
"!",
"framesDir",
".",
"endsWith",
"(",
"\"",
"/",
"\"",
")",
")",
"framesDir",
"+=",
"File",
".",
"separator",
";",
"this",
".",
"frameRate",
"=",
"theFrameRate",
";",
"movieName",
"=",
"getMovieName",
"(",
")",
";",
"outputURL",
"=",
"getOutputURL",
"(",
")",
";",
"}",
"/**\r\n\t * Constructor that takes the directory with the frames\r\n\t * the frame rate, and the output url (dir,name,\r\n\t * and extendsion)\r\n\t *\r\n\t * @param theFramesDir the directory that holds the frame\r\n\t * @param theFrameRate the number of frames per second\r\n\t * @param theOutputURL the complete path name for the output\r\n\t * movie\r\n\t */",
"public",
"MovieWriter",
"(",
"String",
"theFramesDir",
",",
"int",
"theFrameRate",
",",
"String",
"theOutputURL",
")",
"{",
"this",
".",
"framesDir",
"=",
"theFramesDir",
";",
"if",
"(",
"!",
"framesDir",
".",
"endsWith",
"(",
"File",
".",
"separator",
")",
"&&",
"!",
"framesDir",
".",
"endsWith",
"(",
"\"",
"/",
"\"",
")",
")",
"framesDir",
"+=",
"File",
".",
"separator",
";",
"this",
".",
"frameRate",
"=",
"theFrameRate",
";",
"this",
".",
"outputURL",
"=",
"theOutputURL",
";",
"}",
"/**\r\n\t * Method to get the movie name from the directory\r\n\t * where the frames are stored\r\n\t *\r\n\t * @return the name of the movie (like movie1)\r\n\t */",
"private",
"String",
"getMovieName",
"(",
")",
"{",
"File",
"dir",
"=",
"new",
"File",
"(",
"framesDir",
")",
";",
"return",
"dir",
".",
"getName",
"(",
")",
";",
"}",
"/**\r\n\t * Method to create the output URL from the directory\r\n\t * the frames are stored in.\r\n\t *\r\n\t * @return the URL for the output movie file\r\n\t */",
"private",
"String",
"getOutputURL",
"(",
")",
"{",
"File",
"dir",
"=",
"null",
";",
"URL",
"myURL",
"=",
"null",
";",
"if",
"(",
"framesDir",
"!=",
"null",
")",
"{",
"try",
"{",
"dir",
"=",
"new",
"File",
"(",
"framesDir",
"+",
"movieName",
")",
";",
"myURL",
"=",
"dir",
".",
"toURI",
"(",
")",
".",
"toURL",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"ex",
")",
"{",
"}",
"}",
"return",
"myURL",
".",
"toString",
"(",
")",
".",
"replace",
"(",
"\"",
"%20",
"\"",
",",
"\"",
" ",
"\"",
")",
";",
"}",
"/**\r\n\t * Method to get the list of jpeg frames\r\n\t *\r\n\t * @return a list of full path names for the frames\r\n\t * of the movie\r\n\t */",
"public",
"List",
"<",
"String",
">",
"getFrameNames",
"(",
")",
"{",
"File",
"dir",
"=",
"new",
"File",
"(",
"framesDir",
")",
";",
"String",
"[",
"]",
"filesArray",
"=",
"dir",
".",
"list",
"(",
")",
";",
"List",
"<",
"String",
">",
"files",
"=",
"new",
"ArrayList",
"<",
"String",
">",
"(",
")",
";",
"long",
"lenFirst",
"=",
"0",
";",
"for",
"(",
"String",
"fileName",
":",
"filesArray",
")",
"{",
"if",
"(",
"fileName",
".",
"indexOf",
"(",
"\"",
".jpg",
"\"",
")",
">=",
"0",
")",
"{",
"File",
"f",
"=",
"new",
"File",
"(",
"framesDir",
"+",
"fileName",
")",
";",
"if",
"(",
"lenFirst",
"==",
"0",
"||",
"f",
".",
"length",
"(",
")",
">",
"(",
"lenFirst",
"/",
"2",
")",
")",
"{",
"try",
"{",
"BufferedImage",
"i",
"=",
"ImageIO",
".",
"read",
"(",
"f",
")",
";",
"files",
".",
"add",
"(",
"framesDir",
"+",
"fileName",
")",
";",
"}",
"catch",
"(",
"Exception",
"ex",
")",
"{",
"}",
"}",
"if",
"(",
"lenFirst",
"==",
"0",
")",
"lenFirst",
"=",
"f",
".",
"length",
"(",
")",
";",
"}",
"}",
"return",
"files",
";",
"}",
"/**\r\n\t * Method to write the movie frames in AVI format\r\n\t */",
"public",
"void",
"writeAVI",
"(",
")",
"{",
"/* JMF Code no longer functioned for writing AVIs.\r\n * Commented out and code below was written to use a \r\n * different AVI writing library.\r\n * BJD: 11-9-09\r\n *\r\n JpegImagesToMovie imageToMovie = new JpegImagesToMovie();\r\n List<String> frameNames = getFrameNames();\r\n Picture p = new Picture((String) frameNames.get(0));\r\n if(!outputURL.endsWith(\".avi\"))\r\n outputURL = outputURL + \".avi\";\r\n imageToMovie.doItAVI(p.getWidth(),p.getHeight(),\r\n frameRate,frameNames,outputURL);\r\n*/",
"List",
"<",
"String",
">",
"frameNames",
"=",
"getFrameNames",
"(",
")",
";",
"if",
"(",
"!",
"outputURL",
".",
"endsWith",
"(",
"\"",
".avi",
"\"",
")",
")",
"outputURL",
"=",
"outputURL",
"+",
"\"",
".avi",
"\"",
";",
"Picture",
"p",
"=",
"new",
"Picture",
"(",
"(",
"String",
")",
"frameNames",
".",
"get",
"(",
"0",
")",
")",
";",
"try",
"{",
"String",
"filename",
"=",
"(",
"new",
"URL",
"(",
"outputURL",
")",
")",
".",
"getFile",
"(",
")",
";",
"AVIOutputStream",
"AVIout",
"=",
"new",
"AVIOutputStream",
"(",
"new",
"File",
"(",
"filename",
")",
",",
"AVIOutputStream",
".",
"VideoFormat",
".",
"JPG",
")",
";",
"AVIout",
".",
"setVideoCompressionQuality",
"(",
"1",
")",
";",
"AVIout",
".",
"setFrameRate",
"(",
"frameRate",
")",
";",
"AVIout",
".",
"setVideoDimension",
"(",
"p",
".",
"getWidth",
"(",
")",
",",
"p",
".",
"getHeight",
"(",
")",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"frameNames",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"AVIout",
".",
"writeFrame",
"(",
"new",
"File",
"(",
"frameNames",
".",
"get",
"(",
"i",
")",
")",
")",
";",
"}",
"AVIout",
".",
"close",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"}",
"}",
"/**\r\n\t * Method to write the movie frames as quicktime\r\n\t */",
"public",
"void",
"writeQuicktime",
"(",
")",
"{",
"JpegImagesToMovie",
"imageToMovie",
"=",
"new",
"JpegImagesToMovie",
"(",
")",
";",
"List",
"<",
"String",
">",
"frameNames",
"=",
"getFrameNames",
"(",
")",
";",
"Picture",
"p",
"=",
"new",
"Picture",
"(",
"(",
"String",
")",
"frameNames",
".",
"get",
"(",
"0",
")",
")",
";",
"if",
"(",
"!",
"outputURL",
".",
"endsWith",
"(",
"\"",
".mov",
"\"",
")",
")",
"outputURL",
"=",
"outputURL",
"+",
"\"",
".mov",
"\"",
";",
"imageToMovie",
".",
"doItQuicktime",
"(",
"p",
".",
"getWidth",
"(",
")",
",",
"p",
".",
"getHeight",
"(",
")",
",",
"frameRate",
",",
"frameNames",
",",
"outputURL",
")",
";",
"}",
"public",
"static",
"void",
"main",
"(",
"String",
"[",
"]",
"args",
")",
"{",
"MovieWriter",
"writer",
"=",
"new",
"MovieWriter",
"(",
"\"",
"c:/Temp/testmovie/",
"\"",
")",
";",
"writer",
".",
"writeQuicktime",
"(",
")",
";",
"writer",
".",
"writeAVI",
"(",
")",
";",
"}",
"}"
] |
Class to write out an AVI or Quicktime movie from
a series of JPEG (jpg) frames in a directory
|
[
"Class",
"to",
"write",
"out",
"an",
"AVI",
"or",
"Quicktime",
"movie",
"from",
"a",
"series",
"of",
"JPEG",
"(",
"jpg",
")",
"frames",
"in",
"a",
"directory"
] |
[
"///////////////// fields ///////////////////////////\r",
"////////////////// constructors //////////////////////\r",
"//Makes sure framesDir ends with the file separator\r",
"//Makes sure framesDir ends with the file separator\r",
"//Makes sure framesDir ends with the file separator\r",
"/////////////////// methods //////////////////////////\r",
"//return myURL.toString();\r",
"// only continue if jpg picture\r",
"// check for imcomplete image\r",
"// image okay so far\r",
"// if problem reading don't add it\r",
"// The code below utilizes Werner Randelshofer's AVIOutputStream\r",
"// object to write an AVI movie from the list of frames. His code\r",
"// is shared under the Creative Commons Attribution License\r",
"// (see http://creativecommons.org/licenses/by/3.0/). More\r",
"// information about that code can be found in the AVIDemo.jar\r",
"// archive in the jars folder or at http://www.randelshofer.ch\r",
"//Convert the URL into a filename\r",
"//Setup the output stream\r",
"//Write each frame\r",
"//Close the output stream so the AVI has proper format\r"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 17
| 1,719
| 157
|
042a6bddea6c3dbb2c6679c6e6aafbf03adee8c5
|
Jesse1eung/accelerate
|
src/accelerate/state.py
|
[
"Apache-2.0"
] |
Python
|
AcceleratorState
|
This is a variation of a `singleton class <https://en.wikipedia.org/wiki/Singleton_pattern>`__ in the sense that
all instance of :obj:`AcceleratorState` share the same state, which is initialized on the first instantiation.
Attributes
- **device** (:obj:`torch.device`) -- The device to use.
- **distributed_type** (:obj:`~accelerate.state.DistributedType`) -- The type of distributed environment
currently in use.
- **num_processes** (:obj:`int`) -- The number of processes currently launched in parallel.
- **process_index** (:obj:`int`) -- The index of the current process.
- **local_process_index** (:obj:`int`) -- The index of the current process on the current server.
- **use_fp16** (:obj:`bool`) -- Whether or not the current script will use mixed precision.
|
This is a variation of a `singleton class `__ in the sense that
all instance of :obj:`AcceleratorState` share the same state, which is initialized on the first instantiation.
Attributes
|
[
"This",
"is",
"a",
"variation",
"of",
"a",
"`",
"singleton",
"class",
"`",
"__",
"in",
"the",
"sense",
"that",
"all",
"instance",
"of",
":",
"obj",
":",
"`",
"AcceleratorState",
"`",
"share",
"the",
"same",
"state",
"which",
"is",
"initialized",
"on",
"the",
"first",
"instantiation",
".",
"Attributes"
] |
class AcceleratorState:
"""
This is a variation of a `singleton class <https://en.wikipedia.org/wiki/Singleton_pattern>`__ in the sense that
all instance of :obj:`AcceleratorState` share the same state, which is initialized on the first instantiation.
Attributes
- **device** (:obj:`torch.device`) -- The device to use.
- **distributed_type** (:obj:`~accelerate.state.DistributedType`) -- The type of distributed environment
currently in use.
- **num_processes** (:obj:`int`) -- The number of processes currently launched in parallel.
- **process_index** (:obj:`int`) -- The index of the current process.
- **local_process_index** (:obj:`int`) -- The index of the current process on the current server.
- **use_fp16** (:obj:`bool`) -- Whether or not the current script will use mixed precision.
"""
_shared_state = {}
def __init__(self, fp16: bool = None, cpu: bool = False, _from_accelerator: bool = False):
self.__dict__ = self._shared_state
if not getattr(self, "initialized", False):
if not _from_accelerator:
raise ValueError(
"Please make sure to properly initialize your accelerator via `accelerator = Accelerator()` "
"before using any functionality from the `accelerate` library."
)
elif is_tpu_available() and not cpu:
self.distributed_type = DistributedType.TPU
self.num_processes = xm.xrt_world_size()
self.process_index = xm.get_ordinal()
self.local_process_index = xm.get_local_ordinal()
self.device = xm.xla_device()
self.use_fp16 = False
elif int(os.environ.get("LOCAL_RANK", -1)) != -1 and not cpu:
self.distributed_type = DistributedType.MULTI_GPU
if not torch.distributed.is_initialized():
torch.distributed.init_process_group(backend="nccl")
self.num_processes = torch.distributed.get_world_size()
self.process_index = torch.distributed.get_rank()
self.local_process_index = int(os.environ.get("LOCAL_RANK", -1))
self.device = torch.device("cuda", self.local_process_index)
torch.cuda.set_device(self.device)
self.use_fp16 = parse_flag_from_env("USE_FP16", False) if fp16 is None else fp16
else:
self.distributed_type = DistributedType.NO
self.num_processes = 1
self.process_index = self.local_process_index = 0
self.device = torch.device("cuda" if torch.cuda.is_available() and not cpu else "cpu")
self.use_fp16 = parse_flag_from_env("USE_FP16", False) if fp16 is None else fp16
self.initialized = True
def __repr__(self):
return (
f"Distributed environment: {self.distributed_type}\n"
f"Num processes: {self.num_processes}\n"
f"Process index: {self.process_index}\n"
f"Local process index: {self.local_process_index}\n"
f"Device: {self.device}\n"
f"Use FP16 precision: {self.use_fp16}\n"
)
|
[
"class",
"AcceleratorState",
":",
"_shared_state",
"=",
"{",
"}",
"def",
"__init__",
"(",
"self",
",",
"fp16",
":",
"bool",
"=",
"None",
",",
"cpu",
":",
"bool",
"=",
"False",
",",
"_from_accelerator",
":",
"bool",
"=",
"False",
")",
":",
"self",
".",
"__dict__",
"=",
"self",
".",
"_shared_state",
"if",
"not",
"getattr",
"(",
"self",
",",
"\"initialized\"",
",",
"False",
")",
":",
"if",
"not",
"_from_accelerator",
":",
"raise",
"ValueError",
"(",
"\"Please make sure to properly initialize your accelerator via `accelerator = Accelerator()` \"",
"\"before using any functionality from the `accelerate` library.\"",
")",
"elif",
"is_tpu_available",
"(",
")",
"and",
"not",
"cpu",
":",
"self",
".",
"distributed_type",
"=",
"DistributedType",
".",
"TPU",
"self",
".",
"num_processes",
"=",
"xm",
".",
"xrt_world_size",
"(",
")",
"self",
".",
"process_index",
"=",
"xm",
".",
"get_ordinal",
"(",
")",
"self",
".",
"local_process_index",
"=",
"xm",
".",
"get_local_ordinal",
"(",
")",
"self",
".",
"device",
"=",
"xm",
".",
"xla_device",
"(",
")",
"self",
".",
"use_fp16",
"=",
"False",
"elif",
"int",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"\"LOCAL_RANK\"",
",",
"-",
"1",
")",
")",
"!=",
"-",
"1",
"and",
"not",
"cpu",
":",
"self",
".",
"distributed_type",
"=",
"DistributedType",
".",
"MULTI_GPU",
"if",
"not",
"torch",
".",
"distributed",
".",
"is_initialized",
"(",
")",
":",
"torch",
".",
"distributed",
".",
"init_process_group",
"(",
"backend",
"=",
"\"nccl\"",
")",
"self",
".",
"num_processes",
"=",
"torch",
".",
"distributed",
".",
"get_world_size",
"(",
")",
"self",
".",
"process_index",
"=",
"torch",
".",
"distributed",
".",
"get_rank",
"(",
")",
"self",
".",
"local_process_index",
"=",
"int",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"\"LOCAL_RANK\"",
",",
"-",
"1",
")",
")",
"self",
".",
"device",
"=",
"torch",
".",
"device",
"(",
"\"cuda\"",
",",
"self",
".",
"local_process_index",
")",
"torch",
".",
"cuda",
".",
"set_device",
"(",
"self",
".",
"device",
")",
"self",
".",
"use_fp16",
"=",
"parse_flag_from_env",
"(",
"\"USE_FP16\"",
",",
"False",
")",
"if",
"fp16",
"is",
"None",
"else",
"fp16",
"else",
":",
"self",
".",
"distributed_type",
"=",
"DistributedType",
".",
"NO",
"self",
".",
"num_processes",
"=",
"1",
"self",
".",
"process_index",
"=",
"self",
".",
"local_process_index",
"=",
"0",
"self",
".",
"device",
"=",
"torch",
".",
"device",
"(",
"\"cuda\"",
"if",
"torch",
".",
"cuda",
".",
"is_available",
"(",
")",
"and",
"not",
"cpu",
"else",
"\"cpu\"",
")",
"self",
".",
"use_fp16",
"=",
"parse_flag_from_env",
"(",
"\"USE_FP16\"",
",",
"False",
")",
"if",
"fp16",
"is",
"None",
"else",
"fp16",
"self",
".",
"initialized",
"=",
"True",
"def",
"__repr__",
"(",
"self",
")",
":",
"return",
"(",
"f\"Distributed environment: {self.distributed_type}\\n\"",
"f\"Num processes: {self.num_processes}\\n\"",
"f\"Process index: {self.process_index}\\n\"",
"f\"Local process index: {self.local_process_index}\\n\"",
"f\"Device: {self.device}\\n\"",
"f\"Use FP16 precision: {self.use_fp16}\\n\"",
")"
] |
This is a variation of a `singleton class <https://en.wikipedia.org/wiki/Singleton_pattern>`__ in the sense that
all instance of :obj:`AcceleratorState` share the same state, which is initialized on the first instantiation.
|
[
"This",
"is",
"a",
"variation",
"of",
"a",
"`",
"singleton",
"class",
"<https",
":",
"//",
"en",
".",
"wikipedia",
".",
"org",
"/",
"wiki",
"/",
"Singleton_pattern",
">",
"`",
"__",
"in",
"the",
"sense",
"that",
"all",
"instance",
"of",
":",
"obj",
":",
"`",
"AcceleratorState",
"`",
"share",
"the",
"same",
"state",
"which",
"is",
"initialized",
"on",
"the",
"first",
"instantiation",
"."
] |
[
"\"\"\"\n This is a variation of a `singleton class <https://en.wikipedia.org/wiki/Singleton_pattern>`__ in the sense that\n all instance of :obj:`AcceleratorState` share the same state, which is initialized on the first instantiation.\n\n Attributes\n\n - **device** (:obj:`torch.device`) -- The device to use.\n - **distributed_type** (:obj:`~accelerate.state.DistributedType`) -- The type of distributed environment\n currently in use.\n - **num_processes** (:obj:`int`) -- The number of processes currently launched in parallel.\n - **process_index** (:obj:`int`) -- The index of the current process.\n - **local_process_index** (:obj:`int`) -- The index of the current process on the current server.\n - **use_fp16** (:obj:`bool`) -- Whether or not the current script will use mixed precision.\n \"\"\""
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 19
| 710
| 190
|
794c9338b5f45e96947e3d5884983ee24d44e9e8
|
timabell/ef-enum-to-lookup
|
EfEnumToLookup/LookupGenerator/EnumToLookup.cs
|
[
"MIT"
] |
C#
|
EnumToLookup
|
/// <summary>
/// Makes up for a missing feature in Entity Framework 6.1
/// Creates lookup tables and foreign key constraints based on the enums
/// used in your model.
/// Use the properties exposed to control behaviour.
/// Run <c>Apply</c> from your Seed method in either your database initializer
/// or your EF Migrations.
/// It is safe to run repeatedly, and will ensure enum values are kept in line
/// with your current code.
/// Source code: https://github.com/timabell/ef-enum-to-lookup
/// License: MIT
/// </summary>
|
Makes up for a missing feature in Entity Framework 6.1
Creates lookup tables and foreign key constraints based on the enums
used in your model.
Use the properties exposed to control behaviour.
Run Apply
|
[
"Makes",
"up",
"for",
"a",
"missing",
"feature",
"in",
"Entity",
"Framework",
"6",
".",
"1",
"Creates",
"lookup",
"tables",
"and",
"foreign",
"key",
"constraints",
"based",
"on",
"the",
"enums",
"used",
"in",
"your",
"model",
".",
"Use",
"the",
"properties",
"exposed",
"to",
"control",
"behaviour",
".",
"Run",
"Apply"
] |
public class EnumToLookup : IEnumToLookup
{
private readonly EnumParser _enumParser;
public EnumToLookup()
{
NameFieldLength = 255;
TableNamePrefix = "Enum_";
_enumParser = new EnumParser { SplitWords = true };
UseTransaction = true;
}
public bool SplitWords
{
set { _enumParser.SplitWords = value; }
get { return _enumParser.SplitWords; }
}
public int NameFieldLength { get; set; }
public string TableNamePrefix { get; set; }
public string TableNameSuffix { get; set; }
public bool UseTransaction { get; set; }
public void Apply(DbContext context)
{
var model = BuildModelFromContext(context);
var dbHandler = GetDbHandler();
dbHandler.Apply(model, (sql, parameters) => ExecuteSqlCommand(context, sql, parameters));
}
public string GenerateMigrationSql(DbContext context)
{
var model = BuildModelFromContext(context);
var dbHandler = GetDbHandler();
var sb = new StringBuilder();
sb.AppendLine("-- sql generated by https://github.com/timabell/ef-enum-to-lookup");
sb.AppendLine();
sb.Append(dbHandler.GenerateMigrationSql(model));
return sb.ToString();
}
private IDbHandler GetDbHandler()
{
IDbHandler dbHandler = new SqlServerHandler
{
NameFieldLength = NameFieldLength,
TableNamePrefix = TableNamePrefix,
TableNameSuffix = TableNameSuffix,
UseTransaction = UseTransaction,
};
return dbHandler;
}
private LookupDbModel BuildModelFromContext(DbContext context)
{
var enumReferences = FindEnumReferences(context);
var enums = enumReferences
.Select(r => r.EnumType)
.Distinct()
.OrderBy(r => r.Name)
.ToList();
var lookups = (
from enm in enums
select new LookupData
{
Name = enm.Name,
NumericType = enm.GetEnumUnderlyingType(),
Values = _enumParser.GetLookupValues(enm),
}).ToList();
var model = new LookupDbModel
{
Lookups = lookups,
References = enumReferences,
};
return model;
}
private static int ExecuteSqlCommand(DbContext context, string sql, IEnumerable<SqlParameter> parameters = null)
{
if (parameters == null)
{
return context.Database.ExecuteSqlCommand(sql);
}
return context.Database.ExecuteSqlCommand(sql, parameters.Cast<object>().ToArray());
}
internal IList<EnumReference> FindEnumReferences(DbContext context)
{
var metadataWorkspace = ((IObjectContextAdapter)context).ObjectContext.MetadataWorkspace;
var metadataHandler = new MetadataHandler();
return metadataHandler.FindEnumReferences(metadataWorkspace);
}
internal IList<PropertyInfo> FindDbSets(Type contextType)
{
return contextType.GetProperties()
.Where(p => p.PropertyType.IsGenericType
&& p.PropertyType.GetGenericTypeDefinition() == typeof(DbSet<>))
.ToList();
}
internal IList<PropertyInfo> FindEnums(Type type)
{
return type.GetProperties()
.Where(p => p.PropertyType.IsEnum
|| (p.PropertyType.IsGenericType && p.PropertyType.GenericTypeArguments.First().IsEnum))
.ToList();
}
}
|
[
"public",
"class",
"EnumToLookup",
":",
"IEnumToLookup",
"{",
"private",
"readonly",
"EnumParser",
"_enumParser",
";",
"public",
"EnumToLookup",
"(",
")",
"{",
"NameFieldLength",
"=",
"255",
";",
"TableNamePrefix",
"=",
"\"",
"Enum_",
"\"",
";",
"_enumParser",
"=",
"new",
"EnumParser",
"{",
"SplitWords",
"=",
"true",
"}",
";",
"UseTransaction",
"=",
"true",
";",
"}",
"public",
"bool",
"SplitWords",
"{",
"set",
"{",
"_enumParser",
".",
"SplitWords",
"=",
"value",
";",
"}",
"get",
"{",
"return",
"_enumParser",
".",
"SplitWords",
";",
"}",
"}",
"public",
"int",
"NameFieldLength",
"{",
"get",
";",
"set",
";",
"}",
"public",
"string",
"TableNamePrefix",
"{",
"get",
";",
"set",
";",
"}",
"public",
"string",
"TableNameSuffix",
"{",
"get",
";",
"set",
";",
"}",
"public",
"bool",
"UseTransaction",
"{",
"get",
";",
"set",
";",
"}",
"public",
"void",
"Apply",
"(",
"DbContext",
"context",
")",
"{",
"var",
"model",
"=",
"BuildModelFromContext",
"(",
"context",
")",
";",
"var",
"dbHandler",
"=",
"GetDbHandler",
"(",
")",
";",
"dbHandler",
".",
"Apply",
"(",
"model",
",",
"(",
"sql",
",",
"parameters",
")",
"=>",
"ExecuteSqlCommand",
"(",
"context",
",",
"sql",
",",
"parameters",
")",
")",
";",
"}",
"public",
"string",
"GenerateMigrationSql",
"(",
"DbContext",
"context",
")",
"{",
"var",
"model",
"=",
"BuildModelFromContext",
"(",
"context",
")",
";",
"var",
"dbHandler",
"=",
"GetDbHandler",
"(",
")",
";",
"var",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"sb",
".",
"AppendLine",
"(",
"\"",
"-- sql generated by https://github.com/timabell/ef-enum-to-lookup",
"\"",
")",
";",
"sb",
".",
"AppendLine",
"(",
")",
";",
"sb",
".",
"Append",
"(",
"dbHandler",
".",
"GenerateMigrationSql",
"(",
"model",
")",
")",
";",
"return",
"sb",
".",
"ToString",
"(",
")",
";",
"}",
"private",
"IDbHandler",
"GetDbHandler",
"(",
")",
"{",
"IDbHandler",
"dbHandler",
"=",
"new",
"SqlServerHandler",
"{",
"NameFieldLength",
"=",
"NameFieldLength",
",",
"TableNamePrefix",
"=",
"TableNamePrefix",
",",
"TableNameSuffix",
"=",
"TableNameSuffix",
",",
"UseTransaction",
"=",
"UseTransaction",
",",
"}",
";",
"return",
"dbHandler",
";",
"}",
"private",
"LookupDbModel",
"BuildModelFromContext",
"(",
"DbContext",
"context",
")",
"{",
"var",
"enumReferences",
"=",
"FindEnumReferences",
"(",
"context",
")",
";",
"var",
"enums",
"=",
"enumReferences",
".",
"Select",
"(",
"r",
"=>",
"r",
".",
"EnumType",
")",
".",
"Distinct",
"(",
")",
".",
"OrderBy",
"(",
"r",
"=>",
"r",
".",
"Name",
")",
".",
"ToList",
"(",
")",
";",
"var",
"lookups",
"=",
"(",
"from",
"enm",
"in",
"enums",
"select",
"new",
"LookupData",
"{",
"Name",
"=",
"enm",
".",
"Name",
",",
"NumericType",
"=",
"enm",
".",
"GetEnumUnderlyingType",
"(",
")",
",",
"Values",
"=",
"_enumParser",
".",
"GetLookupValues",
"(",
"enm",
")",
",",
"}",
")",
".",
"ToList",
"(",
")",
";",
"var",
"model",
"=",
"new",
"LookupDbModel",
"{",
"Lookups",
"=",
"lookups",
",",
"References",
"=",
"enumReferences",
",",
"}",
";",
"return",
"model",
";",
"}",
"private",
"static",
"int",
"ExecuteSqlCommand",
"(",
"DbContext",
"context",
",",
"string",
"sql",
",",
"IEnumerable",
"<",
"SqlParameter",
">",
"parameters",
"=",
"null",
")",
"{",
"if",
"(",
"parameters",
"==",
"null",
")",
"{",
"return",
"context",
".",
"Database",
".",
"ExecuteSqlCommand",
"(",
"sql",
")",
";",
"}",
"return",
"context",
".",
"Database",
".",
"ExecuteSqlCommand",
"(",
"sql",
",",
"parameters",
".",
"Cast",
"<",
"object",
">",
"(",
")",
".",
"ToArray",
"(",
")",
")",
";",
"}",
"internal",
"IList",
"<",
"EnumReference",
">",
"FindEnumReferences",
"(",
"DbContext",
"context",
")",
"{",
"var",
"metadataWorkspace",
"=",
"(",
"(",
"IObjectContextAdapter",
")",
"context",
")",
".",
"ObjectContext",
".",
"MetadataWorkspace",
";",
"var",
"metadataHandler",
"=",
"new",
"MetadataHandler",
"(",
")",
";",
"return",
"metadataHandler",
".",
"FindEnumReferences",
"(",
"metadataWorkspace",
")",
";",
"}",
"internal",
"IList",
"<",
"PropertyInfo",
">",
"FindDbSets",
"(",
"Type",
"contextType",
")",
"{",
"return",
"contextType",
".",
"GetProperties",
"(",
")",
".",
"Where",
"(",
"p",
"=>",
"p",
".",
"PropertyType",
".",
"IsGenericType",
"&&",
"p",
".",
"PropertyType",
".",
"GetGenericTypeDefinition",
"(",
")",
"==",
"typeof",
"(",
"DbSet",
"<",
">",
")",
")",
".",
"ToList",
"(",
")",
";",
"}",
"internal",
"IList",
"<",
"PropertyInfo",
">",
"FindEnums",
"(",
"Type",
"type",
")",
"{",
"return",
"type",
".",
"GetProperties",
"(",
")",
".",
"Where",
"(",
"p",
"=>",
"p",
".",
"PropertyType",
".",
"IsEnum",
"||",
"(",
"p",
".",
"PropertyType",
".",
"IsGenericType",
"&&",
"p",
".",
"PropertyType",
".",
"GenericTypeArguments",
".",
"First",
"(",
")",
".",
"IsEnum",
")",
")",
".",
"ToList",
"(",
")",
";",
"}",
"}"
] |
Makes up for a missing feature in Entity Framework 6.1
Creates lookup tables and foreign key constraints based on the enums
used in your model.
|
[
"Makes",
"up",
"for",
"a",
"missing",
"feature",
"in",
"Entity",
"Framework",
"6",
".",
"1",
"Creates",
"lookup",
"tables",
"and",
"foreign",
"key",
"constraints",
"based",
"on",
"the",
"enums",
"used",
"in",
"your",
"model",
"."
] |
[
"// set default behaviour, can be overridden by setting properties on object before calling Apply()",
"/// <summary>",
"/// If set to true (default) enum names will have spaces inserted between",
"/// PascalCase words, e.g. enum SomeValue is stored as \"Some Value\".",
"/// </summary>",
"/// <summary>",
"/// The size of the Name field that will be added to the generated lookup tables.",
"/// Adjust to suit your data if required, defaults to 255.",
"/// </summary>",
"/// <summary>",
"/// Prefix to add to all the generated tables to separate help group them together",
"/// and make them stand out as different from other tables.",
"/// Defaults to \"Enum_\" set to null or \"\" to not have any prefix.",
"/// </summary>",
"/// <summary>",
"/// Suffix to add to all the generated tables to separate help group them together",
"/// and make them stand out as different from other tables.",
"/// Defaults to \"\" set to null or \"\" to not have any suffix.",
"/// </summary>",
"/// <summary>",
"/// Whether to run the changes inside a database transaction.",
"/// </summary>",
"/// <summary>",
"/// Create any missing lookup tables,",
"/// enforce values in the lookup tables",
"/// by way of a T-SQL MERGE",
"/// </summary>",
"/// <param name=\"context\">EF Database context to search for enum references,",
"/// context.Database.ExecuteSqlCommand() is used to apply changes.</param>",
"/// <summary>",
"/// Rather than applying the changes directly to the database as Apply() does,",
"/// this will give you a copy of the sql that would have been run to bring the",
"/// database up to date. This is useful for generating migration scripts or",
"/// for environments where your application isn't allowed to make schema changes;",
"/// in this scenario you can generate the sql in advance and apply it separately.",
"/// </summary>",
"/// <param name=\"context\">EF Database context to search for enum references</param>",
"/// <returns>SQL statements needed to update the target database</returns>",
"// todo: support MariaDb etc. Issue #16",
"// recurse through dbsets and references finding anything that uses an enum",
"// for the list of enums generate and missing tables"
] |
[
{
"param": "IEnumToLookup",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "IEnumToLookup",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 20
| 743
| 126
|
8aa32fa2e37b404a66479167090dbb30a29316c4
|
SamueleDelMoro/ACTAM.Project2122-TraningGame
|
node_modules/tone/build/esm/core/context/ToneAudioBuffers.js
|
[
"MIT"
] |
JavaScript
|
ToneAudioBuffers
|
/**
* A data structure for holding multiple buffers in a Map-like datastructure.
*
* @example
* const pianoSamples = new Tone.ToneAudioBuffers({
* A1: "https://tonejs.github.io/audio/casio/A1.mp3",
* A2: "https://tonejs.github.io/audio/casio/A2.mp3",
* }, () => {
* const player = new Tone.Player().toDestination();
* // play one of the samples when they all load
* player.buffer = pianoSamples.get("A2");
* player.start();
* });
* @example
* // To pass in additional parameters in the second parameter
* const buffers = new Tone.ToneAudioBuffers({
* urls: {
* A1: "A1.mp3",
* A2: "A2.mp3",
* },
* onload: () => console.log("loaded"),
* baseUrl: "https://tonejs.github.io/audio/casio/"
* });
* @category Core
*/
|
A data structure for holding multiple buffers in a Map-like datastructure.
|
[
"A",
"data",
"structure",
"for",
"holding",
"multiple",
"buffers",
"in",
"a",
"Map",
"-",
"like",
"datastructure",
"."
] |
class ToneAudioBuffers extends Tone {
constructor() {
super();
this.name = "ToneAudioBuffers";
/**
* All of the buffers
*/
this._buffers = new Map();
/**
* Keep track of the number of loaded buffers
*/
this._loadingCount = 0;
const options = optionsFromArguments(ToneAudioBuffers.getDefaults(), arguments, ["urls", "onload", "baseUrl"], "urls");
this.baseUrl = options.baseUrl;
// add each one
Object.keys(options.urls).forEach(name => {
this._loadingCount++;
const url = options.urls[name];
this.add(name, url, this._bufferLoaded.bind(this, options.onload), options.onerror);
});
}
static getDefaults() {
return {
baseUrl: "",
onerror: noOp,
onload: noOp,
urls: {},
};
}
/**
* True if the buffers object has a buffer by that name.
* @param name The key or index of the buffer.
*/
has(name) {
return this._buffers.has(name.toString());
}
/**
* Get a buffer by name. If an array was loaded,
* then use the array index.
* @param name The key or index of the buffer.
*/
get(name) {
assert(this.has(name), `ToneAudioBuffers has no buffer named: ${name}`);
return this._buffers.get(name.toString());
}
/**
* A buffer was loaded. decrement the counter.
*/
_bufferLoaded(callback) {
this._loadingCount--;
if (this._loadingCount === 0 && callback) {
callback();
}
}
/**
* If the buffers are loaded or not
*/
get loaded() {
return Array.from(this._buffers).every(([_, buffer]) => buffer.loaded);
}
/**
* Add a buffer by name and url to the Buffers
* @param name A unique name to give the buffer
* @param url Either the url of the bufer, or a buffer which will be added with the given name.
* @param callback The callback to invoke when the url is loaded.
* @param onerror Invoked if the buffer can't be loaded
*/
add(name, url, callback = noOp, onerror = noOp) {
if (isString(url)) {
this._buffers.set(name.toString(), new ToneAudioBuffer(this.baseUrl + url, callback, onerror));
}
else {
this._buffers.set(name.toString(), new ToneAudioBuffer(url, callback, onerror));
}
return this;
}
dispose() {
super.dispose();
this._buffers.forEach(buffer => buffer.dispose());
this._buffers.clear();
return this;
}
}
|
[
"class",
"ToneAudioBuffers",
"extends",
"Tone",
"{",
"constructor",
"(",
")",
"{",
"super",
"(",
")",
";",
"this",
".",
"name",
"=",
"\"ToneAudioBuffers\"",
";",
"this",
".",
"_buffers",
"=",
"new",
"Map",
"(",
")",
";",
"this",
".",
"_loadingCount",
"=",
"0",
";",
"const",
"options",
"=",
"optionsFromArguments",
"(",
"ToneAudioBuffers",
".",
"getDefaults",
"(",
")",
",",
"arguments",
",",
"[",
"\"urls\"",
",",
"\"onload\"",
",",
"\"baseUrl\"",
"]",
",",
"\"urls\"",
")",
";",
"this",
".",
"baseUrl",
"=",
"options",
".",
"baseUrl",
";",
"Object",
".",
"keys",
"(",
"options",
".",
"urls",
")",
".",
"forEach",
"(",
"name",
"=>",
"{",
"this",
".",
"_loadingCount",
"++",
";",
"const",
"url",
"=",
"options",
".",
"urls",
"[",
"name",
"]",
";",
"this",
".",
"add",
"(",
"name",
",",
"url",
",",
"this",
".",
"_bufferLoaded",
".",
"bind",
"(",
"this",
",",
"options",
".",
"onload",
")",
",",
"options",
".",
"onerror",
")",
";",
"}",
")",
";",
"}",
"static",
"getDefaults",
"(",
")",
"{",
"return",
"{",
"baseUrl",
":",
"\"\"",
",",
"onerror",
":",
"noOp",
",",
"onload",
":",
"noOp",
",",
"urls",
":",
"{",
"}",
",",
"}",
";",
"}",
"has",
"(",
"name",
")",
"{",
"return",
"this",
".",
"_buffers",
".",
"has",
"(",
"name",
".",
"toString",
"(",
")",
")",
";",
"}",
"get",
"(",
"name",
")",
"{",
"assert",
"(",
"this",
".",
"has",
"(",
"name",
")",
",",
"`",
"${",
"name",
"}",
"`",
")",
";",
"return",
"this",
".",
"_buffers",
".",
"get",
"(",
"name",
".",
"toString",
"(",
")",
")",
";",
"}",
"_bufferLoaded",
"(",
"callback",
")",
"{",
"this",
".",
"_loadingCount",
"--",
";",
"if",
"(",
"this",
".",
"_loadingCount",
"===",
"0",
"&&",
"callback",
")",
"{",
"callback",
"(",
")",
";",
"}",
"}",
"get",
"loaded",
"(",
")",
"{",
"return",
"Array",
".",
"from",
"(",
"this",
".",
"_buffers",
")",
".",
"every",
"(",
"(",
"[",
"_",
",",
"buffer",
"]",
")",
"=>",
"buffer",
".",
"loaded",
")",
";",
"}",
"add",
"(",
"name",
",",
"url",
",",
"callback",
"=",
"noOp",
",",
"onerror",
"=",
"noOp",
")",
"{",
"if",
"(",
"isString",
"(",
"url",
")",
")",
"{",
"this",
".",
"_buffers",
".",
"set",
"(",
"name",
".",
"toString",
"(",
")",
",",
"new",
"ToneAudioBuffer",
"(",
"this",
".",
"baseUrl",
"+",
"url",
",",
"callback",
",",
"onerror",
")",
")",
";",
"}",
"else",
"{",
"this",
".",
"_buffers",
".",
"set",
"(",
"name",
".",
"toString",
"(",
")",
",",
"new",
"ToneAudioBuffer",
"(",
"url",
",",
"callback",
",",
"onerror",
")",
")",
";",
"}",
"return",
"this",
";",
"}",
"dispose",
"(",
")",
"{",
"super",
".",
"dispose",
"(",
")",
";",
"this",
".",
"_buffers",
".",
"forEach",
"(",
"buffer",
"=>",
"buffer",
".",
"dispose",
"(",
")",
")",
";",
"this",
".",
"_buffers",
".",
"clear",
"(",
")",
";",
"return",
"this",
";",
"}",
"}"
] |
A data structure for holding multiple buffers in a Map-like datastructure.
|
[
"A",
"data",
"structure",
"for",
"holding",
"multiple",
"buffers",
"in",
"a",
"Map",
"-",
"like",
"datastructure",
"."
] |
[
"/**\n * All of the buffers\n */",
"/**\n * Keep track of the number of loaded buffers\n */",
"// add each one",
"/**\n * True if the buffers object has a buffer by that name.\n * @param name The key or index of the buffer.\n */",
"/**\n * Get a buffer by name. If an array was loaded,\n * then use the array index.\n * @param name The key or index of the buffer.\n */",
"/**\n * A buffer was loaded. decrement the counter.\n */",
"/**\n * If the buffers are loaded or not\n */",
"/**\n * Add a buffer by name and url to the Buffers\n * @param name A unique name to give the buffer\n * @param url Either the url of the bufer, or a buffer which will be added with the given name.\n * @param callback The callback to invoke when the url is loaded.\n * @param onerror Invoked if the buffer can't be loaded\n */"
] |
[
{
"param": "Tone",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "Tone",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 16
| 609
| 214
|
5bd8c26ed23e193abaf2abbf8ebcb5fc17394b2a
|
gfis/xtrans
|
src/main/java/org/teherba/xtrans/parse/ParseTable.java
|
[
"Apache-2.0"
] |
Java
|
ParseTable
|
/** Maps from the parser's state and an input token to a
* parser action and some additional info:
* <ul>
* <li>for a shift action: the successor state</li>
* <li>for a reduction: the {@link Production production} which was applied</li>
* <li>for accept: nothing</li>
* </ul>
* Besides an array for the productions, this class stores the parser's state
* table in a hashmap of {@link Item}s, which have the properties of {@link Token}s
* which are relevant for the parser's decision.
* <p>
* Besides the bean access methods, there is the {@link #delta} method which
* is used in the parser's loop, and a {@link #load} method which reads
* the grammar resp. the parse table from a database table.
* @author Dr. Georg Fischer
*/
|
Maps from the parser's state and an input token to a
parser action and some additional info:
for a shift action: the successor state
for a reduction: the Production production which was applied
for accept: nothing
Besides an array for the productions, this class stores the parser's state
table in a hashmap of Items, which have the properties of Tokens
which are relevant for the parser's decision.
Besides the bean access methods, there is the #delta method which
is used in the parser's loop, and a #load method which reads
the grammar resp. the parse table from a database table.
@author Dr. Georg Fischer
|
[
"Maps",
"from",
"the",
"parser",
"'",
"s",
"state",
"and",
"an",
"input",
"token",
"to",
"a",
"parser",
"action",
"and",
"some",
"additional",
"info",
":",
"for",
"a",
"shift",
"action",
":",
"the",
"successor",
"state",
"for",
"a",
"reduction",
":",
"the",
"Production",
"production",
"which",
"was",
"applied",
"for",
"accept",
":",
"nothing",
"Besides",
"an",
"array",
"for",
"the",
"productions",
"this",
"class",
"stores",
"the",
"parser",
"'",
"s",
"state",
"table",
"in",
"a",
"hashmap",
"of",
"Items",
"which",
"have",
"the",
"properties",
"of",
"Tokens",
"which",
"are",
"relevant",
"for",
"the",
"parser",
"'",
"s",
"decision",
".",
"Besides",
"the",
"bean",
"access",
"methods",
"there",
"is",
"the",
"#delta",
"method",
"which",
"is",
"used",
"in",
"the",
"parser",
"'",
"s",
"loop",
"and",
"a",
"#load",
"method",
"which",
"reads",
"the",
"grammar",
"resp",
".",
"the",
"parse",
"table",
"from",
"a",
"database",
"table",
".",
"@author",
"Dr",
".",
"Georg",
"Fischer"
] |
public class ParseTable {
public final static String CVSID = "@(#) $Id: ParseTable.java 798 2011-09-10 15:30:05Z gfis $";
/** log4j logger (category) */
private Logger log;
/** Table which maps from (state, item) to (action, nextInfo) */
private HashMap <String, Item> items;
/** Array which maps a production number to a production */
private ArrayList<Production> productions;
/** Array with sublists of transformation rules */
private ArrayList<Transformation> transformations;
/** current state of the push-down parser algorithm */
private int state;
/** Stack of items accumulated so far for open nonterminals */
private Stack<Item> stack;
/** No-args Constructor
*/
public ParseTable() {
log = LogManager.getLogger(ParseTable.class.getName());
items = new HashMap <String, Item>(256);
productions = new ArrayList<Production >(256);
productions.add(null); // ignore element [0] = production for axiom = bop program eop;
} // Constructor()
/** Loads the parser tables from database tables.
* @param grammarName name of the grammar which is to be used for parsing
* @return debugging message
*/
public String load(String grammarName) {
String message = "loaded ";
try {
Dbat dbat = new Dbat();
dbat.initialize(Configuration.CLI_CALL);
Connection con = dbat.getConfiguration().openConnection();
ResultSet resultSet = null;
int rowCount = 0;
Item item = new Item();
PreparedStatement itemStmt = con.prepareStatement(item .getSelectStatement());
itemStmt.clearParameters();
itemStmt.setString(1, grammarName);
resultSet = itemStmt.executeQuery();
rowCount = 0;
while (resultSet.next()) {
item = new Item();
item.fill(resultSet);
items.put(item.key(), item);
rowCount ++;
} // while fetching
resultSet.close();
itemStmt.close();
con.commit();
message = String.valueOf(rowCount) + " items " + message;
Production prod = new Production();
PreparedStatement prodStmt = con.prepareStatement(prod.getSelectStatement());
prodStmt.clearParameters();
prodStmt.setString(1, grammarName);
resultSet = prodStmt.executeQuery();
rowCount = 0;
while (resultSet.next()) {
prod = new Production();
prod.fill(resultSet);
productions.add(prod.key(), prod);
rowCount ++;
} // while fetching
resultSet.close();
prodStmt.close();
con.commit();
message = "ParseTable: " + String.valueOf(rowCount) + " productions, " + message;
Transformation trans = new Transformation();
PreparedStatement transStmt = con.prepareStatement(trans.getSelectStatement());
transStmt.clearParameters();
transStmt.setString(1, grammarName);
resultSet = transStmt.executeQuery();
rowCount = 0;
while (resultSet.next()) {
trans = new Transformation();
trans.fill(resultSet);
transformations.add(trans.key(), trans);
rowCount ++;
} // while fetching
resultSet.close();
transStmt.close();
con.commit();
message = "ParseTable: " + String.valueOf(rowCount) + " transformations, " + message;
dbat.getConfiguration().closeConnection();
} catch (Exception exc) {
log.error(exc.getMessage(), exc);
}
return message + " from grammar \"" + grammarName + "\"";
} // load
/** Initializes the {@link #state} and the {@link #stack}.
*/
public void initParser() {
stack = new Stack<Item>();
state = 1; // initial state
} // initParser
/** Performs the elementary mapping of the push-down parser
* from a pair of ({@link #state}, token) to the next parser action
* and corresponding additional information.
* Adjusts the {@link #state} and the {@link #stack}.
* @param token next input token to be fed into the parsing process.
* @return null Item
*/
public Item delta(Token token) {
Item result = null;
return result;
} // delta
/** Main program, prints SQL statements for the creation and/or filling
* of the database tables.
* @param args commandline arguments
* <pre>
* usage:\tjava org.teherba.xtrans.ParseTable [-c|-ci|-i]
* </pre>
*/
public static void main(String args[]) {
Item item = new Item ();
Production prod = new Production ();
Transformation trans = new Transformation ();
int iarg = 0;
if (iarg >= args.length) {
System.err.println("usage:\tjava org.teherba.xtrans.parse.ParseTable [-c|-ci|-i]\n");
} else {
String options = args[iarg ++];
if (options.indexOf("c") >= 0) { // print DDL
System.out.print(item .getDDL());
System.out.print(prod .getDDL());
System.out.print(trans.getDDL());
} // c
if (options.indexOf("i") >= 0) { // print INSERT statements for "ident" grammar
// not yet implemented
} // i
} // >= 1 argument
} // main
}
|
[
"public",
"class",
"ParseTable",
"{",
"public",
"final",
"static",
"String",
"CVSID",
"=",
"\"",
"@(#) $Id: ParseTable.java 798 2011-09-10 15:30:05Z gfis $",
"\"",
";",
"/** log4j logger (category) */",
"private",
"Logger",
"log",
";",
"/** Table which maps from (state, item) to (action, nextInfo) */",
"private",
"HashMap",
"<",
"String",
",",
"Item",
">",
"items",
";",
"/** Array which maps a production number to a production */",
"private",
"ArrayList",
"<",
"Production",
">",
"productions",
";",
"/** Array with sublists of transformation rules */",
"private",
"ArrayList",
"<",
"Transformation",
">",
"transformations",
";",
"/** current state of the push-down parser algorithm */",
"private",
"int",
"state",
";",
"/** Stack of items accumulated so far for open nonterminals */",
"private",
"Stack",
"<",
"Item",
">",
"stack",
";",
"/** No-args Constructor\n */",
"public",
"ParseTable",
"(",
")",
"{",
"log",
"=",
"LogManager",
".",
"getLogger",
"(",
"ParseTable",
".",
"class",
".",
"getName",
"(",
")",
")",
";",
"items",
"=",
"new",
"HashMap",
"<",
"String",
",",
"Item",
">",
"(",
"256",
")",
";",
"productions",
"=",
"new",
"ArrayList",
"<",
"Production",
">",
"(",
"256",
")",
";",
"productions",
".",
"add",
"(",
"null",
")",
";",
"}",
"/** Loads the parser tables from database tables.\n * @param grammarName name of the grammar which is to be used for parsing\n * @return debugging message\n */",
"public",
"String",
"load",
"(",
"String",
"grammarName",
")",
"{",
"String",
"message",
"=",
"\"",
"loaded ",
"\"",
";",
"try",
"{",
"Dbat",
"dbat",
"=",
"new",
"Dbat",
"(",
")",
";",
"dbat",
".",
"initialize",
"(",
"Configuration",
".",
"CLI_CALL",
")",
";",
"Connection",
"con",
"=",
"dbat",
".",
"getConfiguration",
"(",
")",
".",
"openConnection",
"(",
")",
";",
"ResultSet",
"resultSet",
"=",
"null",
";",
"int",
"rowCount",
"=",
"0",
";",
"Item",
"item",
"=",
"new",
"Item",
"(",
")",
";",
"PreparedStatement",
"itemStmt",
"=",
"con",
".",
"prepareStatement",
"(",
"item",
".",
"getSelectStatement",
"(",
")",
")",
";",
"itemStmt",
".",
"clearParameters",
"(",
")",
";",
"itemStmt",
".",
"setString",
"(",
"1",
",",
"grammarName",
")",
";",
"resultSet",
"=",
"itemStmt",
".",
"executeQuery",
"(",
")",
";",
"rowCount",
"=",
"0",
";",
"while",
"(",
"resultSet",
".",
"next",
"(",
")",
")",
"{",
"item",
"=",
"new",
"Item",
"(",
")",
";",
"item",
".",
"fill",
"(",
"resultSet",
")",
";",
"items",
".",
"put",
"(",
"item",
".",
"key",
"(",
")",
",",
"item",
")",
";",
"rowCount",
"++",
";",
"}",
"resultSet",
".",
"close",
"(",
")",
";",
"itemStmt",
".",
"close",
"(",
")",
";",
"con",
".",
"commit",
"(",
")",
";",
"message",
"=",
"String",
".",
"valueOf",
"(",
"rowCount",
")",
"+",
"\"",
" items ",
"\"",
"+",
"message",
";",
"Production",
"prod",
"=",
"new",
"Production",
"(",
")",
";",
"PreparedStatement",
"prodStmt",
"=",
"con",
".",
"prepareStatement",
"(",
"prod",
".",
"getSelectStatement",
"(",
")",
")",
";",
"prodStmt",
".",
"clearParameters",
"(",
")",
";",
"prodStmt",
".",
"setString",
"(",
"1",
",",
"grammarName",
")",
";",
"resultSet",
"=",
"prodStmt",
".",
"executeQuery",
"(",
")",
";",
"rowCount",
"=",
"0",
";",
"while",
"(",
"resultSet",
".",
"next",
"(",
")",
")",
"{",
"prod",
"=",
"new",
"Production",
"(",
")",
";",
"prod",
".",
"fill",
"(",
"resultSet",
")",
";",
"productions",
".",
"add",
"(",
"prod",
".",
"key",
"(",
")",
",",
"prod",
")",
";",
"rowCount",
"++",
";",
"}",
"resultSet",
".",
"close",
"(",
")",
";",
"prodStmt",
".",
"close",
"(",
")",
";",
"con",
".",
"commit",
"(",
")",
";",
"message",
"=",
"\"",
"ParseTable: ",
"\"",
"+",
"String",
".",
"valueOf",
"(",
"rowCount",
")",
"+",
"\"",
" productions, ",
"\"",
"+",
"message",
";",
"Transformation",
"trans",
"=",
"new",
"Transformation",
"(",
")",
";",
"PreparedStatement",
"transStmt",
"=",
"con",
".",
"prepareStatement",
"(",
"trans",
".",
"getSelectStatement",
"(",
")",
")",
";",
"transStmt",
".",
"clearParameters",
"(",
")",
";",
"transStmt",
".",
"setString",
"(",
"1",
",",
"grammarName",
")",
";",
"resultSet",
"=",
"transStmt",
".",
"executeQuery",
"(",
")",
";",
"rowCount",
"=",
"0",
";",
"while",
"(",
"resultSet",
".",
"next",
"(",
")",
")",
"{",
"trans",
"=",
"new",
"Transformation",
"(",
")",
";",
"trans",
".",
"fill",
"(",
"resultSet",
")",
";",
"transformations",
".",
"add",
"(",
"trans",
".",
"key",
"(",
")",
",",
"trans",
")",
";",
"rowCount",
"++",
";",
"}",
"resultSet",
".",
"close",
"(",
")",
";",
"transStmt",
".",
"close",
"(",
")",
";",
"con",
".",
"commit",
"(",
")",
";",
"message",
"=",
"\"",
"ParseTable: ",
"\"",
"+",
"String",
".",
"valueOf",
"(",
"rowCount",
")",
"+",
"\"",
" transformations, ",
"\"",
"+",
"message",
";",
"dbat",
".",
"getConfiguration",
"(",
")",
".",
"closeConnection",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"exc",
")",
"{",
"log",
".",
"error",
"(",
"exc",
".",
"getMessage",
"(",
")",
",",
"exc",
")",
";",
"}",
"return",
"message",
"+",
"\"",
" from grammar ",
"\\\"",
"\"",
"+",
"grammarName",
"+",
"\"",
"\\\"",
"\"",
";",
"}",
"/** Initializes the {@link #state} and the {@link #stack}.\n */",
"public",
"void",
"initParser",
"(",
")",
"{",
"stack",
"=",
"new",
"Stack",
"<",
"Item",
">",
"(",
")",
";",
"state",
"=",
"1",
";",
"}",
"/** Performs the elementary mapping of the push-down parser\n * from a pair of ({@link #state}, token) to the next parser action \n * and corresponding additional information.\n * Adjusts the {@link #state} and the {@link #stack}.\n * @param token next input token to be fed into the parsing process.\n * @return null Item\n */",
"public",
"Item",
"delta",
"(",
"Token",
"token",
")",
"{",
"Item",
"result",
"=",
"null",
";",
"return",
"result",
";",
"}",
"/** Main program, prints SQL statements for the creation and/or filling\n * of the database tables.\n * @param args commandline arguments\n * <pre>\n * usage:\\tjava org.teherba.xtrans.ParseTable [-c|-ci|-i]\n * </pre>\n */",
"public",
"static",
"void",
"main",
"(",
"String",
"args",
"[",
"]",
")",
"{",
"Item",
"item",
"=",
"new",
"Item",
"(",
")",
";",
"Production",
"prod",
"=",
"new",
"Production",
"(",
")",
";",
"Transformation",
"trans",
"=",
"new",
"Transformation",
"(",
")",
";",
"int",
"iarg",
"=",
"0",
";",
"if",
"(",
"iarg",
">=",
"args",
".",
"length",
")",
"{",
"System",
".",
"err",
".",
"println",
"(",
"\"",
"usage:",
"\\t",
"java org.teherba.xtrans.parse.ParseTable [-c|-ci|-i]",
"\\n",
"\"",
")",
";",
"}",
"else",
"{",
"String",
"options",
"=",
"args",
"[",
"iarg",
"++",
"]",
";",
"if",
"(",
"options",
".",
"indexOf",
"(",
"\"",
"c",
"\"",
")",
">=",
"0",
")",
"{",
"System",
".",
"out",
".",
"print",
"(",
"item",
".",
"getDDL",
"(",
")",
")",
";",
"System",
".",
"out",
".",
"print",
"(",
"prod",
".",
"getDDL",
"(",
")",
")",
";",
"System",
".",
"out",
".",
"print",
"(",
"trans",
".",
"getDDL",
"(",
")",
")",
";",
"}",
"if",
"(",
"options",
".",
"indexOf",
"(",
"\"",
"i",
"\"",
")",
">=",
"0",
")",
"{",
"}",
"}",
"}",
"}"
] |
Maps from the parser's state and an input token to a
parser action and some additional info:
<ul>
<li>for a shift action: the successor state</li>
<li>for a reduction: the {@link Production production} which was applied</li>
<li>for accept: nothing</li>
</ul>
Besides an array for the productions, this class stores the parser's state
table in a hashmap of {@link Item}s, which have the properties of {@link Token}s
which are relevant for the parser's decision.
|
[
"Maps",
"from",
"the",
"parser",
"'",
"s",
"state",
"and",
"an",
"input",
"token",
"to",
"a",
"parser",
"action",
"and",
"some",
"additional",
"info",
":",
"<ul",
">",
"<li",
">",
"for",
"a",
"shift",
"action",
":",
"the",
"successor",
"state<",
"/",
"li",
">",
"<li",
">",
"for",
"a",
"reduction",
":",
"the",
"{",
"@link",
"Production",
"production",
"}",
"which",
"was",
"applied<",
"/",
"li",
">",
"<li",
">",
"for",
"accept",
":",
"nothing<",
"/",
"li",
">",
"<",
"/",
"ul",
">",
"Besides",
"an",
"array",
"for",
"the",
"productions",
"this",
"class",
"stores",
"the",
"parser",
"'",
"s",
"state",
"table",
"in",
"a",
"hashmap",
"of",
"{",
"@link",
"Item",
"}",
"s",
"which",
"have",
"the",
"properties",
"of",
"{",
"@link",
"Token",
"}",
"s",
"which",
"are",
"relevant",
"for",
"the",
"parser",
"'",
"s",
"decision",
"."
] |
[
"// ignore element [0] = production for axiom = bop program eop;",
"// Constructor()",
"// while fetching",
"// while fetching",
"// while fetching",
"// load",
"// initial state",
"// initParser",
"// delta",
"// print DDL",
"// c",
"// print INSERT statements for \"ident\" grammar",
"// not yet implemented",
"// i",
"// >= 1 argument",
"// main"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 14
| 1,177
| 201
|
db670d35b2da29ec94f28aa4898d084f571d1bfb
|
google-cloud-sdk-unofficial/google-cloud-sdk
|
lib/googlecloudsdk/third_party/gapic_clients/logging_v2/services/logging_service_v2/pagers.py
|
[
"Apache-2.0"
] |
Python
|
ListLogsPager
|
A pager for iterating through ``list_logs`` requests.
This class thinly wraps an initial
:class:`googlecloudsdk.third_party.gapic_clients.logging_v2.types.ListLogsResponse` object, and
provides an ``__iter__`` method to iterate through its
``log_names`` field.
If there are more pages, the ``__iter__`` method will make additional
``ListLogs`` requests and continue to iterate
through the ``log_names`` field on the
corresponding responses.
All the usual :class:`googlecloudsdk.third_party.gapic_clients.logging_v2.types.ListLogsResponse`
attributes are available on the pager. If multiple requests are made, only
the most recent response is retained, and thus used for attribute lookup.
|
A pager for iterating through ``list_logs`` requests.
This class thinly wraps an initial
|
[
"A",
"pager",
"for",
"iterating",
"through",
"`",
"`",
"list_logs",
"`",
"`",
"requests",
".",
"This",
"class",
"thinly",
"wraps",
"an",
"initial"
] |
class ListLogsPager:
"""A pager for iterating through ``list_logs`` requests.
This class thinly wraps an initial
:class:`googlecloudsdk.third_party.gapic_clients.logging_v2.types.ListLogsResponse` object, and
provides an ``__iter__`` method to iterate through its
``log_names`` field.
If there are more pages, the ``__iter__`` method will make additional
``ListLogs`` requests and continue to iterate
through the ``log_names`` field on the
corresponding responses.
All the usual :class:`googlecloudsdk.third_party.gapic_clients.logging_v2.types.ListLogsResponse`
attributes are available on the pager. If multiple requests are made, only
the most recent response is retained, and thus used for attribute lookup.
"""
def __init__(self,
method: Callable[..., logging.ListLogsResponse],
request: logging.ListLogsRequest,
response: logging.ListLogsResponse,
*,
metadata: Sequence[Tuple[str, str]] = ()):
"""Instantiate the pager.
Args:
method (Callable): The method that was originally called, and
which instantiated this pager.
request (googlecloudsdk.third_party.gapic_clients.logging_v2.types.ListLogsRequest):
The initial request object.
response (googlecloudsdk.third_party.gapic_clients.logging_v2.types.ListLogsResponse):
The initial response object.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = logging.ListLogsRequest(request)
self._response = response
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
return getattr(self._response, name)
@property
def pages(self) -> Iterable[logging.ListLogsResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
self._response = self._method(self._request, metadata=self._metadata)
yield self._response
def __iter__(self) -> Iterable[str]:
for page in self.pages:
yield from page.log_names
def __repr__(self) -> str:
return '{0}<{1!r}>'.format(self.__class__.__name__, self._response)
|
[
"class",
"ListLogsPager",
":",
"def",
"__init__",
"(",
"self",
",",
"method",
":",
"Callable",
"[",
"...",
",",
"logging",
".",
"ListLogsResponse",
"]",
",",
"request",
":",
"logging",
".",
"ListLogsRequest",
",",
"response",
":",
"logging",
".",
"ListLogsResponse",
",",
"*",
",",
"metadata",
":",
"Sequence",
"[",
"Tuple",
"[",
"str",
",",
"str",
"]",
"]",
"=",
"(",
")",
")",
":",
"\"\"\"Instantiate the pager.\n\n Args:\n method (Callable): The method that was originally called, and\n which instantiated this pager.\n request (googlecloudsdk.third_party.gapic_clients.logging_v2.types.ListLogsRequest):\n The initial request object.\n response (googlecloudsdk.third_party.gapic_clients.logging_v2.types.ListLogsResponse):\n The initial response object.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n \"\"\"",
"self",
".",
"_method",
"=",
"method",
"self",
".",
"_request",
"=",
"logging",
".",
"ListLogsRequest",
"(",
"request",
")",
"self",
".",
"_response",
"=",
"response",
"self",
".",
"_metadata",
"=",
"metadata",
"def",
"__getattr__",
"(",
"self",
",",
"name",
":",
"str",
")",
"->",
"Any",
":",
"return",
"getattr",
"(",
"self",
".",
"_response",
",",
"name",
")",
"@",
"property",
"def",
"pages",
"(",
"self",
")",
"->",
"Iterable",
"[",
"logging",
".",
"ListLogsResponse",
"]",
":",
"yield",
"self",
".",
"_response",
"while",
"self",
".",
"_response",
".",
"next_page_token",
":",
"self",
".",
"_request",
".",
"page_token",
"=",
"self",
".",
"_response",
".",
"next_page_token",
"self",
".",
"_response",
"=",
"self",
".",
"_method",
"(",
"self",
".",
"_request",
",",
"metadata",
"=",
"self",
".",
"_metadata",
")",
"yield",
"self",
".",
"_response",
"def",
"__iter__",
"(",
"self",
")",
"->",
"Iterable",
"[",
"str",
"]",
":",
"for",
"page",
"in",
"self",
".",
"pages",
":",
"yield",
"from",
"page",
".",
"log_names",
"def",
"__repr__",
"(",
"self",
")",
"->",
"str",
":",
"return",
"'{0}<{1!r}>'",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"self",
".",
"_response",
")"
] |
A pager for iterating through ``list_logs`` requests.
|
[
"A",
"pager",
"for",
"iterating",
"through",
"`",
"`",
"list_logs",
"`",
"`",
"requests",
"."
] |
[
"\"\"\"A pager for iterating through ``list_logs`` requests.\n\n This class thinly wraps an initial\n :class:`googlecloudsdk.third_party.gapic_clients.logging_v2.types.ListLogsResponse` object, and\n provides an ``__iter__`` method to iterate through its\n ``log_names`` field.\n\n If there are more pages, the ``__iter__`` method will make additional\n ``ListLogs`` requests and continue to iterate\n through the ``log_names`` field on the\n corresponding responses.\n\n All the usual :class:`googlecloudsdk.third_party.gapic_clients.logging_v2.types.ListLogsResponse`\n attributes are available on the pager. If multiple requests are made, only\n the most recent response is retained, and thus used for attribute lookup.\n \"\"\"",
"\"\"\"Instantiate the pager.\n\n Args:\n method (Callable): The method that was originally called, and\n which instantiated this pager.\n request (googlecloudsdk.third_party.gapic_clients.logging_v2.types.ListLogsRequest):\n The initial request object.\n response (googlecloudsdk.third_party.gapic_clients.logging_v2.types.ListLogsResponse):\n The initial response object.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n \"\"\""
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": [
{
"identifier": "class",
"docstring": "`googlecloudsdk.third_party.gapic_clients.logging_v2.types.ListLogsResponse` object, and\nprovides an ``__iter__`` method to iterate through its\n``log_names`` field.\n\nIf there are more pages, the ``__iter__`` method will make additional\n``ListLogs`` requests and continue to iterate\nthrough the ``log_names`` field on the\ncorresponding responses.\n\nAll the usual :class:`googlecloudsdk.third_party.gapic_clients.logging_v2.types.ListLogsResponse`\nattributes are available on the pager. If multiple requests are made, only\nthe most recent response is retained, and thus used for attribute lookup.",
"docstring_tokens": [
"`",
"googlecloudsdk",
".",
"third_party",
".",
"gapic_clients",
".",
"logging_v2",
".",
"types",
".",
"ListLogsResponse",
"`",
"object",
"and",
"provides",
"an",
"`",
"`",
"__iter__",
"`",
"`",
"method",
"to",
"iterate",
"through",
"its",
"`",
"`",
"log_names",
"`",
"`",
"field",
".",
"If",
"there",
"are",
"more",
"pages",
"the",
"`",
"`",
"__iter__",
"`",
"`",
"method",
"will",
"make",
"additional",
"`",
"`",
"ListLogs",
"`",
"`",
"requests",
"and",
"continue",
"to",
"iterate",
"through",
"the",
"`",
"`",
"log_names",
"`",
"`",
"field",
"on",
"the",
"corresponding",
"responses",
".",
"All",
"the",
"usual",
":",
"class",
":",
"`",
"googlecloudsdk",
".",
"third_party",
".",
"gapic_clients",
".",
"logging_v2",
".",
"types",
".",
"ListLogsResponse",
"`",
"attributes",
"are",
"available",
"on",
"the",
"pager",
".",
"If",
"multiple",
"requests",
"are",
"made",
"only",
"the",
"most",
"recent",
"response",
"is",
"retained",
"and",
"thus",
"used",
"for",
"attribute",
"lookup",
"."
]
}
]
}
| false
| 14
| 514
| 167
|
d2905db2163f0dbb24710ff9e581f8e0c7311565
|
chriswbartley/monoensemble
|
monoensemble/mono_gradient_boosting.py
|
[
"BSD-3-Clause"
] |
Python
|
ConstrainedLogisticRegression
|
A bounds constrained logistic regression with solution offset.
Required to enable ``coef_calc_type``='logistic' option for
``MonoGradientBoostingClassifier`` - because sci-kit learn
``LogisticRegression`` does not allow bounds constraints or solution
offset. It is included here to reduce dependencies.
This is a simple implementation of logistic regression with L2
regularisation, bounds constraints on the coefficients, and the ability
to accept an offset on the solution. It is solved using the scipy
conjugate gradient Newton method ``fmin_tnc``.
Parameters
----------
C : float, 0 < C <= 1.0
Empirical error weight, inverse of lambda (regularisation strength).
fit_intercept : boolean
True to fit an intercept.
random_state : random_state
Random seed.
solver : 'newton-cg'
Uses scipy.opt.fmin_tnc (only implemented option)
incr_feats : array-like
The one-based array indices of the columns in X that should only have
a monotone increasing impact on the resulting class.
decr_feats : array-like
The one-based array indices of the columns in X that should only have
a monotone decreasing impact on the resulting class.
regularise_intercept : boolean
True to regularise the intercept.
standardize : boolean
True to standardise the predictors before regression. Prevents bias
due to regularisation scale.
penalty : string, optional (default='l2')
The regularisation penalty. 'l1' is not guaranteed to work very well
because the newton solver relies on smoothness.
|
A bounds constrained logistic regression with solution offset.
This is a simple implementation of logistic regression with L2
regularisation, bounds constraints on the coefficients, and the ability
to accept an offset on the solution. It is solved using the scipy
conjugate gradient Newton method ``fmin_tnc``.
Parameters
C : float, 0 < C <= 1.0
Empirical error weight, inverse of lambda (regularisation strength).
fit_intercept : boolean
True to fit an intercept.
solver : 'newton-cg'
Uses scipy.opt.fmin_tnc (only implemented option)
incr_feats : array-like
The one-based array indices of the columns in X that should only have
a monotone increasing impact on the resulting class.
decr_feats : array-like
The one-based array indices of the columns in X that should only have
a monotone decreasing impact on the resulting class.
regularise_intercept : boolean
True to regularise the intercept.
standardize : boolean
True to standardise the predictors before regression. Prevents bias
due to regularisation scale.
penalty : string, optional (default='l2')
The regularisation penalty. 'l1' is not guaranteed to work very well
because the newton solver relies on smoothness.
|
[
"A",
"bounds",
"constrained",
"logistic",
"regression",
"with",
"solution",
"offset",
".",
"This",
"is",
"a",
"simple",
"implementation",
"of",
"logistic",
"regression",
"with",
"L2",
"regularisation",
"bounds",
"constraints",
"on",
"the",
"coefficients",
"and",
"the",
"ability",
"to",
"accept",
"an",
"offset",
"on",
"the",
"solution",
".",
"It",
"is",
"solved",
"using",
"the",
"scipy",
"conjugate",
"gradient",
"Newton",
"method",
"`",
"`",
"fmin_tnc",
"`",
"`",
".",
"Parameters",
"C",
":",
"float",
"0",
"<",
"C",
"<",
"=",
"1",
".",
"0",
"Empirical",
"error",
"weight",
"inverse",
"of",
"lambda",
"(",
"regularisation",
"strength",
")",
".",
"fit_intercept",
":",
"boolean",
"True",
"to",
"fit",
"an",
"intercept",
".",
"solver",
":",
"'",
"newton",
"-",
"cg",
"'",
"Uses",
"scipy",
".",
"opt",
".",
"fmin_tnc",
"(",
"only",
"implemented",
"option",
")",
"incr_feats",
":",
"array",
"-",
"like",
"The",
"one",
"-",
"based",
"array",
"indices",
"of",
"the",
"columns",
"in",
"X",
"that",
"should",
"only",
"have",
"a",
"monotone",
"increasing",
"impact",
"on",
"the",
"resulting",
"class",
".",
"decr_feats",
":",
"array",
"-",
"like",
"The",
"one",
"-",
"based",
"array",
"indices",
"of",
"the",
"columns",
"in",
"X",
"that",
"should",
"only",
"have",
"a",
"monotone",
"decreasing",
"impact",
"on",
"the",
"resulting",
"class",
".",
"regularise_intercept",
":",
"boolean",
"True",
"to",
"regularise",
"the",
"intercept",
".",
"standardize",
":",
"boolean",
"True",
"to",
"standardise",
"the",
"predictors",
"before",
"regression",
".",
"Prevents",
"bias",
"due",
"to",
"regularisation",
"scale",
".",
"penalty",
":",
"string",
"optional",
"(",
"default",
"=",
"'",
"l2",
"'",
")",
"The",
"regularisation",
"penalty",
".",
"'",
"l1",
"'",
"is",
"not",
"guaranteed",
"to",
"work",
"very",
"well",
"because",
"the",
"newton",
"solver",
"relies",
"on",
"smoothness",
"."
] |
class ConstrainedLogisticRegression:
"""A bounds constrained logistic regression with solution offset.
Required to enable ``coef_calc_type``='logistic' option for
``MonoGradientBoostingClassifier`` - because sci-kit learn
``LogisticRegression`` does not allow bounds constraints or solution
offset. It is included here to reduce dependencies.
This is a simple implementation of logistic regression with L2
regularisation, bounds constraints on the coefficients, and the ability
to accept an offset on the solution. It is solved using the scipy
conjugate gradient Newton method ``fmin_tnc``.
Parameters
----------
C : float, 0 < C <= 1.0
Empirical error weight, inverse of lambda (regularisation strength).
fit_intercept : boolean
True to fit an intercept.
random_state : random_state
Random seed.
solver : 'newton-cg'
Uses scipy.opt.fmin_tnc (only implemented option)
incr_feats : array-like
The one-based array indices of the columns in X that should only have
a monotone increasing impact on the resulting class.
decr_feats : array-like
The one-based array indices of the columns in X that should only have
a monotone decreasing impact on the resulting class.
regularise_intercept : boolean
True to regularise the intercept.
standardize : boolean
True to standardise the predictors before regression. Prevents bias
due to regularisation scale.
penalty : string, optional (default='l2')
The regularisation penalty. 'l1' is not guaranteed to work very well
because the newton solver relies on smoothness.
"""
def __init__(self, C=1.0, fit_intercept=True, random_state=None,
solver='newton-cg', incr_feats=[], decr_feats=[],
regularise_intercept=False, standardize=False, penalty='l2'):
self.fit_intercept = fit_intercept
self.random_state = random_state
self.solver = solver
self.C = C
self.incr_feats = np.asarray(incr_feats)
self.decr_feats = np.asarray(decr_feats)
self.has_mt_feats = len(incr_feats) > 0 or len(decr_feats) > 0
self.regularise_intercept = regularise_intercept \
if self.fit_intercept else False
self.standardize = standardize
self.penalty = penalty
def fit(self, X, y, sample_weight=None, offset=None):
"""Fit the gradient boosting model.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Training vectors, where n_samples is the number of samples
and n_features is the number of features.
y : array-like, shape = [n_samples]
Target values (integers in classification, real numbers in
regression)
For classification, labels must correspond to classes.
sample_weight : array-like, shape = [n_samples] or None
Sample weights. If None, then samples are equally weighted. Splits
that would create child nodes with net zero or negative weight are
ignored while searching for a split in each node. In the case of
classification, splits are also ignored if they would result in any
single class carrying a negative weight in either child node.
offset : array-like, shape = [n_samples] (optional)
The solution offset for each training point.
Returns
-------
self : object
Returns self.
"""
self.classes_ = np.sort(np.unique(y))
if sample_weight is None:
sample_weight = np.ones(len(y))
sample_weight = np.ravel(sample_weight)
X_ = X.copy()
y = np.ravel(y)
y[y == 0] = -1
if self.standardize:
stds = np.sqrt(
np.average(
(X_ -
np.average(
X_,
axis=0,
weights=sample_weight))**2,
axis=0,
weights=sample_weight)) # Fast and numerically precise
X_[:, stds != 0] = X_[:, stds != 0] / stds[stds != 0]
regularise_intercept_ = self.regularise_intercept \
if self.fit_intercept else True
# Solve
if self.solver == 'newton-cg':
coef_limits = [
(0 if j in self.incr_feats -
1 else None,
0 if j in self.decr_feats -
1 else None) for j in np.arange(
X_.shape[1])]
coef = nnlr(
X_,
y,
sample_weight,
self.C,
coef_limits,
regularise_intercept_,
1. if self.penalty == 'l2' else 0.,
self.fit_intercept,
offset)
if self.fit_intercept:
self.intercept_ = np.asarray([coef[-1]])
self.coef_ = np.asarray([coef[0:len(coef) - 1]])
else:
self.intercept_ = np.asarray([0.])
self.coef_ = np.asarray([coef])
elif self.solver == 'two-pass':
pass
if self.standardize:
self.coef_[0][stds != 0] = self.coef_[
0][stds != 0] / stds[stds != 0]
def predict(self, X):
"""Predict class or regression value for X.
For a classification model, the predicted class for each sample in X is
returned. For a regression model, the predicted value based on X is
returned.
Parameters
----------
X : array-like or sparse matrix of shape = [n_samples, n_features]
The input samples. Internally, it will be converted to
``dtype=np.float32`` and if a sparse matrix is provided
to a sparse ``csr_matrix``.
check_input : boolean, (default=True)
Allow to bypass several input checking.
Don't use this parameter unless you know what you do.
Returns
-------
y : array of shape = [n_samples] or [n_samples, n_outputs]
The predicted classes, or the predict values.
"""
proba = self.predict_proba(X)
return self.classes_.take(np.argmax(proba, axis=1), axis=0)
def predict_proba(self, X):
"""Probability estimates.
The returned estimates for all classes are ordered by the
label of classes.
For a multi_class problem, if multi_class is set to be "multinomial"
the softmax function is used to find the predicted probability of
each class.
Else use a one-vs-rest approach, i.e calculate the probability
of each class assuming it to be positive using the logistic function.
and normalize these values across all the classes.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Returns
-------
T : array-like, shape = [n_samples, n_classes]
Returns the probability of the sample for each class in the model,
where classes are ordered as they are in ``self.classes_``.
"""
if not hasattr(self, "coef_"):
raise NotFittedError("Call fit before prediction")
prob1 = 1. / \
(1 + np.exp(np.dot(self.coef_, -X.T).reshape(-1, 1) -
self.intercept_))
probs = np.hstack([1 - prob1, prob1])
return probs
def decision_function(self, X):
"""Predict confidence scores for samples.
The confidence score for a sample is the signed distance of that
sample to the hyperplane.
Parameters
----------
X : {array-like, sparse matrix}, shape = (n_samples, n_features)
Samples.
Returns
-------
array, shape=(n_samples,) if n_classes == 2 else (n_samples, n_classes)
Confidence scores per (sample, class) combination. In the binary
case, confidence score for self.classes_[1] where >0 means this
class would be predicted.
"""
if not hasattr(self, 'coef_') or self.coef_ is None:
raise NotFittedError("This %(name)s instance is not fitted "
"yet" % {'name': type(self).__name__})
n_features = self.coef_.shape[1]
if X.shape[1] != n_features:
raise ValueError("X has %d features per sample; expecting %d"
% (X.shape[1], n_features))
scores = safe_sparse_dot(X, self.coef_.T,
dense_output=True) + self.intercept_
return scores.ravel() if scores.shape[1] == 1 else scores
def predict_log_proba(self, X):
"""Log of probability estimates.
The returned estimates for all classes are ordered by the
label of classes.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Returns
-------
T : array-like, shape = [n_samples, n_classes]
Returns the log-probability of the sample for each class in the
model, where classes are ordered as they are in ``self.classes_``.
"""
return np.log(self.predict_proba(X))
|
[
"class",
"ConstrainedLogisticRegression",
":",
"def",
"__init__",
"(",
"self",
",",
"C",
"=",
"1.0",
",",
"fit_intercept",
"=",
"True",
",",
"random_state",
"=",
"None",
",",
"solver",
"=",
"'newton-cg'",
",",
"incr_feats",
"=",
"[",
"]",
",",
"decr_feats",
"=",
"[",
"]",
",",
"regularise_intercept",
"=",
"False",
",",
"standardize",
"=",
"False",
",",
"penalty",
"=",
"'l2'",
")",
":",
"self",
".",
"fit_intercept",
"=",
"fit_intercept",
"self",
".",
"random_state",
"=",
"random_state",
"self",
".",
"solver",
"=",
"solver",
"self",
".",
"C",
"=",
"C",
"self",
".",
"incr_feats",
"=",
"np",
".",
"asarray",
"(",
"incr_feats",
")",
"self",
".",
"decr_feats",
"=",
"np",
".",
"asarray",
"(",
"decr_feats",
")",
"self",
".",
"has_mt_feats",
"=",
"len",
"(",
"incr_feats",
")",
">",
"0",
"or",
"len",
"(",
"decr_feats",
")",
">",
"0",
"self",
".",
"regularise_intercept",
"=",
"regularise_intercept",
"if",
"self",
".",
"fit_intercept",
"else",
"False",
"self",
".",
"standardize",
"=",
"standardize",
"self",
".",
"penalty",
"=",
"penalty",
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
",",
"sample_weight",
"=",
"None",
",",
"offset",
"=",
"None",
")",
":",
"\"\"\"Fit the gradient boosting model.\n\n Parameters\n ----------\n X : array-like, shape = [n_samples, n_features]\n Training vectors, where n_samples is the number of samples\n and n_features is the number of features.\n\n y : array-like, shape = [n_samples]\n Target values (integers in classification, real numbers in\n regression)\n For classification, labels must correspond to classes.\n\n sample_weight : array-like, shape = [n_samples] or None\n Sample weights. If None, then samples are equally weighted. Splits\n that would create child nodes with net zero or negative weight are\n ignored while searching for a split in each node. In the case of\n classification, splits are also ignored if they would result in any\n single class carrying a negative weight in either child node.\n\n offset : array-like, shape = [n_samples] (optional)\n The solution offset for each training point.\n\n Returns\n -------\n self : object\n Returns self.\n \"\"\"",
"self",
".",
"classes_",
"=",
"np",
".",
"sort",
"(",
"np",
".",
"unique",
"(",
"y",
")",
")",
"if",
"sample_weight",
"is",
"None",
":",
"sample_weight",
"=",
"np",
".",
"ones",
"(",
"len",
"(",
"y",
")",
")",
"sample_weight",
"=",
"np",
".",
"ravel",
"(",
"sample_weight",
")",
"X_",
"=",
"X",
".",
"copy",
"(",
")",
"y",
"=",
"np",
".",
"ravel",
"(",
"y",
")",
"y",
"[",
"y",
"==",
"0",
"]",
"=",
"-",
"1",
"if",
"self",
".",
"standardize",
":",
"stds",
"=",
"np",
".",
"sqrt",
"(",
"np",
".",
"average",
"(",
"(",
"X_",
"-",
"np",
".",
"average",
"(",
"X_",
",",
"axis",
"=",
"0",
",",
"weights",
"=",
"sample_weight",
")",
")",
"**",
"2",
",",
"axis",
"=",
"0",
",",
"weights",
"=",
"sample_weight",
")",
")",
"X_",
"[",
":",
",",
"stds",
"!=",
"0",
"]",
"=",
"X_",
"[",
":",
",",
"stds",
"!=",
"0",
"]",
"/",
"stds",
"[",
"stds",
"!=",
"0",
"]",
"regularise_intercept_",
"=",
"self",
".",
"regularise_intercept",
"if",
"self",
".",
"fit_intercept",
"else",
"True",
"if",
"self",
".",
"solver",
"==",
"'newton-cg'",
":",
"coef_limits",
"=",
"[",
"(",
"0",
"if",
"j",
"in",
"self",
".",
"incr_feats",
"-",
"1",
"else",
"None",
",",
"0",
"if",
"j",
"in",
"self",
".",
"decr_feats",
"-",
"1",
"else",
"None",
")",
"for",
"j",
"in",
"np",
".",
"arange",
"(",
"X_",
".",
"shape",
"[",
"1",
"]",
")",
"]",
"coef",
"=",
"nnlr",
"(",
"X_",
",",
"y",
",",
"sample_weight",
",",
"self",
".",
"C",
",",
"coef_limits",
",",
"regularise_intercept_",
",",
"1.",
"if",
"self",
".",
"penalty",
"==",
"'l2'",
"else",
"0.",
",",
"self",
".",
"fit_intercept",
",",
"offset",
")",
"if",
"self",
".",
"fit_intercept",
":",
"self",
".",
"intercept_",
"=",
"np",
".",
"asarray",
"(",
"[",
"coef",
"[",
"-",
"1",
"]",
"]",
")",
"self",
".",
"coef_",
"=",
"np",
".",
"asarray",
"(",
"[",
"coef",
"[",
"0",
":",
"len",
"(",
"coef",
")",
"-",
"1",
"]",
"]",
")",
"else",
":",
"self",
".",
"intercept_",
"=",
"np",
".",
"asarray",
"(",
"[",
"0.",
"]",
")",
"self",
".",
"coef_",
"=",
"np",
".",
"asarray",
"(",
"[",
"coef",
"]",
")",
"elif",
"self",
".",
"solver",
"==",
"'two-pass'",
":",
"pass",
"if",
"self",
".",
"standardize",
":",
"self",
".",
"coef_",
"[",
"0",
"]",
"[",
"stds",
"!=",
"0",
"]",
"=",
"self",
".",
"coef_",
"[",
"0",
"]",
"[",
"stds",
"!=",
"0",
"]",
"/",
"stds",
"[",
"stds",
"!=",
"0",
"]",
"def",
"predict",
"(",
"self",
",",
"X",
")",
":",
"\"\"\"Predict class or regression value for X.\n For a classification model, the predicted class for each sample in X is\n returned. For a regression model, the predicted value based on X is\n returned.\n Parameters\n ----------\n X : array-like or sparse matrix of shape = [n_samples, n_features]\n The input samples. Internally, it will be converted to\n ``dtype=np.float32`` and if a sparse matrix is provided\n to a sparse ``csr_matrix``.\n check_input : boolean, (default=True)\n Allow to bypass several input checking.\n Don't use this parameter unless you know what you do.\n Returns\n -------\n y : array of shape = [n_samples] or [n_samples, n_outputs]\n The predicted classes, or the predict values.\n \"\"\"",
"proba",
"=",
"self",
".",
"predict_proba",
"(",
"X",
")",
"return",
"self",
".",
"classes_",
".",
"take",
"(",
"np",
".",
"argmax",
"(",
"proba",
",",
"axis",
"=",
"1",
")",
",",
"axis",
"=",
"0",
")",
"def",
"predict_proba",
"(",
"self",
",",
"X",
")",
":",
"\"\"\"Probability estimates.\n The returned estimates for all classes are ordered by the\n label of classes.\n For a multi_class problem, if multi_class is set to be \"multinomial\"\n the softmax function is used to find the predicted probability of\n each class.\n Else use a one-vs-rest approach, i.e calculate the probability\n of each class assuming it to be positive using the logistic function.\n and normalize these values across all the classes.\n Parameters\n ----------\n X : array-like, shape = [n_samples, n_features]\n Returns\n -------\n T : array-like, shape = [n_samples, n_classes]\n Returns the probability of the sample for each class in the model,\n where classes are ordered as they are in ``self.classes_``.\n \"\"\"",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"coef_\"",
")",
":",
"raise",
"NotFittedError",
"(",
"\"Call fit before prediction\"",
")",
"prob1",
"=",
"1.",
"/",
"(",
"1",
"+",
"np",
".",
"exp",
"(",
"np",
".",
"dot",
"(",
"self",
".",
"coef_",
",",
"-",
"X",
".",
"T",
")",
".",
"reshape",
"(",
"-",
"1",
",",
"1",
")",
"-",
"self",
".",
"intercept_",
")",
")",
"probs",
"=",
"np",
".",
"hstack",
"(",
"[",
"1",
"-",
"prob1",
",",
"prob1",
"]",
")",
"return",
"probs",
"def",
"decision_function",
"(",
"self",
",",
"X",
")",
":",
"\"\"\"Predict confidence scores for samples.\n The confidence score for a sample is the signed distance of that\n sample to the hyperplane.\n Parameters\n ----------\n X : {array-like, sparse matrix}, shape = (n_samples, n_features)\n Samples.\n Returns\n -------\n array, shape=(n_samples,) if n_classes == 2 else (n_samples, n_classes)\n Confidence scores per (sample, class) combination. In the binary\n case, confidence score for self.classes_[1] where >0 means this\n class would be predicted.\n \"\"\"",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'coef_'",
")",
"or",
"self",
".",
"coef_",
"is",
"None",
":",
"raise",
"NotFittedError",
"(",
"\"This %(name)s instance is not fitted \"",
"\"yet\"",
"%",
"{",
"'name'",
":",
"type",
"(",
"self",
")",
".",
"__name__",
"}",
")",
"n_features",
"=",
"self",
".",
"coef_",
".",
"shape",
"[",
"1",
"]",
"if",
"X",
".",
"shape",
"[",
"1",
"]",
"!=",
"n_features",
":",
"raise",
"ValueError",
"(",
"\"X has %d features per sample; expecting %d\"",
"%",
"(",
"X",
".",
"shape",
"[",
"1",
"]",
",",
"n_features",
")",
")",
"scores",
"=",
"safe_sparse_dot",
"(",
"X",
",",
"self",
".",
"coef_",
".",
"T",
",",
"dense_output",
"=",
"True",
")",
"+",
"self",
".",
"intercept_",
"return",
"scores",
".",
"ravel",
"(",
")",
"if",
"scores",
".",
"shape",
"[",
"1",
"]",
"==",
"1",
"else",
"scores",
"def",
"predict_log_proba",
"(",
"self",
",",
"X",
")",
":",
"\"\"\"Log of probability estimates.\n The returned estimates for all classes are ordered by the\n label of classes.\n Parameters\n ----------\n X : array-like, shape = [n_samples, n_features]\n Returns\n -------\n T : array-like, shape = [n_samples, n_classes]\n Returns the log-probability of the sample for each class in the\n model, where classes are ordered as they are in ``self.classes_``.\n \"\"\"",
"return",
"np",
".",
"log",
"(",
"self",
".",
"predict_proba",
"(",
"X",
")",
")"
] |
A bounds constrained logistic regression with solution offset.
|
[
"A",
"bounds",
"constrained",
"logistic",
"regression",
"with",
"solution",
"offset",
"."
] |
[
"\"\"\"A bounds constrained logistic regression with solution offset.\n\n Required to enable ``coef_calc_type``='logistic' option for\n ``MonoGradientBoostingClassifier`` - because sci-kit learn\n ``LogisticRegression`` does not allow bounds constraints or solution\n offset. It is included here to reduce dependencies.\n\n This is a simple implementation of logistic regression with L2\n regularisation, bounds constraints on the coefficients, and the ability\n to accept an offset on the solution. It is solved using the scipy\n conjugate gradient Newton method ``fmin_tnc``.\n\n Parameters\n ----------\n C : float, 0 < C <= 1.0\n Empirical error weight, inverse of lambda (regularisation strength).\n\n fit_intercept : boolean\n True to fit an intercept.\n\n random_state : random_state\n Random seed.\n\n solver : 'newton-cg'\n Uses scipy.opt.fmin_tnc (only implemented option)\n\n incr_feats : array-like\n The one-based array indices of the columns in X that should only have\n a monotone increasing impact on the resulting class.\n\n decr_feats : array-like\n The one-based array indices of the columns in X that should only have\n a monotone decreasing impact on the resulting class.\n\n regularise_intercept : boolean\n True to regularise the intercept.\n\n standardize : boolean\n True to standardise the predictors before regression. Prevents bias\n due to regularisation scale.\n\n penalty : string, optional (default='l2')\n The regularisation penalty. 'l1' is not guaranteed to work very well\n because the newton solver relies on smoothness.\n\n\n \"\"\"",
"\"\"\"Fit the gradient boosting model.\n\n Parameters\n ----------\n X : array-like, shape = [n_samples, n_features]\n Training vectors, where n_samples is the number of samples\n and n_features is the number of features.\n\n y : array-like, shape = [n_samples]\n Target values (integers in classification, real numbers in\n regression)\n For classification, labels must correspond to classes.\n\n sample_weight : array-like, shape = [n_samples] or None\n Sample weights. If None, then samples are equally weighted. Splits\n that would create child nodes with net zero or negative weight are\n ignored while searching for a split in each node. In the case of\n classification, splits are also ignored if they would result in any\n single class carrying a negative weight in either child node.\n\n offset : array-like, shape = [n_samples] (optional)\n The solution offset for each training point.\n\n Returns\n -------\n self : object\n Returns self.\n \"\"\"",
"# Fast and numerically precise",
"# Solve",
"\"\"\"Predict class or regression value for X.\n For a classification model, the predicted class for each sample in X is\n returned. For a regression model, the predicted value based on X is\n returned.\n Parameters\n ----------\n X : array-like or sparse matrix of shape = [n_samples, n_features]\n The input samples. Internally, it will be converted to\n ``dtype=np.float32`` and if a sparse matrix is provided\n to a sparse ``csr_matrix``.\n check_input : boolean, (default=True)\n Allow to bypass several input checking.\n Don't use this parameter unless you know what you do.\n Returns\n -------\n y : array of shape = [n_samples] or [n_samples, n_outputs]\n The predicted classes, or the predict values.\n \"\"\"",
"\"\"\"Probability estimates.\n The returned estimates for all classes are ordered by the\n label of classes.\n For a multi_class problem, if multi_class is set to be \"multinomial\"\n the softmax function is used to find the predicted probability of\n each class.\n Else use a one-vs-rest approach, i.e calculate the probability\n of each class assuming it to be positive using the logistic function.\n and normalize these values across all the classes.\n Parameters\n ----------\n X : array-like, shape = [n_samples, n_features]\n Returns\n -------\n T : array-like, shape = [n_samples, n_classes]\n Returns the probability of the sample for each class in the model,\n where classes are ordered as they are in ``self.classes_``.\n \"\"\"",
"\"\"\"Predict confidence scores for samples.\n The confidence score for a sample is the signed distance of that\n sample to the hyperplane.\n Parameters\n ----------\n X : {array-like, sparse matrix}, shape = (n_samples, n_features)\n Samples.\n Returns\n -------\n array, shape=(n_samples,) if n_classes == 2 else (n_samples, n_classes)\n Confidence scores per (sample, class) combination. In the binary\n case, confidence score for self.classes_[1] where >0 means this\n class would be predicted.\n \"\"\"",
"\"\"\"Log of probability estimates.\n The returned estimates for all classes are ordered by the\n label of classes.\n Parameters\n ----------\n X : array-like, shape = [n_samples, n_features]\n Returns\n -------\n T : array-like, shape = [n_samples, n_classes]\n Returns the log-probability of the sample for each class in the\n model, where classes are ordered as they are in ``self.classes_``.\n \"\"\""
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 19
| 2,043
| 355
|
0acad759501fef326cbcfd3e9f0e8210f9411441
|
owolabileg/property-db
|
android-api/android/app/NotificationManager.java
|
[
"MIT"
] |
Java
|
NotificationManager
|
/**
* Class to notify the user of events that happen. This is how you tell
* the user that something has happened in the background. {@more}
*
* Notifications can take different forms:
* <ul>
* <li>A persistent icon that goes in the status bar and is accessible
* through the launcher, (when the user selects it, a designated Intent
* can be launched),</li>
* <li>Turning on or flashing LEDs on the device, or</li>
* <li>Alerting the user by flashing the backlight, playing a sound,
* or vibrating.</li>
* </ul>
*
* <p>
* Each of the notify methods takes an int id parameter and optionally a
* {@link String} tag parameter, which may be {@code null}. These parameters
* are used to form a pair (tag, id), or ({@code null}, id) if tag is
* unspecified. This pair identifies this notification from your app to the
* system, so that pair should be unique within your app. If you call one
* of the notify methods with a (tag, id) pair that is currently active and
* a new set of notification parameters, it will be updated. For example,
* if you pass a new status bar icon, the old icon in the status bar will
* be replaced with the new one. This is also the same tag and id you pass
* to the {@link #cancel(int)} or {@link #cancel(String, int)} method to clear
* this notification.
*
* <p>
* You do not instantiate this class directly; instead, retrieve it through
* {@link android.content.Context#getSystemService}.
*
* <div class="special reference">
* <h3>Developer Guides</h3>
* <p>For a guide to creating notifications, read the
* <a href="{@docRoot}guide/topics/ui/notifiers/notifications.html">Status Bar Notifications</a>
* developer guide.</p>
* </div>
*
* @see android.app.Notification
* @see android.content.Context#getSystemService
*/
|
Class to notify the user of events that happen. This is how you tell
the user that something has happened in the background.
Notifications can take different forms:
A persistent icon that goes in the status bar and is accessible
through the launcher, (when the user selects it, a designated Intent
can be launched),
Turning on or flashing LEDs on the device, or
Alerting the user by flashing the backlight, playing a sound,
or vibrating.
Each of the notify methods takes an int id parameter and optionally a
String tag parameter, which may be null. These parameters
are used to form a pair (tag, id), or ( null, id) if tag is
unspecified. This pair identifies this notification from your app to the
system, so that pair should be unique within your app. If you call one
of the notify methods with a (tag, id) pair that is currently active and
a new set of notification parameters, it will be updated. For example,
if you pass a new status bar icon, the old icon in the status bar will
be replaced with the new one. This is also the same tag and id you pass
to the #cancel(int) or #cancel(String, int) method to clear
this notification.
You do not instantiate this class directly; instead, retrieve it through
android.content.Context#getSystemService.
Developer Guides
For a guide to creating notifications, read the
Status Bar Notifications
developer guide.
|
[
"Class",
"to",
"notify",
"the",
"user",
"of",
"events",
"that",
"happen",
".",
"This",
"is",
"how",
"you",
"tell",
"the",
"user",
"that",
"something",
"has",
"happened",
"in",
"the",
"background",
".",
"Notifications",
"can",
"take",
"different",
"forms",
":",
"A",
"persistent",
"icon",
"that",
"goes",
"in",
"the",
"status",
"bar",
"and",
"is",
"accessible",
"through",
"the",
"launcher",
"(",
"when",
"the",
"user",
"selects",
"it",
"a",
"designated",
"Intent",
"can",
"be",
"launched",
")",
"Turning",
"on",
"or",
"flashing",
"LEDs",
"on",
"the",
"device",
"or",
"Alerting",
"the",
"user",
"by",
"flashing",
"the",
"backlight",
"playing",
"a",
"sound",
"or",
"vibrating",
".",
"Each",
"of",
"the",
"notify",
"methods",
"takes",
"an",
"int",
"id",
"parameter",
"and",
"optionally",
"a",
"String",
"tag",
"parameter",
"which",
"may",
"be",
"null",
".",
"These",
"parameters",
"are",
"used",
"to",
"form",
"a",
"pair",
"(",
"tag",
"id",
")",
"or",
"(",
"null",
"id",
")",
"if",
"tag",
"is",
"unspecified",
".",
"This",
"pair",
"identifies",
"this",
"notification",
"from",
"your",
"app",
"to",
"the",
"system",
"so",
"that",
"pair",
"should",
"be",
"unique",
"within",
"your",
"app",
".",
"If",
"you",
"call",
"one",
"of",
"the",
"notify",
"methods",
"with",
"a",
"(",
"tag",
"id",
")",
"pair",
"that",
"is",
"currently",
"active",
"and",
"a",
"new",
"set",
"of",
"notification",
"parameters",
"it",
"will",
"be",
"updated",
".",
"For",
"example",
"if",
"you",
"pass",
"a",
"new",
"status",
"bar",
"icon",
"the",
"old",
"icon",
"in",
"the",
"status",
"bar",
"will",
"be",
"replaced",
"with",
"the",
"new",
"one",
".",
"This",
"is",
"also",
"the",
"same",
"tag",
"and",
"id",
"you",
"pass",
"to",
"the",
"#cancel",
"(",
"int",
")",
"or",
"#cancel",
"(",
"String",
"int",
")",
"method",
"to",
"clear",
"this",
"notification",
".",
"You",
"do",
"not",
"instantiate",
"this",
"class",
"directly",
";",
"instead",
"retrieve",
"it",
"through",
"android",
".",
"content",
".",
"Context#getSystemService",
".",
"Developer",
"Guides",
"For",
"a",
"guide",
"to",
"creating",
"notifications",
"read",
"the",
"Status",
"Bar",
"Notifications",
"developer",
"guide",
"."
] |
public class NotificationManager
{
private static String TAG = "NotificationManager";
private static boolean localLOGV = false;
private static INotificationManager sService;
/** @hide */
static public INotificationManager getService()
{
if (sService != null) {
return sService;
}
IBinder b = ServiceManager.getService("notification");
sService = INotificationManager.Stub.asInterface(b);
return sService;
}
/*package*/ NotificationManager(Context context, Handler handler)
{
mContext = context;
}
/** {@hide} */
public static NotificationManager from(Context context) {
return (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
}
/**
* Post a notification to be shown in the status bar. If a notification with
* the same id has already been posted by your application and has not yet been canceled, it
* will be replaced by the updated information.
*
* @param id An identifier for this notification unique within your
* application.
* @param notification A {@link Notification} object describing what to show the user. Must not
* be null.
*/
public void notify(int id, Notification notification)
{
notify(null, id, notification);
}
/**
* Post a notification to be shown in the status bar. If a notification with
* the same tag and id has already been posted by your application and has not yet been
* canceled, it will be replaced by the updated information.
*
* @param tag A string identifier for this notification. May be {@code null}.
* @param id An identifier for this notification. The pair (tag, id) must be unique
* within your application.
* @param notification A {@link Notification} object describing what to
* show the user. Must not be null.
*/
public void notify(String tag, int id, Notification notification)
{
int[] idOut = new int[1];
INotificationManager service = getService();
String pkg = mContext.getPackageName();
if (notification.sound != null) {
notification.sound = notification.sound.getCanonicalUri();
}
if (localLOGV) Log.v(TAG, pkg + ": notify(" + id + ", " + notification + ")");
try {
service.enqueueNotificationWithTag(pkg, tag, id, notification, idOut,
UserHandle.myUserId());
if (id != idOut[0]) {
Log.w(TAG, "notify: id corrupted: sent " + id + ", got back " + idOut[0]);
}
} catch (RemoteException e) {
}
}
/**
* @hide
*/
public void notifyAsUser(String tag, int id, Notification notification, UserHandle user)
{
int[] idOut = new int[1];
INotificationManager service = getService();
String pkg = mContext.getPackageName();
if (notification.sound != null) {
notification.sound = notification.sound.getCanonicalUri();
}
if (localLOGV) Log.v(TAG, pkg + ": notify(" + id + ", " + notification + ")");
try {
service.enqueueNotificationWithTag(pkg, tag, id, notification, idOut,
user.getIdentifier());
if (id != idOut[0]) {
Log.w(TAG, "notify: id corrupted: sent " + id + ", got back " + idOut[0]);
}
} catch (RemoteException e) {
}
}
/**
* Cancel a previously shown notification. If it's transient, the view
* will be hidden. If it's persistent, it will be removed from the status
* bar.
*/
public void cancel(int id)
{
cancel(null, id);
}
/**
* Cancel a previously shown notification. If it's transient, the view
* will be hidden. If it's persistent, it will be removed from the status
* bar.
*/
public void cancel(String tag, int id)
{
INotificationManager service = getService();
String pkg = mContext.getPackageName();
if (localLOGV) Log.v(TAG, pkg + ": cancel(" + id + ")");
try {
service.cancelNotificationWithTag(pkg, tag, id, UserHandle.myUserId());
} catch (RemoteException e) {
}
}
/**
* @hide
*/
public void cancelAsUser(String tag, int id, UserHandle user)
{
INotificationManager service = getService();
String pkg = mContext.getPackageName();
if (localLOGV) Log.v(TAG, pkg + ": cancel(" + id + ")");
try {
service.cancelNotificationWithTag(pkg, tag, id, user.getIdentifier());
} catch (RemoteException e) {
}
}
/**
* Cancel all previously shown notifications. See {@link #cancel} for the
* detailed behavior.
*/
public void cancelAll()
{
INotificationManager service = getService();
String pkg = mContext.getPackageName();
if (localLOGV) Log.v(TAG, pkg + ": cancelAll()");
try {
service.cancelAllNotifications(pkg, UserHandle.myUserId());
} catch (RemoteException e) {
}
}
private Context mContext;
}
|
[
"public",
"class",
"NotificationManager",
"{",
"private",
"static",
"String",
"TAG",
"=",
"\"",
"NotificationManager",
"\"",
";",
"private",
"static",
"boolean",
"localLOGV",
"=",
"false",
";",
"private",
"static",
"INotificationManager",
"sService",
";",
"/** @hide */",
"static",
"public",
"INotificationManager",
"getService",
"(",
")",
"{",
"if",
"(",
"sService",
"!=",
"null",
")",
"{",
"return",
"sService",
";",
"}",
"IBinder",
"b",
"=",
"ServiceManager",
".",
"getService",
"(",
"\"",
"notification",
"\"",
")",
";",
"sService",
"=",
"INotificationManager",
".",
"Stub",
".",
"asInterface",
"(",
"b",
")",
";",
"return",
"sService",
";",
"}",
"/*package*/",
"NotificationManager",
"(",
"Context",
"context",
",",
"Handler",
"handler",
")",
"{",
"mContext",
"=",
"context",
";",
"}",
"/** {@hide} */",
"public",
"static",
"NotificationManager",
"from",
"(",
"Context",
"context",
")",
"{",
"return",
"(",
"NotificationManager",
")",
"context",
".",
"getSystemService",
"(",
"Context",
".",
"NOTIFICATION_SERVICE",
")",
";",
"}",
"/**\n * Post a notification to be shown in the status bar. If a notification with\n * the same id has already been posted by your application and has not yet been canceled, it\n * will be replaced by the updated information.\n *\n * @param id An identifier for this notification unique within your\n * application.\n * @param notification A {@link Notification} object describing what to show the user. Must not\n * be null.\n */",
"public",
"void",
"notify",
"(",
"int",
"id",
",",
"Notification",
"notification",
")",
"{",
"notify",
"(",
"null",
",",
"id",
",",
"notification",
")",
";",
"}",
"/**\n * Post a notification to be shown in the status bar. If a notification with\n * the same tag and id has already been posted by your application and has not yet been\n * canceled, it will be replaced by the updated information.\n *\n * @param tag A string identifier for this notification. May be {@code null}.\n * @param id An identifier for this notification. The pair (tag, id) must be unique\n * within your application.\n * @param notification A {@link Notification} object describing what to\n * show the user. Must not be null.\n */",
"public",
"void",
"notify",
"(",
"String",
"tag",
",",
"int",
"id",
",",
"Notification",
"notification",
")",
"{",
"int",
"[",
"]",
"idOut",
"=",
"new",
"int",
"[",
"1",
"]",
";",
"INotificationManager",
"service",
"=",
"getService",
"(",
")",
";",
"String",
"pkg",
"=",
"mContext",
".",
"getPackageName",
"(",
")",
";",
"if",
"(",
"notification",
".",
"sound",
"!=",
"null",
")",
"{",
"notification",
".",
"sound",
"=",
"notification",
".",
"sound",
".",
"getCanonicalUri",
"(",
")",
";",
"}",
"if",
"(",
"localLOGV",
")",
"Log",
".",
"v",
"(",
"TAG",
",",
"pkg",
"+",
"\"",
": notify(",
"\"",
"+",
"id",
"+",
"\"",
", ",
"\"",
"+",
"notification",
"+",
"\"",
")",
"\"",
")",
";",
"try",
"{",
"service",
".",
"enqueueNotificationWithTag",
"(",
"pkg",
",",
"tag",
",",
"id",
",",
"notification",
",",
"idOut",
",",
"UserHandle",
".",
"myUserId",
"(",
")",
")",
";",
"if",
"(",
"id",
"!=",
"idOut",
"[",
"0",
"]",
")",
"{",
"Log",
".",
"w",
"(",
"TAG",
",",
"\"",
"notify: id corrupted: sent ",
"\"",
"+",
"id",
"+",
"\"",
", got back ",
"\"",
"+",
"idOut",
"[",
"0",
"]",
")",
";",
"}",
"}",
"catch",
"(",
"RemoteException",
"e",
")",
"{",
"}",
"}",
"/**\n * @hide\n */",
"public",
"void",
"notifyAsUser",
"(",
"String",
"tag",
",",
"int",
"id",
",",
"Notification",
"notification",
",",
"UserHandle",
"user",
")",
"{",
"int",
"[",
"]",
"idOut",
"=",
"new",
"int",
"[",
"1",
"]",
";",
"INotificationManager",
"service",
"=",
"getService",
"(",
")",
";",
"String",
"pkg",
"=",
"mContext",
".",
"getPackageName",
"(",
")",
";",
"if",
"(",
"notification",
".",
"sound",
"!=",
"null",
")",
"{",
"notification",
".",
"sound",
"=",
"notification",
".",
"sound",
".",
"getCanonicalUri",
"(",
")",
";",
"}",
"if",
"(",
"localLOGV",
")",
"Log",
".",
"v",
"(",
"TAG",
",",
"pkg",
"+",
"\"",
": notify(",
"\"",
"+",
"id",
"+",
"\"",
", ",
"\"",
"+",
"notification",
"+",
"\"",
")",
"\"",
")",
";",
"try",
"{",
"service",
".",
"enqueueNotificationWithTag",
"(",
"pkg",
",",
"tag",
",",
"id",
",",
"notification",
",",
"idOut",
",",
"user",
".",
"getIdentifier",
"(",
")",
")",
";",
"if",
"(",
"id",
"!=",
"idOut",
"[",
"0",
"]",
")",
"{",
"Log",
".",
"w",
"(",
"TAG",
",",
"\"",
"notify: id corrupted: sent ",
"\"",
"+",
"id",
"+",
"\"",
", got back ",
"\"",
"+",
"idOut",
"[",
"0",
"]",
")",
";",
"}",
"}",
"catch",
"(",
"RemoteException",
"e",
")",
"{",
"}",
"}",
"/**\n * Cancel a previously shown notification. If it's transient, the view\n * will be hidden. If it's persistent, it will be removed from the status\n * bar.\n */",
"public",
"void",
"cancel",
"(",
"int",
"id",
")",
"{",
"cancel",
"(",
"null",
",",
"id",
")",
";",
"}",
"/**\n * Cancel a previously shown notification. If it's transient, the view\n * will be hidden. If it's persistent, it will be removed from the status\n * bar.\n */",
"public",
"void",
"cancel",
"(",
"String",
"tag",
",",
"int",
"id",
")",
"{",
"INotificationManager",
"service",
"=",
"getService",
"(",
")",
";",
"String",
"pkg",
"=",
"mContext",
".",
"getPackageName",
"(",
")",
";",
"if",
"(",
"localLOGV",
")",
"Log",
".",
"v",
"(",
"TAG",
",",
"pkg",
"+",
"\"",
": cancel(",
"\"",
"+",
"id",
"+",
"\"",
")",
"\"",
")",
";",
"try",
"{",
"service",
".",
"cancelNotificationWithTag",
"(",
"pkg",
",",
"tag",
",",
"id",
",",
"UserHandle",
".",
"myUserId",
"(",
")",
")",
";",
"}",
"catch",
"(",
"RemoteException",
"e",
")",
"{",
"}",
"}",
"/**\n * @hide\n */",
"public",
"void",
"cancelAsUser",
"(",
"String",
"tag",
",",
"int",
"id",
",",
"UserHandle",
"user",
")",
"{",
"INotificationManager",
"service",
"=",
"getService",
"(",
")",
";",
"String",
"pkg",
"=",
"mContext",
".",
"getPackageName",
"(",
")",
";",
"if",
"(",
"localLOGV",
")",
"Log",
".",
"v",
"(",
"TAG",
",",
"pkg",
"+",
"\"",
": cancel(",
"\"",
"+",
"id",
"+",
"\"",
")",
"\"",
")",
";",
"try",
"{",
"service",
".",
"cancelNotificationWithTag",
"(",
"pkg",
",",
"tag",
",",
"id",
",",
"user",
".",
"getIdentifier",
"(",
")",
")",
";",
"}",
"catch",
"(",
"RemoteException",
"e",
")",
"{",
"}",
"}",
"/**\n * Cancel all previously shown notifications. See {@link #cancel} for the\n * detailed behavior.\n */",
"public",
"void",
"cancelAll",
"(",
")",
"{",
"INotificationManager",
"service",
"=",
"getService",
"(",
")",
";",
"String",
"pkg",
"=",
"mContext",
".",
"getPackageName",
"(",
")",
";",
"if",
"(",
"localLOGV",
")",
"Log",
".",
"v",
"(",
"TAG",
",",
"pkg",
"+",
"\"",
": cancelAll()",
"\"",
")",
";",
"try",
"{",
"service",
".",
"cancelAllNotifications",
"(",
"pkg",
",",
"UserHandle",
".",
"myUserId",
"(",
")",
")",
";",
"}",
"catch",
"(",
"RemoteException",
"e",
")",
"{",
"}",
"}",
"private",
"Context",
"mContext",
";",
"}"
] |
Class to notify the user of events that happen.
|
[
"Class",
"to",
"notify",
"the",
"user",
"of",
"events",
"that",
"happen",
"."
] |
[] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 16
| 1,139
| 448
|
f7f8556ce67c3df974b7aea5c27bbbfeeadbc68b
|
deverte/psi
|
lib/classes/diagram.js
|
[
"MIT"
] |
JavaScript
|
Diagram
|
/**
* Creates Diagram object.
* @classdesc Diagram class, that contains axis and all columns.
* @param {string} diagramJSON - String with json-description of the diagram.
* @param {object} mjConfig - Configured MathJax package.
* @param {object} mjTypeset - MathJax typeset object.
* @param {object} style - Style object.
* @param {HTMLElement} documentElement - parent HTML-element.
*/
|
Creates Diagram object.
@classdesc Diagram class, that contains axis and all columns.
@param {string} diagramJSON - String with json-description of the diagram.
@param {object} mjConfig - Configured MathJax package.
@param {object} mjTypeset - MathJax typeset object.
@param {object} style - Style object.
@param {HTMLElement} documentElement - parent HTML-element.
|
[
"Creates",
"Diagram",
"object",
".",
"@classdesc",
"Diagram",
"class",
"that",
"contains",
"axis",
"and",
"all",
"columns",
".",
"@param",
"{",
"string",
"}",
"diagramJSON",
"-",
"String",
"with",
"json",
"-",
"description",
"of",
"the",
"diagram",
".",
"@param",
"{",
"object",
"}",
"mjConfig",
"-",
"Configured",
"MathJax",
"package",
".",
"@param",
"{",
"object",
"}",
"mjTypeset",
"-",
"MathJax",
"typeset",
"object",
".",
"@param",
"{",
"object",
"}",
"style",
"-",
"Style",
"object",
".",
"@param",
"{",
"HTMLElement",
"}",
"documentElement",
"-",
"parent",
"HTML",
"-",
"element",
"."
] |
class Diagram {
// Defaults
// Constructor
// Setter
constructor(diagramJSON, {
style = this._STYLE,
documentElement = this._DOCUMENT_ELEMENT,
mjConfig = this._MJ_CONFIG,
mjTypeset = this._MJ_TYPESET
} = {}) {
_defineProperty(this, "_MJ_CONFIG", {
// http://docs.mathjax.org/en/latest/options/output/index.html
MathJax: {
svg: {
scale: 1,
// global scaling factor for all expressions
minScale: 0.5,
// smallest scaling factor to use
matchFontHeight: true,
// true to match ex-height of surrounding font
mtextInheritFont: false,
// true to make mtext elements use surrounding font
merrorInheritFont: true,
// true to make merror text use surrounding font
mathmlSpacing: false,
// true for MathML spacing rules, false for TeX rules
skipAttributes: {},
// RFDa and other attributes NOT to copy to the output
exFactor: 0.5,
// default size of ex in em units
displayAlign: 'center',
// default for indentalign when set to 'auto'
displayIndent: '0',
// default for indentshift when set to 'auto'
fontCache: 'local',
// or 'global' or 'none'
localID: null,
// ID to use for local font cache (for single equation processing)
internalSpeechTitles: true,
// insert <title> tags with speech content
titleID: 0 // initial id number to use for aria-labeledby titles
}
},
displayMessages: false,
// determines whether Message.Set() calls are logged
displayErrors: true,
// determines whether error messages are shown on the console
undefinedCharError: false,
// determines whether "unknown characters" (i.e., no glyph
// in the configured fonts) are saved in the error array
extensions: '',
// a convenience option to add MathJax extensions
fontURL: 'https://cdnjs.cloudflare.com/ajax/' + // for webfont urls in the
'libs/mathjax/2.7.2/fonts/HTML-CSS',
// CSS for HTML output
paths: {} // configures custom path variables (e.g., for third party extensions, cf.
// test/config-third-party-extensions.js)
});
_defineProperty(this, "_MJ_TYPESET", {
// https://www.npmjs.com/package/mathjax-node#typesetoptions-callback
ex: 6,
// ex-size in pixels
width: 100,
// width of container (in ex) for linebreaking and tags
useFontCache: true,
// use <defs> and <use> in svg output?
useGlobalCache: false,
// use common <defs> for all equations?
linebreaks: false,
// automatic linebreaking
equationNumbers: 'none',
// automatic equation numbering ("none", "AMS" or "all")
cjkCharWidth: 13,
// width of CJK character
math: '',
// the math string to typeset
format: 'TeX',
// the input format (TeX, inline-TeX, AsciiMath, or MathML)
xmlns: 'mml',
// the namespace to use for MathML
html: false,
// generate HTML output
htmlNode: false,
// generate HTML output as jsdom node
css: false,
// generate CSS for HTML output
mml: false,
// generate MathML output
mmlNode: false,
// generate MathML output as jsdom node
svg: false,
// generate SVG output
svgNode: false,
// generate SVG output as jsdom node
speakText: true,
// add textual alternative (for TeX/asciimath the input string,
// for MathML a dummy string)
state: {},
// an object to store information from multiple calls (e.g., <defs>
// if useGlobalCache, counter for equation numbering if equationNumbers ar )
timeout: 10e3 // 10 second timeout before restarting MathJax
});
_defineProperty(this, "_STYLE", {});
_defineProperty(this, "_DOCUMENT_ELEMENT", undefined);
_defineProperty(this, "_COLUMNS", []);
_defineProperty(this, "_mjConfig", this._MJ_CONFIG);
_defineProperty(this, "_mjAPI", null);
_defineProperty(this, "_mjTypeset", this._MJ_TYPESET);
_defineProperty(this, "_style", null);
_defineProperty(this, "_documentElement", this._DOCUMENT_ELEMENT);
_defineProperty(this, "_axis", null);
_defineProperty(this, "_columns", []);
_defineProperty(this, "_svg", null);
this.mjConfig = mjConfig;
this.mjTypeset = mjTypeset; // Style priority: 1) style, 2) diagramJSON.style, 3) Style defaults
diagramJSON.style = _.defaultTo(diagramJSON.style, {});
_.defaultsDeep(style, diagramJSON.style);
this.style = new Style(style);
this.documentElement = documentElement; // Columns
Columns.add(this, diagramJSON.columns); // Axis
Axes.add(this, diagramJSON.axis);
}
/**
* Generation of the diagram.
* @public
* @returns Diagram object.
* @example <caption>Example usage.</caption>
* diagramFile = 'diagram.json'
* diagramJSON = JSON.parse(JSON.minify(fs.readFileSync(diagramFile, 'utf8')))
* diagram = new Diagram(diagramJSON)
* await diagram.generate()
*/
async generate() {
await Rows.generateSingle(this); // After that we know heights of the all rows.
Rows.setSingleHeights(this);
await Rows.generateMultiple(this);
this._createCanvas();
Blocks.arrange(this);
Blocks.join(this);
Blocks.drawControlledInteractionLinks(this);
if (this.axis != null) {
await Axes.generateLabels(this);
Axes.generate(this);
Axes.addLabels(this);
Axes.addTicks(this);
}
return this;
}
/**
* Creates canvas containing all graphics (blocks, formulas and etc.).
* @private
*/
_createCanvas() {
// Calculate width and height of canvas as sum of all elements widths and heights
let width = this.style.canvas.margin.left + this.style.canvas.margin.right;
for (let i = 1; i <= Columns.count(this); i++) {
width += Columns.getMaxWidth(this, i) + this.style.columns.interval;
}
let height = this.style.canvas.margin.top + this.style.canvas.margin.bottom;
for (let i = 1; i <= Rows.count(this); i++) {
height += Rows.getMaxHeight(this, i) + this.style.rows.interval;
}
height -= this.style.rows.interval; // Create canvas and it's background
this.svg = SVG(this.documentElement).width(width).height(height);
this.svg.rect().size('100%', '100%').fill({
color: this.style.canvas.backgroundColor,
opacity: this.style.canvas.backgroundOpacity
});
}
get columns() {
return this._columns;
}
/**
* @param {Array<Column>} value - Columns.
*/
set columns(value) {
value = _.defaultTo(value, this._COLUMNS);
for (let column of columns) {
console.assert(column instanceof Column, `Incorrect type '${column}' of 'Diagram.columns.column'. Must be a 'Column'.`);
}
this._columns = value;
}
get axis() {
return this._axis;
}
/**
* @param {Axis | null} value - Axis.
*/
set axis(value) {
console.assert(value instanceof Axis || value == null, `Incorrect type '${value}' of 'Diagram.axis'. Must be an 'Axis' or 'null'.`);
this._axis = value;
}
get mjConfig() {
return this._mjConfig;
}
/**
* @param {object} value - MathJax configuration.
*/
set mjConfig(value) {
value = _.defaultTo(value, {});
_.defaultsDeep(value, this._MJ_CONFIG);
console.assert(typeof value == 'object', `Incorrect type '${value}' of 'Diagram.mjConfig'. Must be an 'object'.`);
mjAPI.config(value);
mjAPI.start();
this.mjAPI = mjAPI;
this._mjConfig = value;
}
get mjAPI() {
return this._mjAPI;
}
/**
* @param {object} value - MathJax API.
*/
set mjAPI(value) {
console.assert(typeof value == 'object', `Incorrect type '${value}' of 'Diagram.mjAPI'. Must be an 'object'.`);
this._mjAPI = value;
}
get mjTypeset() {
return this._mjTypeset;
}
/**
* @param {object} value - MathJax typeset.
*/
set mjTypeset(value) {
value = _.defaultTo(value, {});
_.defaultsDeep(value, this._MJ_TYPESET);
console.assert(typeof value == 'object', `Incorrect type '${value}' of 'Diagram.mjTypeset'. Must be an 'object'.`);
this._mjTypeset = value;
}
get style() {
return this._style;
}
/**
* @param {Style} value - Style object.
*/
set style(value) {
value = _.defaultTo(value, {});
_.defaultsDeep(value, this._STYLE);
console.assert(value instanceof Style, `Incorrect type '${value}' of 'Diagram.style'. Must be a 'Style'.`);
this._style = value;
}
get documentElement() {
return this._documentElement;
}
/**
* @param {object} value - Parent HTML-element.
*/
set documentElement(value) {
if (value == undefined || value == null) {
let document = window.document;
registerWindow(window, document);
value = document.documentElement;
}
console.assert(typeof value == 'object', `Incorrect type '${value}' of 'Diagram.documentElement'. Must be an 'object'.`);
this._documentElement = value;
}
get svg() {
return this._svg;
}
/**
* @param {SVG} value - Canvas.
*/
set svg(value) {
console.assert(value instanceof Object, `Incorrect type '${value}' of 'Diagram.svg'. Must be a 'SVG' or 'object'.`);
this._svg = value;
}
}
|
[
"class",
"Diagram",
"{",
"constructor",
"(",
"diagramJSON",
",",
"{",
"style",
"=",
"this",
".",
"_STYLE",
",",
"documentElement",
"=",
"this",
".",
"_DOCUMENT_ELEMENT",
",",
"mjConfig",
"=",
"this",
".",
"_MJ_CONFIG",
",",
"mjTypeset",
"=",
"this",
".",
"_MJ_TYPESET",
"}",
"=",
"{",
"}",
")",
"{",
"_defineProperty",
"(",
"this",
",",
"\"_MJ_CONFIG\"",
",",
"{",
"MathJax",
":",
"{",
"svg",
":",
"{",
"scale",
":",
"1",
",",
"minScale",
":",
"0.5",
",",
"matchFontHeight",
":",
"true",
",",
"mtextInheritFont",
":",
"false",
",",
"merrorInheritFont",
":",
"true",
",",
"mathmlSpacing",
":",
"false",
",",
"skipAttributes",
":",
"{",
"}",
",",
"exFactor",
":",
"0.5",
",",
"displayAlign",
":",
"'center'",
",",
"displayIndent",
":",
"'0'",
",",
"fontCache",
":",
"'local'",
",",
"localID",
":",
"null",
",",
"internalSpeechTitles",
":",
"true",
",",
"titleID",
":",
"0",
"}",
"}",
",",
"displayMessages",
":",
"false",
",",
"displayErrors",
":",
"true",
",",
"undefinedCharError",
":",
"false",
",",
"extensions",
":",
"''",
",",
"fontURL",
":",
"'https://cdnjs.cloudflare.com/ajax/'",
"+",
"'libs/mathjax/2.7.2/fonts/HTML-CSS'",
",",
"paths",
":",
"{",
"}",
"}",
")",
";",
"_defineProperty",
"(",
"this",
",",
"\"_MJ_TYPESET\"",
",",
"{",
"ex",
":",
"6",
",",
"width",
":",
"100",
",",
"useFontCache",
":",
"true",
",",
"useGlobalCache",
":",
"false",
",",
"linebreaks",
":",
"false",
",",
"equationNumbers",
":",
"'none'",
",",
"cjkCharWidth",
":",
"13",
",",
"math",
":",
"''",
",",
"format",
":",
"'TeX'",
",",
"xmlns",
":",
"'mml'",
",",
"html",
":",
"false",
",",
"htmlNode",
":",
"false",
",",
"css",
":",
"false",
",",
"mml",
":",
"false",
",",
"mmlNode",
":",
"false",
",",
"svg",
":",
"false",
",",
"svgNode",
":",
"false",
",",
"speakText",
":",
"true",
",",
"state",
":",
"{",
"}",
",",
"timeout",
":",
"10e3",
"}",
")",
";",
"_defineProperty",
"(",
"this",
",",
"\"_STYLE\"",
",",
"{",
"}",
")",
";",
"_defineProperty",
"(",
"this",
",",
"\"_DOCUMENT_ELEMENT\"",
",",
"undefined",
")",
";",
"_defineProperty",
"(",
"this",
",",
"\"_COLUMNS\"",
",",
"[",
"]",
")",
";",
"_defineProperty",
"(",
"this",
",",
"\"_mjConfig\"",
",",
"this",
".",
"_MJ_CONFIG",
")",
";",
"_defineProperty",
"(",
"this",
",",
"\"_mjAPI\"",
",",
"null",
")",
";",
"_defineProperty",
"(",
"this",
",",
"\"_mjTypeset\"",
",",
"this",
".",
"_MJ_TYPESET",
")",
";",
"_defineProperty",
"(",
"this",
",",
"\"_style\"",
",",
"null",
")",
";",
"_defineProperty",
"(",
"this",
",",
"\"_documentElement\"",
",",
"this",
".",
"_DOCUMENT_ELEMENT",
")",
";",
"_defineProperty",
"(",
"this",
",",
"\"_axis\"",
",",
"null",
")",
";",
"_defineProperty",
"(",
"this",
",",
"\"_columns\"",
",",
"[",
"]",
")",
";",
"_defineProperty",
"(",
"this",
",",
"\"_svg\"",
",",
"null",
")",
";",
"this",
".",
"mjConfig",
"=",
"mjConfig",
";",
"this",
".",
"mjTypeset",
"=",
"mjTypeset",
";",
"diagramJSON",
".",
"style",
"=",
"_",
".",
"defaultTo",
"(",
"diagramJSON",
".",
"style",
",",
"{",
"}",
")",
";",
"_",
".",
"defaultsDeep",
"(",
"style",
",",
"diagramJSON",
".",
"style",
")",
";",
"this",
".",
"style",
"=",
"new",
"Style",
"(",
"style",
")",
";",
"this",
".",
"documentElement",
"=",
"documentElement",
";",
"Columns",
".",
"add",
"(",
"this",
",",
"diagramJSON",
".",
"columns",
")",
";",
"Axes",
".",
"add",
"(",
"this",
",",
"diagramJSON",
".",
"axis",
")",
";",
"}",
"async",
"generate",
"(",
")",
"{",
"await",
"Rows",
".",
"generateSingle",
"(",
"this",
")",
";",
"Rows",
".",
"setSingleHeights",
"(",
"this",
")",
";",
"await",
"Rows",
".",
"generateMultiple",
"(",
"this",
")",
";",
"this",
".",
"_createCanvas",
"(",
")",
";",
"Blocks",
".",
"arrange",
"(",
"this",
")",
";",
"Blocks",
".",
"join",
"(",
"this",
")",
";",
"Blocks",
".",
"drawControlledInteractionLinks",
"(",
"this",
")",
";",
"if",
"(",
"this",
".",
"axis",
"!=",
"null",
")",
"{",
"await",
"Axes",
".",
"generateLabels",
"(",
"this",
")",
";",
"Axes",
".",
"generate",
"(",
"this",
")",
";",
"Axes",
".",
"addLabels",
"(",
"this",
")",
";",
"Axes",
".",
"addTicks",
"(",
"this",
")",
";",
"}",
"return",
"this",
";",
"}",
"_createCanvas",
"(",
")",
"{",
"let",
"width",
"=",
"this",
".",
"style",
".",
"canvas",
".",
"margin",
".",
"left",
"+",
"this",
".",
"style",
".",
"canvas",
".",
"margin",
".",
"right",
";",
"for",
"(",
"let",
"i",
"=",
"1",
";",
"i",
"<=",
"Columns",
".",
"count",
"(",
"this",
")",
";",
"i",
"++",
")",
"{",
"width",
"+=",
"Columns",
".",
"getMaxWidth",
"(",
"this",
",",
"i",
")",
"+",
"this",
".",
"style",
".",
"columns",
".",
"interval",
";",
"}",
"let",
"height",
"=",
"this",
".",
"style",
".",
"canvas",
".",
"margin",
".",
"top",
"+",
"this",
".",
"style",
".",
"canvas",
".",
"margin",
".",
"bottom",
";",
"for",
"(",
"let",
"i",
"=",
"1",
";",
"i",
"<=",
"Rows",
".",
"count",
"(",
"this",
")",
";",
"i",
"++",
")",
"{",
"height",
"+=",
"Rows",
".",
"getMaxHeight",
"(",
"this",
",",
"i",
")",
"+",
"this",
".",
"style",
".",
"rows",
".",
"interval",
";",
"}",
"height",
"-=",
"this",
".",
"style",
".",
"rows",
".",
"interval",
";",
"this",
".",
"svg",
"=",
"SVG",
"(",
"this",
".",
"documentElement",
")",
".",
"width",
"(",
"width",
")",
".",
"height",
"(",
"height",
")",
";",
"this",
".",
"svg",
".",
"rect",
"(",
")",
".",
"size",
"(",
"'100%'",
",",
"'100%'",
")",
".",
"fill",
"(",
"{",
"color",
":",
"this",
".",
"style",
".",
"canvas",
".",
"backgroundColor",
",",
"opacity",
":",
"this",
".",
"style",
".",
"canvas",
".",
"backgroundOpacity",
"}",
")",
";",
"}",
"get",
"columns",
"(",
")",
"{",
"return",
"this",
".",
"_columns",
";",
"}",
"set",
"columns",
"(",
"value",
")",
"{",
"value",
"=",
"_",
".",
"defaultTo",
"(",
"value",
",",
"this",
".",
"_COLUMNS",
")",
";",
"for",
"(",
"let",
"column",
"of",
"columns",
")",
"{",
"console",
".",
"assert",
"(",
"column",
"instanceof",
"Column",
",",
"`",
"${",
"column",
"}",
"`",
")",
";",
"}",
"this",
".",
"_columns",
"=",
"value",
";",
"}",
"get",
"axis",
"(",
")",
"{",
"return",
"this",
".",
"_axis",
";",
"}",
"set",
"axis",
"(",
"value",
")",
"{",
"console",
".",
"assert",
"(",
"value",
"instanceof",
"Axis",
"||",
"value",
"==",
"null",
",",
"`",
"${",
"value",
"}",
"`",
")",
";",
"this",
".",
"_axis",
"=",
"value",
";",
"}",
"get",
"mjConfig",
"(",
")",
"{",
"return",
"this",
".",
"_mjConfig",
";",
"}",
"set",
"mjConfig",
"(",
"value",
")",
"{",
"value",
"=",
"_",
".",
"defaultTo",
"(",
"value",
",",
"{",
"}",
")",
";",
"_",
".",
"defaultsDeep",
"(",
"value",
",",
"this",
".",
"_MJ_CONFIG",
")",
";",
"console",
".",
"assert",
"(",
"typeof",
"value",
"==",
"'object'",
",",
"`",
"${",
"value",
"}",
"`",
")",
";",
"mjAPI",
".",
"config",
"(",
"value",
")",
";",
"mjAPI",
".",
"start",
"(",
")",
";",
"this",
".",
"mjAPI",
"=",
"mjAPI",
";",
"this",
".",
"_mjConfig",
"=",
"value",
";",
"}",
"get",
"mjAPI",
"(",
")",
"{",
"return",
"this",
".",
"_mjAPI",
";",
"}",
"set",
"mjAPI",
"(",
"value",
")",
"{",
"console",
".",
"assert",
"(",
"typeof",
"value",
"==",
"'object'",
",",
"`",
"${",
"value",
"}",
"`",
")",
";",
"this",
".",
"_mjAPI",
"=",
"value",
";",
"}",
"get",
"mjTypeset",
"(",
")",
"{",
"return",
"this",
".",
"_mjTypeset",
";",
"}",
"set",
"mjTypeset",
"(",
"value",
")",
"{",
"value",
"=",
"_",
".",
"defaultTo",
"(",
"value",
",",
"{",
"}",
")",
";",
"_",
".",
"defaultsDeep",
"(",
"value",
",",
"this",
".",
"_MJ_TYPESET",
")",
";",
"console",
".",
"assert",
"(",
"typeof",
"value",
"==",
"'object'",
",",
"`",
"${",
"value",
"}",
"`",
")",
";",
"this",
".",
"_mjTypeset",
"=",
"value",
";",
"}",
"get",
"style",
"(",
")",
"{",
"return",
"this",
".",
"_style",
";",
"}",
"set",
"style",
"(",
"value",
")",
"{",
"value",
"=",
"_",
".",
"defaultTo",
"(",
"value",
",",
"{",
"}",
")",
";",
"_",
".",
"defaultsDeep",
"(",
"value",
",",
"this",
".",
"_STYLE",
")",
";",
"console",
".",
"assert",
"(",
"value",
"instanceof",
"Style",
",",
"`",
"${",
"value",
"}",
"`",
")",
";",
"this",
".",
"_style",
"=",
"value",
";",
"}",
"get",
"documentElement",
"(",
")",
"{",
"return",
"this",
".",
"_documentElement",
";",
"}",
"set",
"documentElement",
"(",
"value",
")",
"{",
"if",
"(",
"value",
"==",
"undefined",
"||",
"value",
"==",
"null",
")",
"{",
"let",
"document",
"=",
"window",
".",
"document",
";",
"registerWindow",
"(",
"window",
",",
"document",
")",
";",
"value",
"=",
"document",
".",
"documentElement",
";",
"}",
"console",
".",
"assert",
"(",
"typeof",
"value",
"==",
"'object'",
",",
"`",
"${",
"value",
"}",
"`",
")",
";",
"this",
".",
"_documentElement",
"=",
"value",
";",
"}",
"get",
"svg",
"(",
")",
"{",
"return",
"this",
".",
"_svg",
";",
"}",
"set",
"svg",
"(",
"value",
")",
"{",
"console",
".",
"assert",
"(",
"value",
"instanceof",
"Object",
",",
"`",
"${",
"value",
"}",
"`",
")",
";",
"this",
".",
"_svg",
"=",
"value",
";",
"}",
"}"
] |
Creates Diagram object.
|
[
"Creates",
"Diagram",
"object",
"."
] |
[
"// Defaults",
"// Constructor",
"// Setter",
"// http://docs.mathjax.org/en/latest/options/output/index.html",
"// global scaling factor for all expressions",
"// smallest scaling factor to use",
"// true to match ex-height of surrounding font",
"// true to make mtext elements use surrounding font",
"// true to make merror text use surrounding font",
"// true for MathML spacing rules, false for TeX rules",
"// RFDa and other attributes NOT to copy to the output",
"// default size of ex in em units",
"// default for indentalign when set to 'auto'",
"// default for indentshift when set to 'auto'",
"// or 'global' or 'none'",
"// ID to use for local font cache (for single equation processing)",
"// insert <title> tags with speech content",
"// initial id number to use for aria-labeledby titles",
"// determines whether Message.Set() calls are logged",
"// determines whether error messages are shown on the console",
"// determines whether \"unknown characters\" (i.e., no glyph",
"// in the configured fonts) are saved in the error array",
"// a convenience option to add MathJax extensions",
"// for webfont urls in the",
"// CSS for HTML output",
"// configures custom path variables (e.g., for third party extensions, cf.",
"// test/config-third-party-extensions.js)",
"// https://www.npmjs.com/package/mathjax-node#typesetoptions-callback",
"// ex-size in pixels",
"// width of container (in ex) for linebreaking and tags",
"// use <defs> and <use> in svg output?",
"// use common <defs> for all equations?",
"// automatic linebreaking",
"// automatic equation numbering (\"none\", \"AMS\" or \"all\")",
"// width of CJK character",
"// the math string to typeset",
"// the input format (TeX, inline-TeX, AsciiMath, or MathML)",
"// the namespace to use for MathML",
"// generate HTML output",
"// generate HTML output as jsdom node",
"// generate CSS for HTML output",
"// generate MathML output",
"// generate MathML output as jsdom node",
"// generate SVG output",
"// generate SVG output as jsdom node",
"// add textual alternative (for TeX/asciimath the input string,",
"// for MathML a dummy string)",
"// an object to store information from multiple calls (e.g., <defs>",
"// if useGlobalCache, counter for equation numbering if equationNumbers ar )",
"// 10 second timeout before restarting MathJax",
"// Style priority: 1) style, 2) diagramJSON.style, 3) Style defaults",
"// Columns",
"// Axis",
"/**\n * Generation of the diagram.\n * @public\n * @returns Diagram object.\n * @example <caption>Example usage.</caption>\n * diagramFile = 'diagram.json'\n * diagramJSON = JSON.parse(JSON.minify(fs.readFileSync(diagramFile, 'utf8')))\n * diagram = new Diagram(diagramJSON)\n * await diagram.generate()\n */",
"// After that we know heights of the all rows.",
"/**\n * Creates canvas containing all graphics (blocks, formulas and etc.).\n * @private\n */",
"// Calculate width and height of canvas as sum of all elements widths and heights",
"// Create canvas and it's background",
"/**\n * @param {Array<Column>} value - Columns.\n */",
"/**\n * @param {Axis | null} value - Axis.\n */",
"/**\n * @param {object} value - MathJax configuration.\n */",
"/**\n * @param {object} value - MathJax API.\n */",
"/**\n * @param {object} value - MathJax typeset.\n */",
"/**\n * @param {Style} value - Style object.\n */",
"/**\n * @param {object} value - Parent HTML-element.\n */",
"/**\n * @param {SVG} value - Canvas.\n */"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 15
| 2,333
| 95
|
1b65834b62b5642c6eac62e8e29d43eb008bdbab
|
damirarh/dotnet-config2json
|
src/dotnet-config2json/Parser/KeyValueParser.cs
|
[
"Apache-2.0"
] |
C#
|
KeyValueParser
|
/// <summary>
/// ConfigurationProvider for *.config files. Only elements that contain
/// <add KeyName="A" ValueName="B"/> or <remove KeyName="A" ValueName="B"/> (value is not
/// considered for a remove action) as their descendents are used.
/// All others are skipped.
/// KeyName/ValueName can be configured. Default is "key" and "value", respectively.
/// </summary>
/// <example>
/// The following configuration file will result in the following key-value
/// pairs in the dictionary:
/// @{
/// { "nodea:TheKey" : "TheValue" },
/// { "nodeb:nested:NestedKey" : "ValueA" },
/// { "nodeb:nested:NestedKey2" : "ValueB" },
/// }
///
/// <configuration>
/// <nodea>
/// <add key="TheKey" value="TheValue" />
/// </nodea>
/// <nodeb>
/// <nested>
/// <add key="NestedKey" value="ValueA" />
/// <add key="NestedKey2" value="ValueB" />
/// <remove key="SomeTestKey" />
/// </nested>
/// </nodeb>
/// </configuration>
///
/// </example>
|
ConfigurationProvider for *.config files. Only elements that contain
or (value is not
considered for a remove action) as their descendents are used.
All others are skipped.
|
[
"ConfigurationProvider",
"for",
"*",
".",
"config",
"files",
".",
"Only",
"elements",
"that",
"contain",
"or",
"(",
"value",
"is",
"not",
"considered",
"for",
"a",
"remove",
"action",
")",
"as",
"their",
"descendents",
"are",
"used",
".",
"All",
"others",
"are",
"skipped",
"."
] |
public class KeyValueParser : IConfigurationParser
{
private readonly IConsole _logger;
private readonly string _keyName = "key";
private readonly string _valueName = "value";
private readonly string[] _supportedActions = Enum.GetNames(typeof(ConfigurationAction)).Select(x => x.ToLowerInvariant()).ToArray();
public KeyValueParser()
: this("key", "value")
{ }
public KeyValueParser(string key, string value)
: this(key, value, null)
{ }
public KeyValueParser(string key, string value, IConsole logger)
{
_keyName = key;
_valueName = value;
_logger = logger;
}
public bool CanParseElement(XElement element)
{
var hasKeyAttribute = element.DescendantsAndSelf().Any(x => x.Attribute(_keyName) != null);
return hasKeyAttribute;
}
public void ParseElement(XElement element, Stack<string> context, SortedDictionary<string, string> results)
{
if (!CanParseElement(element))
{
return;
}
if (!element.Elements().Any())
{
AddToDictionary(element, context, results);
}
context.Push(element.Name.ToString());
foreach (var node in element.Elements())
{
var hasSupportedAction = node.DescendantsAndSelf().Any(x => _supportedActions.Contains(x.Name.ToString().ToLowerInvariant()));
if (!hasSupportedAction)
{
if (_logger != null)
{
_logger.WriteLine($"Contains an unsupported config element. [{node.ToString()}]");
}
continue;
}
ParseElement(node, context, results);
}
context.Pop();
}
private void AddToDictionary(XElement element, Stack<string> context, SortedDictionary<string, string> results)
{
ConfigurationAction action;
if (!Enum.TryParse(element.Name.ToString(), true, out action))
{
if (_logger != null)
{
_logger.WriteLine($"Element with an unsupported action. [{element.ToString()}]");
}
return;
}
var key = element.Attribute(_keyName);
var value = element.Attribute(_valueName);
if (key == null)
{
if (_logger != null)
{
_logger.WriteLine($"[{element.ToString()}] is not supported because it does not have an attribute with {_keyName}");
}
return;
}
var fullkey = GetKey(context, key.Value);
switch (action)
{
case ConfigurationAction.Add:
string valueToAdd = null;
if (value == null && _logger != null)
{
_logger.WriteLine($"Could not parse the value attribute [{_valueName}] from [{element.ToString()}]. Using null as value...");
}
else
{
valueToAdd = value.Value;
}
if (results.ContainsKey(fullkey))
{
if (_logger != null)
{
_logger.WriteLine($"{fullkey} exists. Replacing existing value [{results[fullkey]}] with {valueToAdd}");
}
results[fullkey] = valueToAdd;
}
else
{
results.Add(fullkey, valueToAdd);
}
break;
case ConfigurationAction.Remove:
results.Remove(fullkey);
break;
default:
throw new NotSupportedException($"Unsupported action: [{action}]");
}
}
private static string GetKey(Stack<string> context, string name)
{
return string.Join(ConfigurationPath.KeyDelimiter, context.Reverse().Concat(new[] { name }));
}
}
|
[
"public",
"class",
"KeyValueParser",
":",
"IConfigurationParser",
"{",
"private",
"readonly",
"IConsole",
"_logger",
";",
"private",
"readonly",
"string",
"_keyName",
"=",
"\"",
"key",
"\"",
";",
"private",
"readonly",
"string",
"_valueName",
"=",
"\"",
"value",
"\"",
";",
"private",
"readonly",
"string",
"[",
"]",
"_supportedActions",
"=",
"Enum",
".",
"GetNames",
"(",
"typeof",
"(",
"ConfigurationAction",
")",
")",
".",
"Select",
"(",
"x",
"=>",
"x",
".",
"ToLowerInvariant",
"(",
")",
")",
".",
"ToArray",
"(",
")",
";",
"public",
"KeyValueParser",
"(",
")",
":",
"this",
"(",
"\"",
"key",
"\"",
",",
"\"",
"value",
"\"",
")",
"{",
"}",
"public",
"KeyValueParser",
"(",
"string",
"key",
",",
"string",
"value",
")",
":",
"this",
"(",
"key",
",",
"value",
",",
"null",
")",
"{",
"}",
"public",
"KeyValueParser",
"(",
"string",
"key",
",",
"string",
"value",
",",
"IConsole",
"logger",
")",
"{",
"_keyName",
"=",
"key",
";",
"_valueName",
"=",
"value",
";",
"_logger",
"=",
"logger",
";",
"}",
"public",
"bool",
"CanParseElement",
"(",
"XElement",
"element",
")",
"{",
"var",
"hasKeyAttribute",
"=",
"element",
".",
"DescendantsAndSelf",
"(",
")",
".",
"Any",
"(",
"x",
"=>",
"x",
".",
"Attribute",
"(",
"_keyName",
")",
"!=",
"null",
")",
";",
"return",
"hasKeyAttribute",
";",
"}",
"public",
"void",
"ParseElement",
"(",
"XElement",
"element",
",",
"Stack",
"<",
"string",
">",
"context",
",",
"SortedDictionary",
"<",
"string",
",",
"string",
">",
"results",
")",
"{",
"if",
"(",
"!",
"CanParseElement",
"(",
"element",
")",
")",
"{",
"return",
";",
"}",
"if",
"(",
"!",
"element",
".",
"Elements",
"(",
")",
".",
"Any",
"(",
")",
")",
"{",
"AddToDictionary",
"(",
"element",
",",
"context",
",",
"results",
")",
";",
"}",
"context",
".",
"Push",
"(",
"element",
".",
"Name",
".",
"ToString",
"(",
")",
")",
";",
"foreach",
"(",
"var",
"node",
"in",
"element",
".",
"Elements",
"(",
")",
")",
"{",
"var",
"hasSupportedAction",
"=",
"node",
".",
"DescendantsAndSelf",
"(",
")",
".",
"Any",
"(",
"x",
"=>",
"_supportedActions",
".",
"Contains",
"(",
"x",
".",
"Name",
".",
"ToString",
"(",
")",
".",
"ToLowerInvariant",
"(",
")",
")",
")",
";",
"if",
"(",
"!",
"hasSupportedAction",
")",
"{",
"if",
"(",
"_logger",
"!=",
"null",
")",
"{",
"_logger",
".",
"WriteLine",
"(",
"$\"",
"Contains an unsupported config element. [",
"{",
"node",
".",
"ToString",
"(",
")",
"}",
"]",
"\"",
")",
";",
"}",
"continue",
";",
"}",
"ParseElement",
"(",
"node",
",",
"context",
",",
"results",
")",
";",
"}",
"context",
".",
"Pop",
"(",
")",
";",
"}",
"private",
"void",
"AddToDictionary",
"(",
"XElement",
"element",
",",
"Stack",
"<",
"string",
">",
"context",
",",
"SortedDictionary",
"<",
"string",
",",
"string",
">",
"results",
")",
"{",
"ConfigurationAction",
"action",
";",
"if",
"(",
"!",
"Enum",
".",
"TryParse",
"(",
"element",
".",
"Name",
".",
"ToString",
"(",
")",
",",
"true",
",",
"out",
"action",
")",
")",
"{",
"if",
"(",
"_logger",
"!=",
"null",
")",
"{",
"_logger",
".",
"WriteLine",
"(",
"$\"",
"Element with an unsupported action. [",
"{",
"element",
".",
"ToString",
"(",
")",
"}",
"]",
"\"",
")",
";",
"}",
"return",
";",
"}",
"var",
"key",
"=",
"element",
".",
"Attribute",
"(",
"_keyName",
")",
";",
"var",
"value",
"=",
"element",
".",
"Attribute",
"(",
"_valueName",
")",
";",
"if",
"(",
"key",
"==",
"null",
")",
"{",
"if",
"(",
"_logger",
"!=",
"null",
")",
"{",
"_logger",
".",
"WriteLine",
"(",
"$\"",
"[",
"{",
"element",
".",
"ToString",
"(",
")",
"}",
"] is not supported because it does not have an attribute with ",
"{",
"_keyName",
"}",
"\"",
")",
";",
"}",
"return",
";",
"}",
"var",
"fullkey",
"=",
"GetKey",
"(",
"context",
",",
"key",
".",
"Value",
")",
";",
"switch",
"(",
"action",
")",
"{",
"case",
"ConfigurationAction",
".",
"Add",
":",
"string",
"valueToAdd",
"=",
"null",
";",
"if",
"(",
"value",
"==",
"null",
"&&",
"_logger",
"!=",
"null",
")",
"{",
"_logger",
".",
"WriteLine",
"(",
"$\"",
"Could not parse the value attribute [",
"{",
"_valueName",
"}",
"] from [",
"{",
"element",
".",
"ToString",
"(",
")",
"}",
"]. Using null as value...",
"\"",
")",
";",
"}",
"else",
"{",
"valueToAdd",
"=",
"value",
".",
"Value",
";",
"}",
"if",
"(",
"results",
".",
"ContainsKey",
"(",
"fullkey",
")",
")",
"{",
"if",
"(",
"_logger",
"!=",
"null",
")",
"{",
"_logger",
".",
"WriteLine",
"(",
"$\"",
"{",
"fullkey",
"}",
" exists. Replacing existing value [",
"{",
"results",
"[",
"fullkey",
"]",
"}",
"] with ",
"{",
"valueToAdd",
"}",
"\"",
")",
";",
"}",
"results",
"[",
"fullkey",
"]",
"=",
"valueToAdd",
";",
"}",
"else",
"{",
"results",
".",
"Add",
"(",
"fullkey",
",",
"valueToAdd",
")",
";",
"}",
"break",
";",
"case",
"ConfigurationAction",
".",
"Remove",
":",
"results",
".",
"Remove",
"(",
"fullkey",
")",
";",
"break",
";",
"default",
":",
"throw",
"new",
"NotSupportedException",
"(",
"$\"",
"Unsupported action: [",
"{",
"action",
"}",
"]",
"\"",
")",
";",
"}",
"}",
"private",
"static",
"string",
"GetKey",
"(",
"Stack",
"<",
"string",
">",
"context",
",",
"string",
"name",
")",
"{",
"return",
"string",
".",
"Join",
"(",
"ConfigurationPath",
".",
"KeyDelimiter",
",",
"context",
".",
"Reverse",
"(",
")",
".",
"Concat",
"(",
"new",
"[",
"]",
"{",
"name",
"}",
")",
")",
";",
"}",
"}"
] |
ConfigurationProvider for *.config files.
|
[
"ConfigurationProvider",
"for",
"*",
".",
"config",
"files",
"."
] |
[
"/// <summary>",
"/// The key/value attribute names.",
"/// </summary>"
] |
[
{
"param": "IConfigurationParser",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "IConfigurationParser",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": [
{
"identifier": "example",
"docstring": "The following configuration file will result in the following key-value\npairs in the dictionary:\n@{\n{ \"nodea:TheKey\" : \"TheValue\" },\n{ \"nodeb:nested:NestedKey\" : \"ValueA\" },\n{ \"nodeb:nested:NestedKey2\" : \"ValueB\" },\n}\n\n",
"docstring_tokens": [
"The",
"following",
"configuration",
"file",
"will",
"result",
"in",
"the",
"following",
"key",
"-",
"value",
"pairs",
"in",
"the",
"dictionary",
":",
"@",
"{",
"{",
"\"",
"nodea",
":",
"TheKey",
"\"",
":",
"\"",
"TheValue",
"\"",
"}",
"{",
"\"",
"nodeb",
":",
"nested",
":",
"NestedKey",
"\"",
":",
"\"",
"ValueA",
"\"",
"}",
"{",
"\"",
"nodeb",
":",
"nested",
":",
"NestedKey2",
"\"",
":",
"\"",
"ValueB",
"\"",
"}",
"}"
]
}
]
}
| false
| 22
| 736
| 390
|
af0364e3a649aa9b713461eb21cc09f3ff6ecf7a
|
zjm3007210057/leetcode
|
club.isparkle.leetcode/string/LongestSubstringWithoutRepeatingCharacters.java
|
[
"Apache-2.0"
] |
Java
|
LongestSubstringWithoutRepeatingCharacters
|
/**
* 3. Longest Substring Without Repeating Characters
* <p>
* Given a string, find the length of the longest substring without repeating characters.
* Example 1:
* Input: "abcabcbb"
* Output: 3
* Explanation: The answer is "abc", with the length of 3.
*
* Example 2:
* Input: "bbbbb"
* Output: 1
* Explanation: The answer is "b", with the length of 1.
*
* Example 3:
* Input: "pwwkew"
* Output: 3
* Explanation: The answer is "wke", with the length of 3.
*
* Note that the answer must be a substring, "pwke" is a subsequence and not a substring
* <p>
* Created by zjm on 2019/8/30 19:45
*/
|
3. Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Note that the answer must be a substring, "pwke" is a subsequence and not a substring
Created by zjm on 2019/8/30 19:45
|
[
"3",
".",
"Longest",
"Substring",
"Without",
"Repeating",
"Characters",
"Given",
"a",
"string",
"find",
"the",
"length",
"of",
"the",
"longest",
"substring",
"without",
"repeating",
"characters",
".",
"Example",
"1",
":",
"Input",
":",
"\"",
"abcabcbb",
"\"",
"Output",
":",
"3",
"Explanation",
":",
"The",
"answer",
"is",
"\"",
"abc",
"\"",
"with",
"the",
"length",
"of",
"3",
".",
"Example",
"2",
":",
"Input",
":",
"\"",
"bbbbb",
"\"",
"Output",
":",
"1",
"Explanation",
":",
"The",
"answer",
"is",
"\"",
"b",
"\"",
"with",
"the",
"length",
"of",
"1",
".",
"Example",
"3",
":",
"Input",
":",
"\"",
"pwwkew",
"\"",
"Output",
":",
"3",
"Explanation",
":",
"The",
"answer",
"is",
"\"",
"wke",
"\"",
"with",
"the",
"length",
"of",
"3",
".",
"Note",
"that",
"the",
"answer",
"must",
"be",
"a",
"substring",
"\"",
"pwke",
"\"",
"is",
"a",
"subsequence",
"and",
"not",
"a",
"substring",
"Created",
"by",
"zjm",
"on",
"2019",
"/",
"8",
"/",
"30",
"19",
":",
"45"
] |
public class LongestSubstringWithoutRepeatingCharacters {
//采用双指针和map,每次往map中放入字符,判断字符是否已经存在,如果存在则更新左指针,结果为右指针和左指针之差的最大值
public int lengthOfLongestSubstring(String s) {
int res = 0;
int l = 0;
Map<Character, Integer> map = new HashMap();
for(int i = 0; i < s.length(); i++) {
Integer tmp = map.get(s.charAt(i));
if(tmp != null && tmp >= l) {
res = Math.max(res, i - l);
l = tmp + 1;
}else {
res = Math.max(res, i - l + 1);
}
map.put(s.charAt(i), i);
}
return res;
}
}
|
[
"public",
"class",
"LongestSubstringWithoutRepeatingCharacters",
"{",
"public",
"int",
"lengthOfLongestSubstring",
"(",
"String",
"s",
")",
"{",
"int",
"res",
"=",
"0",
";",
"int",
"l",
"=",
"0",
";",
"Map",
"<",
"Character",
",",
"Integer",
">",
"map",
"=",
"new",
"HashMap",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"s",
".",
"length",
"(",
")",
";",
"i",
"++",
")",
"{",
"Integer",
"tmp",
"=",
"map",
".",
"get",
"(",
"s",
".",
"charAt",
"(",
"i",
")",
")",
";",
"if",
"(",
"tmp",
"!=",
"null",
"&&",
"tmp",
">=",
"l",
")",
"{",
"res",
"=",
"Math",
".",
"max",
"(",
"res",
",",
"i",
"-",
"l",
")",
";",
"l",
"=",
"tmp",
"+",
"1",
";",
"}",
"else",
"{",
"res",
"=",
"Math",
".",
"max",
"(",
"res",
",",
"i",
"-",
"l",
"+",
"1",
")",
";",
"}",
"map",
".",
"put",
"(",
"s",
".",
"charAt",
"(",
"i",
")",
",",
"i",
")",
";",
"}",
"return",
"res",
";",
"}",
"}"
] |
3.
|
[
"3",
"."
] |
[
"//采用双指针和map,每次往map中放入字符,判断字符是否已经存在,如果存在则更新左指针,结果为右指针和左指针之差的最大值"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 15
| 185
| 194
|
d9eb22cb1ee782cd89e32b07aba05cc03ba6dd37
|
SOFAgh/CADability
|
CADability/JsonSerialize.cs
|
[
"MIT"
] |
C#
|
JsonDict
|
/// <summary>
/// Actually a Json object: a dictionary of string->value pairs, where the value is either a string, boolean, null or List<object> (list of objects).
/// Numbers are kept as strings, because it depends on their usage, whether they will be parsed as double, int, long, ulong, byte etc.
/// </summary>
|
Actually a Json object: a dictionary of string->value pairs, where the value is either a string, boolean, null or List (list of objects).
Numbers are kept as strings, because it depends on their usage, whether they will be parsed as double, int, long, ulong, byte etc.
|
[
"Actually",
"a",
"Json",
"object",
":",
"a",
"dictionary",
"of",
"string",
"-",
">",
"value",
"pairs",
"where",
"the",
"value",
"is",
"either",
"a",
"string",
"boolean",
"null",
"or",
"List",
"(",
"list",
"of",
"objects",
")",
".",
"Numbers",
"are",
"kept",
"as",
"strings",
"because",
"it",
"depends",
"on",
"their",
"usage",
"whether",
"they",
"will",
"be",
"parsed",
"as",
"double",
"int",
"long",
"ulong",
"byte",
"etc",
"."
] |
class JsonDict : Dictionary<string, object>, IJsonReadData
{
private JsonSerialize root;
public JsonDict(JsonSerialize root) : base()
{
this.root = root;
}
object IJsonReadData.GetProperty(string name)
{
return this[name];
}
bool IJsonReadData.HasProperty(string name)
{
return ContainsKey(name);
}
string IJsonReadData.GetStringProperty(string name)
{
return this[name] as string;
}
int IJsonReadData.GetIntProperty(string name)
{
return Convert.ToInt32(this[name]);
}
double IJsonReadData.GetDoubleProperty(string name)
{
return (double)this[name];
}
object IJsonReadData.GetProperty(string name, Type type)
{
object val = this[name];
if (SerializeAsStruct(type))
{
ConstructorInfo cie = type.GetConstructor(BindingFlags.CreateInstance | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, Type.DefaultBinder, new Type[] { typeof(IJsonReadStruct) }, null);
return cie.Invoke(new object[] { new JsonArray(val as List<object>, root) });
}
if ((type.IsPrimitive || type.IsEnum) && val is string)
{
return Parse(val, type);
}
if (type.IsPrimitive && val is double)
{
return Convert.ChangeType(val, type);
}
if (type.IsArray)
{
ConstructorInfo cie = type.GetConstructor(BindingFlags.CreateInstance | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, Type.DefaultBinder, new Type[] { typeof(int) }, null);
Type eltp = type.GetElementType();
Array sar = cie.Invoke(new object[] { (val as List<object>).Count }) as Array;
if (eltp.IsArray)
{
ConstructorInfo subci = eltp.GetConstructor(BindingFlags.CreateInstance | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, Type.DefaultBinder, new Type[] { typeof(int) }, null);
List<object> kve = val as List<object>;
for (int i = 0; i < kve.Count; i++)
{
List<object> sublist = kve[i] as List<object>;
Array ssar = subci.Invoke(new object[] { sublist.Count }) as Array;
for (int j = 0; j < sublist.Count; j++)
{
ssar.SetValue(sublist[j], j);
}
sar.SetValue(ssar, i);
}
return sar;
}
else if (SerializeAsStruct(eltp))
{
ConstructorInfo cieltp = eltp.GetConstructor(BindingFlags.CreateInstance | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, Type.DefaultBinder, new Type[] { typeof(IJsonReadStruct) }, null);
List<object> kve = val as List<object>;
for (int i = 0; i < kve.Count; i++)
{
sar.SetValue(cieltp.Invoke(new object[] { new JsonArray(kve[i] as List<object>, root) }), i);
}
return sar;
}
else
{
List<object> kve = val as List<object>;
for (int i = 0; i < kve.Count; i++)
{
sar.SetValue(kve[i], i);
}
return sar;
}
}
else if (type.GetInterface("IList") != null)
{
ConstructorInfo cie = type.GetConstructor(BindingFlags.CreateInstance | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, Type.DefaultBinder, new Type[0], null);
IList ar = cie.Invoke(new object[0]) as IList;
List<object> kve = val as List<object>;
for (int i = 0; i < kve.Count; i++)
{
ar.Add(kve[i]);
}
return ar;
}
return val;
}
T IJsonReadData.GetProperty<T>(string name)
{
if (!ContainsKey(name)) return default(T);
return (T)(this as IJsonReadData).GetProperty(name, typeof(T));
}
bool IJsonReadData.TryGetProperty<T>(string name, out T val)
{
if (ContainsKey(name))
{
val = (this as IJsonReadData).GetProperty(name, typeof(T)) as T;
return true;
}
val = default(T);
return false;
}
T IJsonReadData.GetPropertyOrDefault<T>(string name)
{
if (ContainsKey(name))
{
object o = (this as IJsonReadData).GetProperty(name, typeof(T));
if (o != null && o is T) return (T)o;
}
return default(T);
}
void IJsonReadData.RegisterForSerializationDoneCallback(IJsonSerializeDone toCall)
{
root.RegisterForSerializationDoneCallback(toCall);
}
Dictionary<string, object>.Enumerator IJsonReadData.GetEnumerator()
{
return this.GetEnumerator();
}
public int Version { get; set; }
int IJsonReadData.Version => Version;
}
|
[
"class",
"JsonDict",
":",
"Dictionary",
"<",
"string",
",",
"object",
">",
",",
"IJsonReadData",
"{",
"private",
"JsonSerialize",
"root",
";",
"public",
"JsonDict",
"(",
"JsonSerialize",
"root",
")",
":",
"base",
"(",
")",
"{",
"this",
".",
"root",
"=",
"root",
";",
"}",
"object",
"IJsonReadData",
".",
"GetProperty",
"(",
"string",
"name",
")",
"{",
"return",
"this",
"[",
"name",
"]",
";",
"}",
"bool",
"IJsonReadData",
".",
"HasProperty",
"(",
"string",
"name",
")",
"{",
"return",
"ContainsKey",
"(",
"name",
")",
";",
"}",
"string",
"IJsonReadData",
".",
"GetStringProperty",
"(",
"string",
"name",
")",
"{",
"return",
"this",
"[",
"name",
"]",
"as",
"string",
";",
"}",
"int",
"IJsonReadData",
".",
"GetIntProperty",
"(",
"string",
"name",
")",
"{",
"return",
"Convert",
".",
"ToInt32",
"(",
"this",
"[",
"name",
"]",
")",
";",
"}",
"double",
"IJsonReadData",
".",
"GetDoubleProperty",
"(",
"string",
"name",
")",
"{",
"return",
"(",
"double",
")",
"this",
"[",
"name",
"]",
";",
"}",
"object",
"IJsonReadData",
".",
"GetProperty",
"(",
"string",
"name",
",",
"Type",
"type",
")",
"{",
"object",
"val",
"=",
"this",
"[",
"name",
"]",
";",
"if",
"(",
"SerializeAsStruct",
"(",
"type",
")",
")",
"{",
"ConstructorInfo",
"cie",
"=",
"type",
".",
"GetConstructor",
"(",
"BindingFlags",
".",
"CreateInstance",
"|",
"BindingFlags",
".",
"Instance",
"|",
"BindingFlags",
".",
"Public",
"|",
"BindingFlags",
".",
"NonPublic",
",",
"Type",
".",
"DefaultBinder",
",",
"new",
"Type",
"[",
"]",
"{",
"typeof",
"(",
"IJsonReadStruct",
")",
"}",
",",
"null",
")",
";",
"return",
"cie",
".",
"Invoke",
"(",
"new",
"object",
"[",
"]",
"{",
"new",
"JsonArray",
"(",
"val",
"as",
"List",
"<",
"object",
">",
",",
"root",
")",
"}",
")",
";",
"}",
"if",
"(",
"(",
"type",
".",
"IsPrimitive",
"||",
"type",
".",
"IsEnum",
")",
"&&",
"val",
"is",
"string",
")",
"{",
"return",
"Parse",
"(",
"val",
",",
"type",
")",
";",
"}",
"if",
"(",
"type",
".",
"IsPrimitive",
"&&",
"val",
"is",
"double",
")",
"{",
"return",
"Convert",
".",
"ChangeType",
"(",
"val",
",",
"type",
")",
";",
"}",
"if",
"(",
"type",
".",
"IsArray",
")",
"{",
"ConstructorInfo",
"cie",
"=",
"type",
".",
"GetConstructor",
"(",
"BindingFlags",
".",
"CreateInstance",
"|",
"BindingFlags",
".",
"Instance",
"|",
"BindingFlags",
".",
"Public",
"|",
"BindingFlags",
".",
"NonPublic",
",",
"Type",
".",
"DefaultBinder",
",",
"new",
"Type",
"[",
"]",
"{",
"typeof",
"(",
"int",
")",
"}",
",",
"null",
")",
";",
"Type",
"eltp",
"=",
"type",
".",
"GetElementType",
"(",
")",
";",
"Array",
"sar",
"=",
"cie",
".",
"Invoke",
"(",
"new",
"object",
"[",
"]",
"{",
"(",
"val",
"as",
"List",
"<",
"object",
">",
")",
".",
"Count",
"}",
")",
"as",
"Array",
";",
"if",
"(",
"eltp",
".",
"IsArray",
")",
"{",
"ConstructorInfo",
"subci",
"=",
"eltp",
".",
"GetConstructor",
"(",
"BindingFlags",
".",
"CreateInstance",
"|",
"BindingFlags",
".",
"Instance",
"|",
"BindingFlags",
".",
"Public",
"|",
"BindingFlags",
".",
"NonPublic",
",",
"Type",
".",
"DefaultBinder",
",",
"new",
"Type",
"[",
"]",
"{",
"typeof",
"(",
"int",
")",
"}",
",",
"null",
")",
";",
"List",
"<",
"object",
">",
"kve",
"=",
"val",
"as",
"List",
"<",
"object",
">",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"kve",
".",
"Count",
";",
"i",
"++",
")",
"{",
"List",
"<",
"object",
">",
"sublist",
"=",
"kve",
"[",
"i",
"]",
"as",
"List",
"<",
"object",
">",
";",
"Array",
"ssar",
"=",
"subci",
".",
"Invoke",
"(",
"new",
"object",
"[",
"]",
"{",
"sublist",
".",
"Count",
"}",
")",
"as",
"Array",
";",
"for",
"(",
"int",
"j",
"=",
"0",
";",
"j",
"<",
"sublist",
".",
"Count",
";",
"j",
"++",
")",
"{",
"ssar",
".",
"SetValue",
"(",
"sublist",
"[",
"j",
"]",
",",
"j",
")",
";",
"}",
"sar",
".",
"SetValue",
"(",
"ssar",
",",
"i",
")",
";",
"}",
"return",
"sar",
";",
"}",
"else",
"if",
"(",
"SerializeAsStruct",
"(",
"eltp",
")",
")",
"{",
"ConstructorInfo",
"cieltp",
"=",
"eltp",
".",
"GetConstructor",
"(",
"BindingFlags",
".",
"CreateInstance",
"|",
"BindingFlags",
".",
"Instance",
"|",
"BindingFlags",
".",
"Public",
"|",
"BindingFlags",
".",
"NonPublic",
",",
"Type",
".",
"DefaultBinder",
",",
"new",
"Type",
"[",
"]",
"{",
"typeof",
"(",
"IJsonReadStruct",
")",
"}",
",",
"null",
")",
";",
"List",
"<",
"object",
">",
"kve",
"=",
"val",
"as",
"List",
"<",
"object",
">",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"kve",
".",
"Count",
";",
"i",
"++",
")",
"{",
"sar",
".",
"SetValue",
"(",
"cieltp",
".",
"Invoke",
"(",
"new",
"object",
"[",
"]",
"{",
"new",
"JsonArray",
"(",
"kve",
"[",
"i",
"]",
"as",
"List",
"<",
"object",
">",
",",
"root",
")",
"}",
")",
",",
"i",
")",
";",
"}",
"return",
"sar",
";",
"}",
"else",
"{",
"List",
"<",
"object",
">",
"kve",
"=",
"val",
"as",
"List",
"<",
"object",
">",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"kve",
".",
"Count",
";",
"i",
"++",
")",
"{",
"sar",
".",
"SetValue",
"(",
"kve",
"[",
"i",
"]",
",",
"i",
")",
";",
"}",
"return",
"sar",
";",
"}",
"}",
"else",
"if",
"(",
"type",
".",
"GetInterface",
"(",
"\"",
"IList",
"\"",
")",
"!=",
"null",
")",
"{",
"ConstructorInfo",
"cie",
"=",
"type",
".",
"GetConstructor",
"(",
"BindingFlags",
".",
"CreateInstance",
"|",
"BindingFlags",
".",
"Instance",
"|",
"BindingFlags",
".",
"Public",
"|",
"BindingFlags",
".",
"NonPublic",
",",
"Type",
".",
"DefaultBinder",
",",
"new",
"Type",
"[",
"0",
"]",
",",
"null",
")",
";",
"IList",
"ar",
"=",
"cie",
".",
"Invoke",
"(",
"new",
"object",
"[",
"0",
"]",
")",
"as",
"IList",
";",
"List",
"<",
"object",
">",
"kve",
"=",
"val",
"as",
"List",
"<",
"object",
">",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"kve",
".",
"Count",
";",
"i",
"++",
")",
"{",
"ar",
".",
"Add",
"(",
"kve",
"[",
"i",
"]",
")",
";",
"}",
"return",
"ar",
";",
"}",
"return",
"val",
";",
"}",
"T",
"IJsonReadData",
".",
"GetProperty",
"<",
"T",
">",
"(",
"string",
"name",
")",
"{",
"if",
"(",
"!",
"ContainsKey",
"(",
"name",
")",
")",
"return",
"default",
"(",
"T",
")",
";",
"return",
"(",
"T",
")",
"(",
"this",
"as",
"IJsonReadData",
")",
".",
"GetProperty",
"(",
"name",
",",
"typeof",
"(",
"T",
")",
")",
";",
"}",
"bool",
"IJsonReadData",
".",
"TryGetProperty",
"<",
"T",
">",
"(",
"string",
"name",
",",
"out",
"T",
"val",
")",
"{",
"if",
"(",
"ContainsKey",
"(",
"name",
")",
")",
"{",
"val",
"=",
"(",
"this",
"as",
"IJsonReadData",
")",
".",
"GetProperty",
"(",
"name",
",",
"typeof",
"(",
"T",
")",
")",
"as",
"T",
";",
"return",
"true",
";",
"}",
"val",
"=",
"default",
"(",
"T",
")",
";",
"return",
"false",
";",
"}",
"T",
"IJsonReadData",
".",
"GetPropertyOrDefault",
"<",
"T",
">",
"(",
"string",
"name",
")",
"{",
"if",
"(",
"ContainsKey",
"(",
"name",
")",
")",
"{",
"object",
"o",
"=",
"(",
"this",
"as",
"IJsonReadData",
")",
".",
"GetProperty",
"(",
"name",
",",
"typeof",
"(",
"T",
")",
")",
";",
"if",
"(",
"o",
"!=",
"null",
"&&",
"o",
"is",
"T",
")",
"return",
"(",
"T",
")",
"o",
";",
"}",
"return",
"default",
"(",
"T",
")",
";",
"}",
"void",
"IJsonReadData",
".",
"RegisterForSerializationDoneCallback",
"(",
"IJsonSerializeDone",
"toCall",
")",
"{",
"root",
".",
"RegisterForSerializationDoneCallback",
"(",
"toCall",
")",
";",
"}",
"Dictionary",
"<",
"string",
",",
"object",
">",
".",
"Enumerator",
"IJsonReadData",
".",
"GetEnumerator",
"(",
")",
"{",
"return",
"this",
".",
"GetEnumerator",
"(",
")",
";",
"}",
"public",
"int",
"Version",
"{",
"get",
";",
"set",
";",
"}",
"int",
"IJsonReadData",
".",
"Version",
"=>",
"Version",
";",
"}"
] |
Actually a Json object: a dictionary of string->value pairs, where the value is either a string, boolean, null or List<object> (list of objects).
|
[
"Actually",
"a",
"Json",
"object",
":",
"a",
"dictionary",
"of",
"string",
"-",
">",
"value",
"pairs",
"where",
"the",
"value",
"is",
"either",
"a",
"string",
"boolean",
"null",
"or",
"List<object",
">",
"(",
"list",
"of",
"objects",
")",
"."
] |
[
"// all numbers are read as double"
] |
[
{
"param": "IJsonReadData",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "IJsonReadData",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 28
| 1,084
| 76
|
b3a5e7afe55ccc1ef738017019df12c89605357d
|
wterkaj/ApertusVR
|
plugins/track/head/kinectHeadTracking/3rdParty/kinect/v2.0_1409/Samples/Managed/KinectFusionExplorer-WPF/Properties/Resources.Designer.cs
|
[
"MIT"
] |
C#
|
Resources
|
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
|
A strongly-typed resource class, for looking up localized strings, etc.
|
[
"A",
"strongly",
"-",
"typed",
"resource",
"class",
"for",
"looking",
"up",
"localized",
"strings",
"etc",
"."
] |
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.Samples.Kinect.KinectFusionExplorer.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
internal static string CameraTrackingFailed {
get {
return ResourceManager.GetString("CameraTrackingFailed", resourceCulture);
}
}
internal static string ErrorSaveMesh {
get {
return ResourceManager.GetString("ErrorSaveMesh", resourceCulture);
}
}
internal static string ErrorSaveMeshOutOfMemory {
get {
return ResourceManager.GetString("ErrorSaveMeshOutOfMemory", resourceCulture);
}
}
internal static string Fps {
get {
return ResourceManager.GetString("Fps", resourceCulture);
}
}
internal static string IntroductoryMessage {
get {
return ResourceManager.GetString("IntroductoryMessage", resourceCulture);
}
}
internal static string InvalidMeshArgument {
get {
return ResourceManager.GetString("InvalidMeshArgument", resourceCulture);
}
}
internal static string MeshNullVolume {
get {
return ResourceManager.GetString("MeshNullVolume", resourceCulture);
}
}
internal static string MeshSaveCanceled {
get {
return ResourceManager.GetString("MeshSaveCanceled", resourceCulture);
}
}
internal static string MeshSaved {
get {
return ResourceManager.GetString("MeshSaved", resourceCulture);
}
}
internal static string MissingPrerequisite {
get {
return ResourceManager.GetString("MissingPrerequisite", resourceCulture);
}
}
internal static string NoDirectX11CompatibleDeviceOrInvalidDeviceIndex {
get {
return ResourceManager.GetString("NoDirectX11CompatibleDeviceOrInvalidDeviceIndex", resourceCulture);
}
}
internal static string NoReadyKinect {
get {
return ResourceManager.GetString("NoReadyKinect", resourceCulture);
}
}
internal static string OutOfMemory {
get {
return ResourceManager.GetString("OutOfMemory", resourceCulture);
}
}
internal static string PoseFinderNotEnoughMatches {
get {
return ResourceManager.GetString("PoseFinderNotEnoughMatches", resourceCulture);
}
}
internal static string PoseFinderPoseHistoryFull {
get {
return ResourceManager.GetString("PoseFinderPoseHistoryFull", resourceCulture);
}
}
internal static string ResetFailed {
get {
return ResourceManager.GetString("ResetFailed", resourceCulture);
}
}
internal static string ResetVolume {
get {
return ResourceManager.GetString("ResetVolume", resourceCulture);
}
}
internal static string ResetVolumeAuto {
get {
return ResourceManager.GetString("ResetVolumeAuto", resourceCulture);
}
}
internal static string SavingMesh {
get {
return ResourceManager.GetString("SavingMesh", resourceCulture);
}
}
internal static string VolumeResolution {
get {
return ResourceManager.GetString("VolumeResolution", resourceCulture);
}
}
}
|
[
"[",
"global",
"::",
"System",
".",
"CodeDom",
".",
"Compiler",
".",
"GeneratedCodeAttribute",
"(",
"\"",
"System.Resources.Tools.StronglyTypedResourceBuilder",
"\"",
",",
"\"",
"4.0.0.0",
"\"",
")",
"]",
"[",
"global",
"::",
"System",
".",
"Diagnostics",
".",
"DebuggerNonUserCodeAttribute",
"(",
")",
"]",
"[",
"global",
"::",
"System",
".",
"Runtime",
".",
"CompilerServices",
".",
"CompilerGeneratedAttribute",
"(",
")",
"]",
"internal",
"class",
"Resources",
"{",
"private",
"static",
"global",
"::",
"System",
".",
"Resources",
".",
"ResourceManager",
"resourceMan",
";",
"private",
"static",
"global",
"::",
"System",
".",
"Globalization",
".",
"CultureInfo",
"resourceCulture",
";",
"[",
"global",
"::",
"System",
".",
"Diagnostics",
".",
"CodeAnalysis",
".",
"SuppressMessageAttribute",
"(",
"\"",
"Microsoft.Performance",
"\"",
",",
"\"",
"CA1811:AvoidUncalledPrivateCode",
"\"",
")",
"]",
"internal",
"Resources",
"(",
")",
"{",
"}",
"[",
"global",
"::",
"System",
".",
"ComponentModel",
".",
"EditorBrowsableAttribute",
"(",
"global",
"::",
"System",
".",
"ComponentModel",
".",
"EditorBrowsableState",
".",
"Advanced",
")",
"]",
"internal",
"static",
"global",
"::",
"System",
".",
"Resources",
".",
"ResourceManager",
"ResourceManager",
"{",
"get",
"{",
"if",
"(",
"object",
".",
"ReferenceEquals",
"(",
"resourceMan",
",",
"null",
")",
")",
"{",
"global",
"::",
"System",
".",
"Resources",
".",
"ResourceManager",
"temp",
"=",
"new",
"global",
"::",
"System",
".",
"Resources",
".",
"ResourceManager",
"(",
"\"",
"Microsoft.Samples.Kinect.KinectFusionExplorer.Properties.Resources",
"\"",
",",
"typeof",
"(",
"Resources",
")",
".",
"Assembly",
")",
";",
"resourceMan",
"=",
"temp",
";",
"}",
"return",
"resourceMan",
";",
"}",
"}",
"[",
"global",
"::",
"System",
".",
"ComponentModel",
".",
"EditorBrowsableAttribute",
"(",
"global",
"::",
"System",
".",
"ComponentModel",
".",
"EditorBrowsableState",
".",
"Advanced",
")",
"]",
"internal",
"static",
"global",
"::",
"System",
".",
"Globalization",
".",
"CultureInfo",
"Culture",
"{",
"get",
"{",
"return",
"resourceCulture",
";",
"}",
"set",
"{",
"resourceCulture",
"=",
"value",
";",
"}",
"}",
"internal",
"static",
"string",
"CameraTrackingFailed",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"CameraTrackingFailed",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"ErrorSaveMesh",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"ErrorSaveMesh",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"ErrorSaveMeshOutOfMemory",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"ErrorSaveMeshOutOfMemory",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Fps",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Fps",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"IntroductoryMessage",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"IntroductoryMessage",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"InvalidMeshArgument",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"InvalidMeshArgument",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"MeshNullVolume",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"MeshNullVolume",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"MeshSaveCanceled",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"MeshSaveCanceled",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"MeshSaved",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"MeshSaved",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"MissingPrerequisite",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"MissingPrerequisite",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"NoDirectX11CompatibleDeviceOrInvalidDeviceIndex",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"NoDirectX11CompatibleDeviceOrInvalidDeviceIndex",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"NoReadyKinect",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"NoReadyKinect",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"OutOfMemory",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"OutOfMemory",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"PoseFinderNotEnoughMatches",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"PoseFinderNotEnoughMatches",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"PoseFinderPoseHistoryFull",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"PoseFinderPoseHistoryFull",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"ResetFailed",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"ResetFailed",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"ResetVolume",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"ResetVolume",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"ResetVolumeAuto",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"ResetVolumeAuto",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"SavingMesh",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"SavingMesh",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"VolumeResolution",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"VolumeResolution",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"}"
] |
A strongly-typed resource class, for looking up localized strings, etc.
|
[
"A",
"strongly",
"-",
"typed",
"resource",
"class",
"for",
"looking",
"up",
"localized",
"strings",
"etc",
"."
] |
[
"/// <summary>",
"/// Returns the cached ResourceManager instance used by this class.",
"/// </summary>",
"/// <summary>",
"/// Overrides the current thread's CurrentUICulture property for all",
"/// resource lookups using this strongly typed resource class.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Kinect Fusion camera tracking failed. Align the camera to the last tracked position..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Error saving Kinect Fusion mesh!.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Error saving Kinect Fusion mesh - out of memory!.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Fps: {0:0.00}.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Click "Reset Reconstruction" to clear.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Invalid mesh arguments. Saving mesh process aborted.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Cannot create mesh of non-existent reconstruction.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Mesh save canceled.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Saved Kinect Fusion mesh.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to A prerequisite component for Kinect Fusion is missing. Please refer to the Toolkit documentation for assistance.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to No DirectX11 device detected, or invalid device index - Kinect Fusion requires a DirectX11 device for GPU-based reconstruction..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to No ready Kinect found!.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Out of memory error initializing reconstruction - try a smaller reconstruction volume.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to FindCameraPose exited early as not good enough pose matches..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Kinect Fusion Camera Pose Finder pose history is full, overwritten oldest pose to store current pose..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Kinect Fusion reset reconstruction call failed.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Reconstruction has been reset.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Kinect Fusion camera tracking failed, automatically reset volume.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Creating and saving mesh of reconstruction, please wait....",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Volume resolution should be greater than 0 and multiple of 32.",
"/// </summary>"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 17
| 827
| 84
|
aa6e231c79b5ccf1121e0fad1debb80580f9a85d
|
microsoft/Akoustos
|
src/audio.py
|
[
"MIT"
] |
Python
|
Audio
|
Container for audio samples
Initializing an `Audio` object directly requires the specification of the
sample rate. Use `Audio.from_file` or `Audio.from_bytesio` with
`sample_rate=None` to use a native sampling rate.
Args:
samples (np.array): The audio samples
sample_rate (integer): The sampling rate for the audio samples
Returns:
An initialized `Audio` object
|
Container for audio samples
Initializing an `Audio` object directly requires the specification of the
sample rate.
|
[
"Container",
"for",
"audio",
"samples",
"Initializing",
"an",
"`",
"Audio",
"`",
"object",
"directly",
"requires",
"the",
"specification",
"of",
"the",
"sample",
"rate",
"."
] |
class Audio:
"""Container for audio samples
Initializing an `Audio` object directly requires the specification of the
sample rate. Use `Audio.from_file` or `Audio.from_bytesio` with
`sample_rate=None` to use a native sampling rate.
Args:
samples (np.array): The audio samples
sample_rate (integer): The sampling rate for the audio samples
Returns:
An initialized `Audio` object
"""
def __init__(self, samples, sample_rate):
# Do not move these lines; it will break Pytorch training
self.samples = samples
self.sample_rate = sample_rate
@classmethod
def load(cls, path):
"""Load audio from files
Deal with the various possible input types to load an audio
file and generate a spectrogram
Args:
path (str, Path): path to an audio file
Returns:
Audio: attributes samples and sample_rate
"""
samples, sample_rate = librosa.load(path)
return cls(samples, sample_rate)
def time_to_sample(self, time):
"""Given a time, convert it to the corresponding sample
Args:
time: The time to multiply with the sample_rate
Returns:
sample: The rounded sample
"""
return int(time * self.sample_rate)
def trim(self, start_time, end_time):
"""Trim Audio object in time
Args:
start_time: time in seconds for start of extracted clip
end_time: time in seconds for end of extracted clip
Returns:
a new Audio object containing samples from start_time to end_time
"""
start_sample = self.time_to_sample(start_time)
end_sample = self.time_to_sample(end_time)
samples_trimmed = self.samples[start_sample:end_sample]
return Audio(
samples_trimmed,
self.sample_rate
)
def duration(self):
"""Return duration of Audio
Returns:
duration (float): The duration of the Audio
"""
return len(self.samples) / self.sample_rate
def generate_spectrogram(self, axis=False, filename=None, sr = 22050, hop_length=512, fmin=None, fmax=None, x_axis='time', y_axis='linear', cmap = 'viridis'):
# reference: https://librosa.org/doc/main/generated/librosa.display.specshow.html
# colormap: https://matplotlib.org/stable/tutorials/colors/colormaps.html
fig, ax = plt.subplots()
if axis == False:
plt.axis('off')
D = librosa.amplitude_to_db(np.abs(librosa.stft(self.samples)), ref=np.max)
img = librosa.display.specshow(D, x_axis=x_axis, y_axis=y_axis, sr=sr, hop_length=hop_length, fmin=fmin, fmax=fmax, ax=ax, cmap = cmap)
if filename:
image_path = Path(filename)
fig.savefig(image_path)
plt.close()
|
[
"class",
"Audio",
":",
"def",
"__init__",
"(",
"self",
",",
"samples",
",",
"sample_rate",
")",
":",
"self",
".",
"samples",
"=",
"samples",
"self",
".",
"sample_rate",
"=",
"sample_rate",
"@",
"classmethod",
"def",
"load",
"(",
"cls",
",",
"path",
")",
":",
"\"\"\"Load audio from files\n\n Deal with the various possible input types to load an audio\n file and generate a spectrogram\n\n Args:\n path (str, Path): path to an audio file\n\n Returns:\n Audio: attributes samples and sample_rate\n \"\"\"",
"samples",
",",
"sample_rate",
"=",
"librosa",
".",
"load",
"(",
"path",
")",
"return",
"cls",
"(",
"samples",
",",
"sample_rate",
")",
"def",
"time_to_sample",
"(",
"self",
",",
"time",
")",
":",
"\"\"\"Given a time, convert it to the corresponding sample\n Args:\n time: The time to multiply with the sample_rate\n Returns:\n sample: The rounded sample\n \"\"\"",
"return",
"int",
"(",
"time",
"*",
"self",
".",
"sample_rate",
")",
"def",
"trim",
"(",
"self",
",",
"start_time",
",",
"end_time",
")",
":",
"\"\"\"Trim Audio object in time\n\n Args:\n start_time: time in seconds for start of extracted clip\n end_time: time in seconds for end of extracted clip\n Returns:\n a new Audio object containing samples from start_time to end_time\n \"\"\"",
"start_sample",
"=",
"self",
".",
"time_to_sample",
"(",
"start_time",
")",
"end_sample",
"=",
"self",
".",
"time_to_sample",
"(",
"end_time",
")",
"samples_trimmed",
"=",
"self",
".",
"samples",
"[",
"start_sample",
":",
"end_sample",
"]",
"return",
"Audio",
"(",
"samples_trimmed",
",",
"self",
".",
"sample_rate",
")",
"def",
"duration",
"(",
"self",
")",
":",
"\"\"\"Return duration of Audio\n\n Returns:\n duration (float): The duration of the Audio\n \"\"\"",
"return",
"len",
"(",
"self",
".",
"samples",
")",
"/",
"self",
".",
"sample_rate",
"def",
"generate_spectrogram",
"(",
"self",
",",
"axis",
"=",
"False",
",",
"filename",
"=",
"None",
",",
"sr",
"=",
"22050",
",",
"hop_length",
"=",
"512",
",",
"fmin",
"=",
"None",
",",
"fmax",
"=",
"None",
",",
"x_axis",
"=",
"'time'",
",",
"y_axis",
"=",
"'linear'",
",",
"cmap",
"=",
"'viridis'",
")",
":",
"fig",
",",
"ax",
"=",
"plt",
".",
"subplots",
"(",
")",
"if",
"axis",
"==",
"False",
":",
"plt",
".",
"axis",
"(",
"'off'",
")",
"D",
"=",
"librosa",
".",
"amplitude_to_db",
"(",
"np",
".",
"abs",
"(",
"librosa",
".",
"stft",
"(",
"self",
".",
"samples",
")",
")",
",",
"ref",
"=",
"np",
".",
"max",
")",
"img",
"=",
"librosa",
".",
"display",
".",
"specshow",
"(",
"D",
",",
"x_axis",
"=",
"x_axis",
",",
"y_axis",
"=",
"y_axis",
",",
"sr",
"=",
"sr",
",",
"hop_length",
"=",
"hop_length",
",",
"fmin",
"=",
"fmin",
",",
"fmax",
"=",
"fmax",
",",
"ax",
"=",
"ax",
",",
"cmap",
"=",
"cmap",
")",
"if",
"filename",
":",
"image_path",
"=",
"Path",
"(",
"filename",
")",
"fig",
".",
"savefig",
"(",
"image_path",
")",
"plt",
".",
"close",
"(",
")"
] |
Container for audio samples
Initializing an `Audio` object directly requires the specification of the
sample rate.
|
[
"Container",
"for",
"audio",
"samples",
"Initializing",
"an",
"`",
"Audio",
"`",
"object",
"directly",
"requires",
"the",
"specification",
"of",
"the",
"sample",
"rate",
"."
] |
[
"\"\"\"Container for audio samples\n\n Initializing an `Audio` object directly requires the specification of the\n sample rate. Use `Audio.from_file` or `Audio.from_bytesio` with\n `sample_rate=None` to use a native sampling rate.\n\n Args:\n samples (np.array): The audio samples\n sample_rate (integer): The sampling rate for the audio samples\n\n Returns:\n An initialized `Audio` object\n \"\"\"",
"# Do not move these lines; it will break Pytorch training",
"\"\"\"Load audio from files\n\n Deal with the various possible input types to load an audio\n file and generate a spectrogram\n\n Args:\n path (str, Path): path to an audio file\n\n Returns:\n Audio: attributes samples and sample_rate\n \"\"\"",
"\"\"\"Given a time, convert it to the corresponding sample\n Args:\n time: The time to multiply with the sample_rate\n Returns:\n sample: The rounded sample\n \"\"\"",
"\"\"\"Trim Audio object in time\n\n Args:\n start_time: time in seconds for start of extracted clip\n end_time: time in seconds for end of extracted clip\n Returns:\n a new Audio object containing samples from start_time to end_time\n \"\"\"",
"\"\"\"Return duration of Audio\n\n Returns:\n duration (float): The duration of the Audio\n \"\"\"",
"# reference: https://librosa.org/doc/main/generated/librosa.display.specshow.html",
"# colormap: https://matplotlib.org/stable/tutorials/colors/colormaps.html"
] |
[] |
{
"returns": [
{
"docstring": "An initialized `Audio` object",
"docstring_tokens": [
"An",
"initialized",
"`",
"Audio",
"`",
"object"
],
"type": null
}
],
"raises": [],
"params": [],
"outlier_params": [
{
"identifier": "samples",
"type": null,
"docstring": "The audio samples",
"docstring_tokens": [
"The",
"audio",
"samples"
],
"default": null,
"is_optional": false
},
{
"identifier": "sample_rate",
"type": null,
"docstring": "The sampling rate for the audio samples",
"docstring_tokens": [
"The",
"sampling",
"rate",
"for",
"the",
"audio",
"samples"
],
"default": null,
"is_optional": false
}
],
"others": []
}
| false
| 14
| 651
| 92
|
77bb4335ed34d28618c7e5bd7f1bf32006d7f20d
|
Ruaghain/carbon
|
src/components/animated-menu-button/animated-menu-button.js
|
[
"Apache-2.0"
] |
JavaScript
|
AnimatedMenuButton
|
/**
* An AnimatedMenuButton widget.
*
* == How to use an AnimatedMenuButton in a component:
*
* In your file
*
* import AnimatedMenuButton from 'carbon-react/lib/components/animated-menu-button';
*
* To render a AnimatedMenuButton, pass children to be rendered in the expanded menu:
*
* <AnimatedMenuButton>
* <Row>
* <div>
* <h2 className="title">Foo</h2>
* <p><Link href='#'>Bar</Link></p>
* </div>
* </Row>
* </AnimatedMenuButton>
*
* @class AnimatedMenuButton
* @constructor
*/
|
In your file
import AnimatedMenuButton from 'carbon-react/lib/components/animated-menu-button'.
To render a AnimatedMenuButton, pass children to be rendered in the expanded menu.
Foo
Bar
|
[
"In",
"your",
"file",
"import",
"AnimatedMenuButton",
"from",
"'",
"carbon",
"-",
"react",
"/",
"lib",
"/",
"components",
"/",
"animated",
"-",
"menu",
"-",
"button",
"'",
".",
"To",
"render",
"a",
"AnimatedMenuButton",
"pass",
"children",
"to",
"be",
"rendered",
"in",
"the",
"expanded",
"menu",
".",
"Foo",
"Bar"
] |
class AnimatedMenuButton extends React.Component {
static propTypes = {
/**
* Children elements
*
* @property children
* @type {Node}
*/
children: PropTypes.node,
/**
* Custom className
*
* @property className
* @type {String}
*/
className: PropTypes.string,
/**
* The direction in which the menu expands.
*
* Options: right, left
*
* @property direction
* @type {String}
* @default left
*/
direction: PropTypes.string,
/**
* A label to display at the top of the expanded menu.
*
* @property label
* @type {String}e
*/
label: PropTypes.string,
/**
* The size of the menu.
*
* Options: small, smed, medium, mlarge, large
*
* @property size
* @type {String}
* @default medium
*/
size: PropTypes.string
}
static defaultProps = {
direction: 'left',
size: 'medium'
}
constructor(...args) {
super(...args);
/**
* Determines if the blur event should be prevented.
*
* @property blockBlur
* @type {Boolean}
* @default false
*/
this.blockBlur = false;
this.closeHandler = this.closeHandler.bind(this);
this.closeIcon = this.closeIcon.bind(this);
this.componentProps = this.componentProps.bind(this);
this.handleBlur = this.handleBlur.bind(this);
this.innerHTML = this.innerHTML.bind(this);
this.labelHTML = this.labelHTML.bind(this);
this.mainClasses = this.mainClasses.bind(this);
this.openHandler = this.openHandler.bind(this);
}
state = {
/**
* Menu open or closed.
*
* @property open
* @type {Boolean}
*/
open: false,
/**
* Indicates if user currently on touch device
*
* @property touch
* @type {Boolean}
*/
touch: Devices.isTouchDevice()
};
/**
* Getter for label HTML
*
* @method labelHTML
* @return {HTML} HTML for label.
*/
labelHTML() {
if (this.props.label) {
return (
<span
className='carbon-animated-menu-button__label'
data-element='label'
key='label'
>
{ this.props.label }
</span>
);
}
return '';
}
/**
* Getter for inner HTML of menu
*
* @method innerHTML
* @return {HTML} HTML for menu contents.
*/
innerHTML() {
const contents = [];
// If device supports touch, add close icon.
if (this.state.touch) { contents.push(this.closeIcon()); }
contents.push(this.labelHTML());
contents.push(this.props.children);
return (
<div className='carbon-animated-menu-button__content'>
{ contents }
</div>
);
}
/**
* Getter for widget's main classes.
*
* @method mainClasses
* @return {String} Classnames
*/
mainClasses() {
return classNames(
this.props.className,
'carbon-animated-menu-button',
`carbon-animated-menu-button--${this.props.direction}`,
`carbon-animated-menu-button--${this.props.size}`
);
}
/**
* A getter that returns any supplied custom props along with default props.
*
* @method componentProps
* @return {Object} props including class names & event handlers.
*/
componentProps() {
const { ...props } = validProps(this);
delete props['data-element'];
delete props['data-role'];
props.className = this.mainClasses();
props.onBlur = this.handleBlur;
props.onFocus = this.openHandler;
props.onMouseEnter = this.openHandler;
props.onMouseLeave = this.closeHandler;
props.onTouchEnd = this.state.touch ? this.openHandler : null;
props.ref = (comp) => { this._button = comp; };
return props;
}
/**
* Returns a close icon with touch handler.
*
* @method closeIcon
* @return {HTML} html for close icon
*/
closeIcon() {
return (
<button
className='carbon-animated-menu-button__close-button'
data-element='close'
key='close'
onClick={ this.closeHandler }
ref={ (comp) => { this._closeIcon = comp; } }
type='button'
>
<Icon type='close' />
</button>
);
}
/**
* Opens handler on event.
*
* @method openHandler
* @return {void}
*/
openHandler() {
this.setState({ open: true });
this.blockBlur = true;
}
/**
* Closes menu on event.
*
* @method closeHandler
* @return {void}
*/
closeHandler(event) {
event.preventDefault();
this.setState({ open: false });
this.blockBlur = false;
}
/**
* Handles blur of expanded menu.
*
* @method handleBlur
* @return {void}
*/
handleBlur() {
if (!this.blockBlur) { this.setState({ open: false }); }
}
/**
* Renders the component.
*
* @method render
*/
render() {
let content;
if (this.state.open) {
content = this.innerHTML();
}
return (
<div { ...this.componentProps() } { ...tagComponent('animated-menu-button', this.props) }>
<Icon type='add' data-element='open' />
<CSSTransitionGroup
component='div'
transitionEnterTimeout={ 500 }
transitionLeaveTimeout={ 500 }
transitionName='carbon-animated-menu-button'
>
{ content }
</CSSTransitionGroup>
</div>
);
}
}
|
[
"class",
"AnimatedMenuButton",
"extends",
"React",
".",
"Component",
"{",
"static",
"propTypes",
"=",
"{",
"children",
":",
"PropTypes",
".",
"node",
",",
"className",
":",
"PropTypes",
".",
"string",
",",
"direction",
":",
"PropTypes",
".",
"string",
",",
"label",
":",
"PropTypes",
".",
"string",
",",
"size",
":",
"PropTypes",
".",
"string",
"}",
"static",
"defaultProps",
"=",
"{",
"direction",
":",
"'left'",
",",
"size",
":",
"'medium'",
"}",
"constructor",
"(",
"...",
"args",
")",
"{",
"super",
"(",
"...",
"args",
")",
";",
"this",
".",
"blockBlur",
"=",
"false",
";",
"this",
".",
"closeHandler",
"=",
"this",
".",
"closeHandler",
".",
"bind",
"(",
"this",
")",
";",
"this",
".",
"closeIcon",
"=",
"this",
".",
"closeIcon",
".",
"bind",
"(",
"this",
")",
";",
"this",
".",
"componentProps",
"=",
"this",
".",
"componentProps",
".",
"bind",
"(",
"this",
")",
";",
"this",
".",
"handleBlur",
"=",
"this",
".",
"handleBlur",
".",
"bind",
"(",
"this",
")",
";",
"this",
".",
"innerHTML",
"=",
"this",
".",
"innerHTML",
".",
"bind",
"(",
"this",
")",
";",
"this",
".",
"labelHTML",
"=",
"this",
".",
"labelHTML",
".",
"bind",
"(",
"this",
")",
";",
"this",
".",
"mainClasses",
"=",
"this",
".",
"mainClasses",
".",
"bind",
"(",
"this",
")",
";",
"this",
".",
"openHandler",
"=",
"this",
".",
"openHandler",
".",
"bind",
"(",
"this",
")",
";",
"}",
"state",
"=",
"{",
"open",
":",
"false",
",",
"touch",
":",
"Devices",
".",
"isTouchDevice",
"(",
")",
"}",
";",
"labelHTML",
"(",
")",
"{",
"if",
"(",
"this",
".",
"props",
".",
"label",
")",
"{",
"return",
"(",
"<",
"span",
"className",
"=",
"'carbon-animated-menu-button__label'",
"data-element",
"=",
"'label'",
"key",
"=",
"'label'",
">",
"\n ",
"{",
"this",
".",
"props",
".",
"label",
"}",
"\n ",
"<",
"/",
"span",
">",
")",
";",
"}",
"return",
"''",
";",
"}",
"innerHTML",
"(",
")",
"{",
"const",
"contents",
"=",
"[",
"]",
";",
"if",
"(",
"this",
".",
"state",
".",
"touch",
")",
"{",
"contents",
".",
"push",
"(",
"this",
".",
"closeIcon",
"(",
")",
")",
";",
"}",
"contents",
".",
"push",
"(",
"this",
".",
"labelHTML",
"(",
")",
")",
";",
"contents",
".",
"push",
"(",
"this",
".",
"props",
".",
"children",
")",
";",
"return",
"(",
"<",
"div",
"className",
"=",
"'carbon-animated-menu-button__content'",
">",
"\n ",
"{",
"contents",
"}",
"\n ",
"<",
"/",
"div",
">",
")",
";",
"}",
"mainClasses",
"(",
")",
"{",
"return",
"classNames",
"(",
"this",
".",
"props",
".",
"className",
",",
"'carbon-animated-menu-button'",
",",
"`",
"${",
"this",
".",
"props",
".",
"direction",
"}",
"`",
",",
"`",
"${",
"this",
".",
"props",
".",
"size",
"}",
"`",
")",
";",
"}",
"componentProps",
"(",
")",
"{",
"const",
"{",
"...",
"props",
"}",
"=",
"validProps",
"(",
"this",
")",
";",
"delete",
"props",
"[",
"'data-element'",
"]",
";",
"delete",
"props",
"[",
"'data-role'",
"]",
";",
"props",
".",
"className",
"=",
"this",
".",
"mainClasses",
"(",
")",
";",
"props",
".",
"onBlur",
"=",
"this",
".",
"handleBlur",
";",
"props",
".",
"onFocus",
"=",
"this",
".",
"openHandler",
";",
"props",
".",
"onMouseEnter",
"=",
"this",
".",
"openHandler",
";",
"props",
".",
"onMouseLeave",
"=",
"this",
".",
"closeHandler",
";",
"props",
".",
"onTouchEnd",
"=",
"this",
".",
"state",
".",
"touch",
"?",
"this",
".",
"openHandler",
":",
"null",
";",
"props",
".",
"ref",
"=",
"(",
"comp",
")",
"=>",
"{",
"this",
".",
"_button",
"=",
"comp",
";",
"}",
";",
"return",
"props",
";",
"}",
"closeIcon",
"(",
")",
"{",
"return",
"(",
"<",
"button",
"className",
"=",
"'carbon-animated-menu-button__close-button'",
"data-element",
"=",
"'close'",
"key",
"=",
"'close'",
"onClick",
"=",
"{",
"this",
".",
"closeHandler",
"}",
"ref",
"=",
"{",
"(",
"comp",
")",
"=>",
"{",
"this",
".",
"_closeIcon",
"=",
"comp",
";",
"}",
"}",
"type",
"=",
"'button'",
">",
"\n ",
"<",
"Icon",
"type",
"=",
"'close'",
"/",
">",
"\n ",
"<",
"/",
"button",
">",
")",
";",
"}",
"openHandler",
"(",
")",
"{",
"this",
".",
"setState",
"(",
"{",
"open",
":",
"true",
"}",
")",
";",
"this",
".",
"blockBlur",
"=",
"true",
";",
"}",
"closeHandler",
"(",
"event",
")",
"{",
"event",
".",
"preventDefault",
"(",
")",
";",
"this",
".",
"setState",
"(",
"{",
"open",
":",
"false",
"}",
")",
";",
"this",
".",
"blockBlur",
"=",
"false",
";",
"}",
"handleBlur",
"(",
")",
"{",
"if",
"(",
"!",
"this",
".",
"blockBlur",
")",
"{",
"this",
".",
"setState",
"(",
"{",
"open",
":",
"false",
"}",
")",
";",
"}",
"}",
"render",
"(",
")",
"{",
"let",
"content",
";",
"if",
"(",
"this",
".",
"state",
".",
"open",
")",
"{",
"content",
"=",
"this",
".",
"innerHTML",
"(",
")",
";",
"}",
"return",
"(",
"<",
"div",
"{",
"...",
"this",
".",
"componentProps",
"(",
")",
"}",
"{",
"...",
"tagComponent",
"(",
"'animated-menu-button'",
",",
"this",
".",
"props",
")",
"}",
">",
"\n ",
"<",
"Icon",
"type",
"=",
"'add'",
"data-element",
"=",
"'open'",
"/",
">",
"\n\n ",
"<",
"CSSTransitionGroup",
"component",
"=",
"'div'",
"transitionEnterTimeout",
"=",
"{",
"500",
"}",
"transitionLeaveTimeout",
"=",
"{",
"500",
"}",
"transitionName",
"=",
"'carbon-animated-menu-button'",
">",
"\n ",
"{",
"content",
"}",
"\n ",
"<",
"/",
"CSSTransitionGroup",
">",
"\n ",
"<",
"/",
"div",
">",
")",
";",
"}",
"}"
] |
An AnimatedMenuButton widget.
|
[
"An",
"AnimatedMenuButton",
"widget",
"."
] |
[
"/**\n * Children elements\n *\n * @property children\n * @type {Node}\n */",
"/**\n * Custom className\n *\n * @property className\n * @type {String}\n */",
"/**\n * The direction in which the menu expands.\n *\n * Options: right, left\n *\n * @property direction\n * @type {String}\n * @default left\n */",
"/**\n * A label to display at the top of the expanded menu.\n *\n * @property label\n * @type {String}e\n */",
"/**\n * The size of the menu.\n *\n * Options: small, smed, medium, mlarge, large\n *\n * @property size\n * @type {String}\n * @default medium\n */",
"/**\n * Determines if the blur event should be prevented.\n *\n * @property blockBlur\n * @type {Boolean}\n * @default false\n */",
"/**\n * Menu open or closed.\n *\n * @property open\n * @type {Boolean}\n */",
"/**\n * Indicates if user currently on touch device\n *\n * @property touch\n * @type {Boolean}\n */",
"/**\n * Getter for label HTML\n *\n * @method labelHTML\n * @return {HTML} HTML for label.\n */",
"/**\n * Getter for inner HTML of menu\n *\n * @method innerHTML\n * @return {HTML} HTML for menu contents.\n */",
"// If device supports touch, add close icon.",
"/**\n * Getter for widget's main classes.\n *\n * @method mainClasses\n * @return {String} Classnames\n */",
"/**\n * A getter that returns any supplied custom props along with default props.\n *\n * @method componentProps\n * @return {Object} props including class names & event handlers.\n */",
"/**\n * Returns a close icon with touch handler.\n *\n * @method closeIcon\n * @return {HTML} html for close icon\n */",
"/**\n * Opens handler on event.\n *\n * @method openHandler\n * @return {void}\n */",
"/**\n * Closes menu on event.\n *\n * @method closeHandler\n * @return {void}\n */",
"/**\n * Handles blur of expanded menu.\n *\n * @method handleBlur\n * @return {void}\n */",
"/**\n * Renders the component.\n *\n * @method render\n */"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 16
| 1,324
| 142
|
fb0a9eda5846a0ec0a8053e04f73c3a46ec2cb5e
|
quantitare/quantitare-categories
|
lib/quantitare/categories/current_location.rb
|
[
"MIT"
] |
Ruby
|
CurrentLocation
|
##
# While Quantitare provides a special scrobble type for location tracking known as +LocationScrobble+, it is often
# the case that those scrobbles are not created in real-time. This is not ideal if the user wants to take advantage
# of scrobblers and services that are augmented by location data. The +current_location+ category provides a more
# flexible way to provide location data to Quantitare without using the +LocationScrobble+ interface, which requires
# place and transit data.
#
|
While Quantitare provides a special scrobble type for location tracking known as +LocationScrobble+, it is often
the case that those scrobbles are not created in real-time. This is not ideal if the user wants to take advantage
of scrobblers and services that are augmented by location data. The +current_location+ category provides a more
flexible way to provide location data to Quantitare without using the +LocationScrobble+ interface, which requires
place and transit data.
|
[
"While",
"Quantitare",
"provides",
"a",
"special",
"scrobble",
"type",
"for",
"location",
"tracking",
"known",
"as",
"+",
"LocationScrobble",
"+",
"it",
"is",
"often",
"the",
"case",
"that",
"those",
"scrobbles",
"are",
"not",
"created",
"in",
"real",
"-",
"time",
".",
"This",
"is",
"not",
"ideal",
"if",
"the",
"user",
"wants",
"to",
"take",
"advantage",
"of",
"scrobblers",
"and",
"services",
"that",
"are",
"augmented",
"by",
"location",
"data",
".",
"The",
"+",
"current_location",
"+",
"category",
"provides",
"a",
"more",
"flexible",
"way",
"to",
"provide",
"location",
"data",
"to",
"Quantitare",
"without",
"using",
"the",
"+",
"LocationScrobble",
"+",
"interface",
"which",
"requires",
"place",
"and",
"transit",
"data",
"."
] |
class CurrentLocation < Quantitare::Category
specification do
required(:longitude).filled(:float)
required(:latitude).filled(:float)
# The user's altitude in meters
optional(:altitude) { nil? | empty? | int? | float? }
# The user's course over ground in degrees
optional(:course) { nil? | empty? | int? | float? }
# The user's velocity in km/h
optional(:velocity) { nil? | empty? | int? | float? }
# The horizontal and vertical accuracies of the location sample in meters
optional(:horizontal_accuracy) { nil? | empty? | int? | float? }
optional(:vertical_accuracy) { nil? | empty? | int? | float? }
end
end
|
[
"class",
"CurrentLocation",
"<",
"Quantitare",
"::",
"Category",
"specification",
"do",
"required",
"(",
":longitude",
")",
".",
"filled",
"(",
":float",
")",
"required",
"(",
":latitude",
")",
".",
"filled",
"(",
":float",
")",
"optional",
"(",
":altitude",
")",
"{",
"nil?",
"|",
"empty?",
"|",
"int?",
"|",
"float?",
"}",
"optional",
"(",
":course",
")",
"{",
"nil?",
"|",
"empty?",
"|",
"int?",
"|",
"float?",
"}",
"optional",
"(",
":velocity",
")",
"{",
"nil?",
"|",
"empty?",
"|",
"int?",
"|",
"float?",
"}",
"optional",
"(",
":horizontal_accuracy",
")",
"{",
"nil?",
"|",
"empty?",
"|",
"int?",
"|",
"float?",
"}",
"optional",
"(",
":vertical_accuracy",
")",
"{",
"nil?",
"|",
"empty?",
"|",
"int?",
"|",
"float?",
"}",
"end",
"end"
] |
While Quantitare provides a special scrobble type for location tracking known as +LocationScrobble+, it is often
the case that those scrobbles are not created in real-time.
|
[
"While",
"Quantitare",
"provides",
"a",
"special",
"scrobble",
"type",
"for",
"location",
"tracking",
"known",
"as",
"+",
"LocationScrobble",
"+",
"it",
"is",
"often",
"the",
"case",
"that",
"those",
"scrobbles",
"are",
"not",
"created",
"in",
"real",
"-",
"time",
"."
] |
[
"# The user's altitude in meters",
"# The user's course over ground in degrees",
"# The user's velocity in km/h",
"# The horizontal and vertical accuracies of the location sample in meters"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 13
| 174
| 112
|
1e08a43d509af86e9dfb4232e5c183a48742e88e
|
emillynge/deeplearning4j
|
datavec/datavec-data/datavec-data-image/src/main/java/org/datavec/image/loader/LFWLoader.java
|
[
"Apache-2.0"
] |
Java
|
LFWLoader
|
/**
* Loads LFW faces data transform.
* Customize the size of images by passing in preferred dimensions.
*
* DataSet
* 5749 different individuals
* 1680 people have two or more images in the database
* 4069 people have just a single image in the database
* available as 250 by 250 pixel JPEG images
* most images are in color, although a few are grayscale
*
*/
|
Loads LFW faces data transform.
Customize the size of images by passing in preferred dimensions.
DataSet
5749 different individuals
1680 people have two or more images in the database
4069 people have just a single image in the database
available as 250 by 250 pixel JPEG images
most images are in color, although a few are grayscale
|
[
"Loads",
"LFW",
"faces",
"data",
"transform",
".",
"Customize",
"the",
"size",
"of",
"images",
"by",
"passing",
"in",
"preferred",
"dimensions",
".",
"DataSet",
"5749",
"different",
"individuals",
"1680",
"people",
"have",
"two",
"or",
"more",
"images",
"in",
"the",
"database",
"4069",
"people",
"have",
"just",
"a",
"single",
"image",
"in",
"the",
"database",
"available",
"as",
"250",
"by",
"250",
"pixel",
"JPEG",
"images",
"most",
"images",
"are",
"in",
"color",
"although",
"a",
"few",
"are",
"grayscale"
] |
public class LFWLoader extends BaseImageLoader implements Serializable {
public final static int NUM_IMAGES = 13233;
public final static int NUM_LABELS = 5749;
public final static int SUB_NUM_IMAGES = 1054;
public final static int SUB_NUM_LABELS = 432;
public final static int HEIGHT = 250;
public final static int WIDTH = 250;
public final static int CHANNELS = 3;
public final static String DATA_URL = "http://vis-www.cs.umass.edu/lfw/lfw.tgz";
public final static String LABEL_URL = "http://vis-www.cs.umass.edu/lfw/lfw-names.txt";
public final static String SUBSET_URL = "http://vis-www.cs.umass.edu/lfw/lfw-a.tgz";
protected final static String REGEX_PATTERN = ".[0-9]+";
public final static PathLabelGenerator LABEL_PATTERN = new PatternPathLabelGenerator(REGEX_PATTERN);
public String dataFile = "lfw";
public String labelFile = "lfw-names.txt";
public String subsetFile = "lfw-a";
public String localDir = "lfw";
public String localSubDir = "lfw-a/lfw";
protected File fullDir;
protected boolean useSubset = false;
InputSplit[] inputSplit;
public static Map<String, String> lfwData = new HashMap<>();
public static Map<String, String> lfwLabel = new HashMap<>();
public static Map<String, String> lfwSubsetData = new HashMap<>();
public LFWLoader() {
this(false);
}
public LFWLoader(boolean useSubset) {
this(new long[] {HEIGHT, WIDTH, CHANNELS,}, null, useSubset);
}
public LFWLoader(int[] imgDim, boolean useSubset) {
this(imgDim, null, useSubset);
}
public LFWLoader(long[] imgDim, boolean useSubset) {
this(imgDim, null, useSubset);
}
public LFWLoader(int[] imgDim, ImageTransform imgTransform, boolean useSubset) {
this.height = imgDim[0];
this.width = imgDim[1];
this.channels = imgDim[2];
this.imageTransform = imgTransform;
this.useSubset = useSubset;
this.localDir = useSubset ? localSubDir : localDir;
this.fullDir = new File(BASE_DIR, localDir);
generateLfwMaps();
}
public LFWLoader(long[] imgDim, ImageTransform imgTransform, boolean useSubset) {
this.height = imgDim[0];
this.width = imgDim[1];
this.channels = imgDim[2];
this.imageTransform = imgTransform;
this.useSubset = useSubset;
this.localDir = useSubset ? localSubDir : localDir;
this.fullDir = new File(BASE_DIR, localDir);
generateLfwMaps();
}
public void generateLfwMaps() {
if (useSubset) {
// Subset of just faces with a name starting with A
lfwSubsetData.put("filesFilename", new File(SUBSET_URL).getName());
lfwSubsetData.put("filesURL", SUBSET_URL);
lfwSubsetData.put("filesFilenameUnzipped", subsetFile);
} else {
lfwData.put("filesFilename", new File(DATA_URL).getName());
lfwData.put("filesURL", DATA_URL);
lfwData.put("filesFilenameUnzipped", dataFile);
lfwLabel.put("filesFilename", labelFile);
lfwLabel.put("filesURL", LABEL_URL);
lfwLabel.put("filesFilenameUnzipped", labelFile);
}
}
public void load() {
load(NUM_IMAGES, NUM_IMAGES, NUM_LABELS, LABEL_PATTERN, 1, rng);
}
public void load(long batchSize, long numExamples, long numLabels, PathLabelGenerator labelGenerator,
double splitTrainTest, Random rng) {
if (!imageFilesExist()) {
if (!fullDir.exists() || fullDir.listFiles() == null || fullDir.listFiles().length == 0) {
fullDir.mkdir();
if (useSubset) {
log.info("Downloading {} subset...", localDir);
downloadAndUntar(lfwSubsetData, fullDir);
} else {
log.info("Downloading {}...", localDir);
downloadAndUntar(lfwData, fullDir);
downloadAndUntar(lfwLabel, fullDir);
}
}
}
FileSplit fileSplit = new FileSplit(fullDir, ALLOWED_FORMATS, rng);
BalancedPathFilter pathFilter = new BalancedPathFilter(rng, ALLOWED_FORMATS, labelGenerator, numExamples,
numLabels, 0, batchSize, null);
inputSplit = fileSplit.sample(pathFilter, numExamples * splitTrainTest, numExamples * (1 - splitTrainTest));
}
public boolean imageFilesExist() {
if (useSubset) {
File f = new File(BASE_DIR, lfwSubsetData.get("filesFilenameUnzipped"));
if (!f.exists())
return false;
} else {
File f = new File(BASE_DIR, lfwData.get("filesFilenameUnzipped"));
if (!f.exists())
return false;
f = new File(BASE_DIR, lfwLabel.get("filesFilenameUnzipped"));
if (!f.exists())
return false;
}
return true;
}
public RecordReader getRecordReader(long numExamples) {
return getRecordReader(numExamples, numExamples, new long[] {height, width, channels},
useSubset ? SUB_NUM_LABELS : NUM_LABELS, LABEL_PATTERN, true, 1,
new Random(System.currentTimeMillis()));
}
public RecordReader getRecordReader(long batchSize, long numExamples, long numLabels, Random rng) {
return getRecordReader(numExamples, batchSize, new long[] {height, width, channels}, numLabels, LABEL_PATTERN,
true, 1, rng);
}
public RecordReader getRecordReader(long batchSize, long numExamples, boolean train, double splitTrainTest) {
return getRecordReader(numExamples, batchSize, new long[] {height, width, channels},
useSubset ? SUB_NUM_LABELS : NUM_LABELS, LABEL_PATTERN, train, splitTrainTest,
new Random(System.currentTimeMillis()));
}
public RecordReader getRecordReader(long batchSize, long numExamples, int[] imgDim, boolean train,
double splitTrainTest, Random rng) {
return getRecordReader(numExamples, batchSize, imgDim, useSubset ? SUB_NUM_LABELS : NUM_LABELS, LABEL_PATTERN,
train, splitTrainTest, rng);
}
public RecordReader getRecordReader(long batchSize, long numExamples, long[] imgDim, boolean train,
double splitTrainTest, Random rng) {
return getRecordReader(numExamples, batchSize, imgDim, useSubset ? SUB_NUM_LABELS : NUM_LABELS, LABEL_PATTERN,
train, splitTrainTest, rng);
}
public RecordReader getRecordReader(long batchSize, long numExamples, PathLabelGenerator labelGenerator,
boolean train, double splitTrainTest, Random rng) {
return getRecordReader(numExamples, batchSize, new long[] {height, width, channels},
useSubset ? SUB_NUM_LABELS : NUM_LABELS, labelGenerator, train, splitTrainTest, rng);
}
public RecordReader getRecordReader(long batchSize, long numExamples, int[] imgDim, PathLabelGenerator labelGenerator,
boolean train, double splitTrainTest, Random rng) {
return getRecordReader(numExamples, batchSize, imgDim, useSubset ? SUB_NUM_LABELS : NUM_LABELS, labelGenerator,
train, splitTrainTest, rng);
}
public RecordReader getRecordReader(long batchSize, long numExamples, long[] imgDim, PathLabelGenerator labelGenerator,
boolean train, double splitTrainTest, Random rng) {
return getRecordReader(numExamples, batchSize, imgDim, useSubset ? SUB_NUM_LABELS : NUM_LABELS, labelGenerator,
train, splitTrainTest, rng);
}
public RecordReader getRecordReader(long batchSize, long numExamples, int[] imgDim, long numLabels,
PathLabelGenerator labelGenerator, boolean train, double splitTrainTest, Random rng) {
load(batchSize, numExamples, numLabels, labelGenerator, splitTrainTest, rng);
RecordReader recordReader =
new ImageRecordReader(imgDim[0], imgDim[1], imgDim[2], labelGenerator, imageTransform);
try {
InputSplit data = train ? inputSplit[0] : inputSplit[1];
recordReader.initialize(data);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
return recordReader;
}
public RecordReader getRecordReader(long batchSize, long numExamples, long[] imgDim, long numLabels,
PathLabelGenerator labelGenerator, boolean train, double splitTrainTest, Random rng) {
load(batchSize, numExamples, numLabels, labelGenerator, splitTrainTest, rng);
RecordReader recordReader =
new ImageRecordReader(imgDim[0], imgDim[1], imgDim[2], labelGenerator, imageTransform);
try {
InputSplit data = train ? inputSplit[0] : inputSplit[1];
recordReader.initialize(data);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
return recordReader;
}
@Override
public INDArray asRowVector(File f) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public INDArray asRowVector(InputStream inputStream) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public INDArray asMatrix(File f) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public INDArray asMatrix(InputStream inputStream) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public Image asImageMatrix(File f) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public Image asImageMatrix(InputStream inputStream) throws IOException {
throw new UnsupportedOperationException();
}
}
|
[
"public",
"class",
"LFWLoader",
"extends",
"BaseImageLoader",
"implements",
"Serializable",
"{",
"public",
"final",
"static",
"int",
"NUM_IMAGES",
"=",
"13233",
";",
"public",
"final",
"static",
"int",
"NUM_LABELS",
"=",
"5749",
";",
"public",
"final",
"static",
"int",
"SUB_NUM_IMAGES",
"=",
"1054",
";",
"public",
"final",
"static",
"int",
"SUB_NUM_LABELS",
"=",
"432",
";",
"public",
"final",
"static",
"int",
"HEIGHT",
"=",
"250",
";",
"public",
"final",
"static",
"int",
"WIDTH",
"=",
"250",
";",
"public",
"final",
"static",
"int",
"CHANNELS",
"=",
"3",
";",
"public",
"final",
"static",
"String",
"DATA_URL",
"=",
"\"",
"http://vis-www.cs.umass.edu/lfw/lfw.tgz",
"\"",
";",
"public",
"final",
"static",
"String",
"LABEL_URL",
"=",
"\"",
"http://vis-www.cs.umass.edu/lfw/lfw-names.txt",
"\"",
";",
"public",
"final",
"static",
"String",
"SUBSET_URL",
"=",
"\"",
"http://vis-www.cs.umass.edu/lfw/lfw-a.tgz",
"\"",
";",
"protected",
"final",
"static",
"String",
"REGEX_PATTERN",
"=",
"\"",
".[0-9]+",
"\"",
";",
"public",
"final",
"static",
"PathLabelGenerator",
"LABEL_PATTERN",
"=",
"new",
"PatternPathLabelGenerator",
"(",
"REGEX_PATTERN",
")",
";",
"public",
"String",
"dataFile",
"=",
"\"",
"lfw",
"\"",
";",
"public",
"String",
"labelFile",
"=",
"\"",
"lfw-names.txt",
"\"",
";",
"public",
"String",
"subsetFile",
"=",
"\"",
"lfw-a",
"\"",
";",
"public",
"String",
"localDir",
"=",
"\"",
"lfw",
"\"",
";",
"public",
"String",
"localSubDir",
"=",
"\"",
"lfw-a/lfw",
"\"",
";",
"protected",
"File",
"fullDir",
";",
"protected",
"boolean",
"useSubset",
"=",
"false",
";",
"InputSplit",
"[",
"]",
"inputSplit",
";",
"public",
"static",
"Map",
"<",
"String",
",",
"String",
">",
"lfwData",
"=",
"new",
"HashMap",
"<",
">",
"(",
")",
";",
"public",
"static",
"Map",
"<",
"String",
",",
"String",
">",
"lfwLabel",
"=",
"new",
"HashMap",
"<",
">",
"(",
")",
";",
"public",
"static",
"Map",
"<",
"String",
",",
"String",
">",
"lfwSubsetData",
"=",
"new",
"HashMap",
"<",
">",
"(",
")",
";",
"public",
"LFWLoader",
"(",
")",
"{",
"this",
"(",
"false",
")",
";",
"}",
"public",
"LFWLoader",
"(",
"boolean",
"useSubset",
")",
"{",
"this",
"(",
"new",
"long",
"[",
"]",
"{",
"HEIGHT",
",",
"WIDTH",
",",
"CHANNELS",
",",
"}",
",",
"null",
",",
"useSubset",
")",
";",
"}",
"public",
"LFWLoader",
"(",
"int",
"[",
"]",
"imgDim",
",",
"boolean",
"useSubset",
")",
"{",
"this",
"(",
"imgDim",
",",
"null",
",",
"useSubset",
")",
";",
"}",
"public",
"LFWLoader",
"(",
"long",
"[",
"]",
"imgDim",
",",
"boolean",
"useSubset",
")",
"{",
"this",
"(",
"imgDim",
",",
"null",
",",
"useSubset",
")",
";",
"}",
"public",
"LFWLoader",
"(",
"int",
"[",
"]",
"imgDim",
",",
"ImageTransform",
"imgTransform",
",",
"boolean",
"useSubset",
")",
"{",
"this",
".",
"height",
"=",
"imgDim",
"[",
"0",
"]",
";",
"this",
".",
"width",
"=",
"imgDim",
"[",
"1",
"]",
";",
"this",
".",
"channels",
"=",
"imgDim",
"[",
"2",
"]",
";",
"this",
".",
"imageTransform",
"=",
"imgTransform",
";",
"this",
".",
"useSubset",
"=",
"useSubset",
";",
"this",
".",
"localDir",
"=",
"useSubset",
"?",
"localSubDir",
":",
"localDir",
";",
"this",
".",
"fullDir",
"=",
"new",
"File",
"(",
"BASE_DIR",
",",
"localDir",
")",
";",
"generateLfwMaps",
"(",
")",
";",
"}",
"public",
"LFWLoader",
"(",
"long",
"[",
"]",
"imgDim",
",",
"ImageTransform",
"imgTransform",
",",
"boolean",
"useSubset",
")",
"{",
"this",
".",
"height",
"=",
"imgDim",
"[",
"0",
"]",
";",
"this",
".",
"width",
"=",
"imgDim",
"[",
"1",
"]",
";",
"this",
".",
"channels",
"=",
"imgDim",
"[",
"2",
"]",
";",
"this",
".",
"imageTransform",
"=",
"imgTransform",
";",
"this",
".",
"useSubset",
"=",
"useSubset",
";",
"this",
".",
"localDir",
"=",
"useSubset",
"?",
"localSubDir",
":",
"localDir",
";",
"this",
".",
"fullDir",
"=",
"new",
"File",
"(",
"BASE_DIR",
",",
"localDir",
")",
";",
"generateLfwMaps",
"(",
")",
";",
"}",
"public",
"void",
"generateLfwMaps",
"(",
")",
"{",
"if",
"(",
"useSubset",
")",
"{",
"lfwSubsetData",
".",
"put",
"(",
"\"",
"filesFilename",
"\"",
",",
"new",
"File",
"(",
"SUBSET_URL",
")",
".",
"getName",
"(",
")",
")",
";",
"lfwSubsetData",
".",
"put",
"(",
"\"",
"filesURL",
"\"",
",",
"SUBSET_URL",
")",
";",
"lfwSubsetData",
".",
"put",
"(",
"\"",
"filesFilenameUnzipped",
"\"",
",",
"subsetFile",
")",
";",
"}",
"else",
"{",
"lfwData",
".",
"put",
"(",
"\"",
"filesFilename",
"\"",
",",
"new",
"File",
"(",
"DATA_URL",
")",
".",
"getName",
"(",
")",
")",
";",
"lfwData",
".",
"put",
"(",
"\"",
"filesURL",
"\"",
",",
"DATA_URL",
")",
";",
"lfwData",
".",
"put",
"(",
"\"",
"filesFilenameUnzipped",
"\"",
",",
"dataFile",
")",
";",
"lfwLabel",
".",
"put",
"(",
"\"",
"filesFilename",
"\"",
",",
"labelFile",
")",
";",
"lfwLabel",
".",
"put",
"(",
"\"",
"filesURL",
"\"",
",",
"LABEL_URL",
")",
";",
"lfwLabel",
".",
"put",
"(",
"\"",
"filesFilenameUnzipped",
"\"",
",",
"labelFile",
")",
";",
"}",
"}",
"public",
"void",
"load",
"(",
")",
"{",
"load",
"(",
"NUM_IMAGES",
",",
"NUM_IMAGES",
",",
"NUM_LABELS",
",",
"LABEL_PATTERN",
",",
"1",
",",
"rng",
")",
";",
"}",
"public",
"void",
"load",
"(",
"long",
"batchSize",
",",
"long",
"numExamples",
",",
"long",
"numLabels",
",",
"PathLabelGenerator",
"labelGenerator",
",",
"double",
"splitTrainTest",
",",
"Random",
"rng",
")",
"{",
"if",
"(",
"!",
"imageFilesExist",
"(",
")",
")",
"{",
"if",
"(",
"!",
"fullDir",
".",
"exists",
"(",
")",
"||",
"fullDir",
".",
"listFiles",
"(",
")",
"==",
"null",
"||",
"fullDir",
".",
"listFiles",
"(",
")",
".",
"length",
"==",
"0",
")",
"{",
"fullDir",
".",
"mkdir",
"(",
")",
";",
"if",
"(",
"useSubset",
")",
"{",
"log",
".",
"info",
"(",
"\"",
"Downloading {} subset...",
"\"",
",",
"localDir",
")",
";",
"downloadAndUntar",
"(",
"lfwSubsetData",
",",
"fullDir",
")",
";",
"}",
"else",
"{",
"log",
".",
"info",
"(",
"\"",
"Downloading {}...",
"\"",
",",
"localDir",
")",
";",
"downloadAndUntar",
"(",
"lfwData",
",",
"fullDir",
")",
";",
"downloadAndUntar",
"(",
"lfwLabel",
",",
"fullDir",
")",
";",
"}",
"}",
"}",
"FileSplit",
"fileSplit",
"=",
"new",
"FileSplit",
"(",
"fullDir",
",",
"ALLOWED_FORMATS",
",",
"rng",
")",
";",
"BalancedPathFilter",
"pathFilter",
"=",
"new",
"BalancedPathFilter",
"(",
"rng",
",",
"ALLOWED_FORMATS",
",",
"labelGenerator",
",",
"numExamples",
",",
"numLabels",
",",
"0",
",",
"batchSize",
",",
"null",
")",
";",
"inputSplit",
"=",
"fileSplit",
".",
"sample",
"(",
"pathFilter",
",",
"numExamples",
"*",
"splitTrainTest",
",",
"numExamples",
"*",
"(",
"1",
"-",
"splitTrainTest",
")",
")",
";",
"}",
"public",
"boolean",
"imageFilesExist",
"(",
")",
"{",
"if",
"(",
"useSubset",
")",
"{",
"File",
"f",
"=",
"new",
"File",
"(",
"BASE_DIR",
",",
"lfwSubsetData",
".",
"get",
"(",
"\"",
"filesFilenameUnzipped",
"\"",
")",
")",
";",
"if",
"(",
"!",
"f",
".",
"exists",
"(",
")",
")",
"return",
"false",
";",
"}",
"else",
"{",
"File",
"f",
"=",
"new",
"File",
"(",
"BASE_DIR",
",",
"lfwData",
".",
"get",
"(",
"\"",
"filesFilenameUnzipped",
"\"",
")",
")",
";",
"if",
"(",
"!",
"f",
".",
"exists",
"(",
")",
")",
"return",
"false",
";",
"f",
"=",
"new",
"File",
"(",
"BASE_DIR",
",",
"lfwLabel",
".",
"get",
"(",
"\"",
"filesFilenameUnzipped",
"\"",
")",
")",
";",
"if",
"(",
"!",
"f",
".",
"exists",
"(",
")",
")",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}",
"public",
"RecordReader",
"getRecordReader",
"(",
"long",
"numExamples",
")",
"{",
"return",
"getRecordReader",
"(",
"numExamples",
",",
"numExamples",
",",
"new",
"long",
"[",
"]",
"{",
"height",
",",
"width",
",",
"channels",
"}",
",",
"useSubset",
"?",
"SUB_NUM_LABELS",
":",
"NUM_LABELS",
",",
"LABEL_PATTERN",
",",
"true",
",",
"1",
",",
"new",
"Random",
"(",
"System",
".",
"currentTimeMillis",
"(",
")",
")",
")",
";",
"}",
"public",
"RecordReader",
"getRecordReader",
"(",
"long",
"batchSize",
",",
"long",
"numExamples",
",",
"long",
"numLabels",
",",
"Random",
"rng",
")",
"{",
"return",
"getRecordReader",
"(",
"numExamples",
",",
"batchSize",
",",
"new",
"long",
"[",
"]",
"{",
"height",
",",
"width",
",",
"channels",
"}",
",",
"numLabels",
",",
"LABEL_PATTERN",
",",
"true",
",",
"1",
",",
"rng",
")",
";",
"}",
"public",
"RecordReader",
"getRecordReader",
"(",
"long",
"batchSize",
",",
"long",
"numExamples",
",",
"boolean",
"train",
",",
"double",
"splitTrainTest",
")",
"{",
"return",
"getRecordReader",
"(",
"numExamples",
",",
"batchSize",
",",
"new",
"long",
"[",
"]",
"{",
"height",
",",
"width",
",",
"channels",
"}",
",",
"useSubset",
"?",
"SUB_NUM_LABELS",
":",
"NUM_LABELS",
",",
"LABEL_PATTERN",
",",
"train",
",",
"splitTrainTest",
",",
"new",
"Random",
"(",
"System",
".",
"currentTimeMillis",
"(",
")",
")",
")",
";",
"}",
"public",
"RecordReader",
"getRecordReader",
"(",
"long",
"batchSize",
",",
"long",
"numExamples",
",",
"int",
"[",
"]",
"imgDim",
",",
"boolean",
"train",
",",
"double",
"splitTrainTest",
",",
"Random",
"rng",
")",
"{",
"return",
"getRecordReader",
"(",
"numExamples",
",",
"batchSize",
",",
"imgDim",
",",
"useSubset",
"?",
"SUB_NUM_LABELS",
":",
"NUM_LABELS",
",",
"LABEL_PATTERN",
",",
"train",
",",
"splitTrainTest",
",",
"rng",
")",
";",
"}",
"public",
"RecordReader",
"getRecordReader",
"(",
"long",
"batchSize",
",",
"long",
"numExamples",
",",
"long",
"[",
"]",
"imgDim",
",",
"boolean",
"train",
",",
"double",
"splitTrainTest",
",",
"Random",
"rng",
")",
"{",
"return",
"getRecordReader",
"(",
"numExamples",
",",
"batchSize",
",",
"imgDim",
",",
"useSubset",
"?",
"SUB_NUM_LABELS",
":",
"NUM_LABELS",
",",
"LABEL_PATTERN",
",",
"train",
",",
"splitTrainTest",
",",
"rng",
")",
";",
"}",
"public",
"RecordReader",
"getRecordReader",
"(",
"long",
"batchSize",
",",
"long",
"numExamples",
",",
"PathLabelGenerator",
"labelGenerator",
",",
"boolean",
"train",
",",
"double",
"splitTrainTest",
",",
"Random",
"rng",
")",
"{",
"return",
"getRecordReader",
"(",
"numExamples",
",",
"batchSize",
",",
"new",
"long",
"[",
"]",
"{",
"height",
",",
"width",
",",
"channels",
"}",
",",
"useSubset",
"?",
"SUB_NUM_LABELS",
":",
"NUM_LABELS",
",",
"labelGenerator",
",",
"train",
",",
"splitTrainTest",
",",
"rng",
")",
";",
"}",
"public",
"RecordReader",
"getRecordReader",
"(",
"long",
"batchSize",
",",
"long",
"numExamples",
",",
"int",
"[",
"]",
"imgDim",
",",
"PathLabelGenerator",
"labelGenerator",
",",
"boolean",
"train",
",",
"double",
"splitTrainTest",
",",
"Random",
"rng",
")",
"{",
"return",
"getRecordReader",
"(",
"numExamples",
",",
"batchSize",
",",
"imgDim",
",",
"useSubset",
"?",
"SUB_NUM_LABELS",
":",
"NUM_LABELS",
",",
"labelGenerator",
",",
"train",
",",
"splitTrainTest",
",",
"rng",
")",
";",
"}",
"public",
"RecordReader",
"getRecordReader",
"(",
"long",
"batchSize",
",",
"long",
"numExamples",
",",
"long",
"[",
"]",
"imgDim",
",",
"PathLabelGenerator",
"labelGenerator",
",",
"boolean",
"train",
",",
"double",
"splitTrainTest",
",",
"Random",
"rng",
")",
"{",
"return",
"getRecordReader",
"(",
"numExamples",
",",
"batchSize",
",",
"imgDim",
",",
"useSubset",
"?",
"SUB_NUM_LABELS",
":",
"NUM_LABELS",
",",
"labelGenerator",
",",
"train",
",",
"splitTrainTest",
",",
"rng",
")",
";",
"}",
"public",
"RecordReader",
"getRecordReader",
"(",
"long",
"batchSize",
",",
"long",
"numExamples",
",",
"int",
"[",
"]",
"imgDim",
",",
"long",
"numLabels",
",",
"PathLabelGenerator",
"labelGenerator",
",",
"boolean",
"train",
",",
"double",
"splitTrainTest",
",",
"Random",
"rng",
")",
"{",
"load",
"(",
"batchSize",
",",
"numExamples",
",",
"numLabels",
",",
"labelGenerator",
",",
"splitTrainTest",
",",
"rng",
")",
";",
"RecordReader",
"recordReader",
"=",
"new",
"ImageRecordReader",
"(",
"imgDim",
"[",
"0",
"]",
",",
"imgDim",
"[",
"1",
"]",
",",
"imgDim",
"[",
"2",
"]",
",",
"labelGenerator",
",",
"imageTransform",
")",
";",
"try",
"{",
"InputSplit",
"data",
"=",
"train",
"?",
"inputSplit",
"[",
"0",
"]",
":",
"inputSplit",
"[",
"1",
"]",
";",
"recordReader",
".",
"initialize",
"(",
"data",
")",
";",
"}",
"catch",
"(",
"IOException",
"|",
"InterruptedException",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"}",
"return",
"recordReader",
";",
"}",
"public",
"RecordReader",
"getRecordReader",
"(",
"long",
"batchSize",
",",
"long",
"numExamples",
",",
"long",
"[",
"]",
"imgDim",
",",
"long",
"numLabels",
",",
"PathLabelGenerator",
"labelGenerator",
",",
"boolean",
"train",
",",
"double",
"splitTrainTest",
",",
"Random",
"rng",
")",
"{",
"load",
"(",
"batchSize",
",",
"numExamples",
",",
"numLabels",
",",
"labelGenerator",
",",
"splitTrainTest",
",",
"rng",
")",
";",
"RecordReader",
"recordReader",
"=",
"new",
"ImageRecordReader",
"(",
"imgDim",
"[",
"0",
"]",
",",
"imgDim",
"[",
"1",
"]",
",",
"imgDim",
"[",
"2",
"]",
",",
"labelGenerator",
",",
"imageTransform",
")",
";",
"try",
"{",
"InputSplit",
"data",
"=",
"train",
"?",
"inputSplit",
"[",
"0",
"]",
":",
"inputSplit",
"[",
"1",
"]",
";",
"recordReader",
".",
"initialize",
"(",
"data",
")",
";",
"}",
"catch",
"(",
"IOException",
"|",
"InterruptedException",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"}",
"return",
"recordReader",
";",
"}",
"@",
"Override",
"public",
"INDArray",
"asRowVector",
"(",
"File",
"f",
")",
"throws",
"IOException",
"{",
"throw",
"new",
"UnsupportedOperationException",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"INDArray",
"asRowVector",
"(",
"InputStream",
"inputStream",
")",
"throws",
"IOException",
"{",
"throw",
"new",
"UnsupportedOperationException",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"INDArray",
"asMatrix",
"(",
"File",
"f",
")",
"throws",
"IOException",
"{",
"throw",
"new",
"UnsupportedOperationException",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"INDArray",
"asMatrix",
"(",
"InputStream",
"inputStream",
")",
"throws",
"IOException",
"{",
"throw",
"new",
"UnsupportedOperationException",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"Image",
"asImageMatrix",
"(",
"File",
"f",
")",
"throws",
"IOException",
"{",
"throw",
"new",
"UnsupportedOperationException",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"Image",
"asImageMatrix",
"(",
"InputStream",
"inputStream",
")",
"throws",
"IOException",
"{",
"throw",
"new",
"UnsupportedOperationException",
"(",
")",
";",
"}",
"}"
] |
Loads LFW faces data transform.
|
[
"Loads",
"LFW",
"faces",
"data",
"transform",
"."
] |
[
"// Subset of just faces with a name starting with A"
] |
[
{
"param": "BaseImageLoader",
"type": null
},
{
"param": "Serializable",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "BaseImageLoader",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "Serializable",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 15
| 2,168
| 102
|
c7ae014645a8d9ca3cab9005c505b76938925561
|
shota0701nemoto/insta-clone-new
|
vendor/bundle/ruby/2.6.0/gems/coderay-1.1.2/lib/coderay/encoders/terminal.rb
|
[
"RSA-MD"
] |
Ruby
|
Terminal
|
# Outputs code highlighted for a color terminal.
#
# Note: This encoder is in beta. It currently doesn't use the Styles.
#
# Alias: +term+
#
# == Authors & License
#
# By Rob Aldred (http://robaldred.co.uk)
#
# Based on idea by Nathan Weizenbaum (http://nex-3.com)
#
# MIT License (http://www.opensource.org/licenses/mit-license.php)
|
Outputs code highlighted for a color terminal.
Note: This encoder is in beta. It currently doesn't use the Styles.
Authors & License
By Rob Aldred
Based on idea by Nathan Weizenbaum
MIT License
|
[
"Outputs",
"code",
"highlighted",
"for",
"a",
"color",
"terminal",
".",
"Note",
":",
"This",
"encoder",
"is",
"in",
"beta",
".",
"It",
"currently",
"doesn",
"'",
"t",
"use",
"the",
"Styles",
".",
"Authors",
"&",
"License",
"By",
"Rob",
"Aldred",
"Based",
"on",
"idea",
"by",
"Nathan",
"Weizenbaum",
"MIT",
"License"
] |
class Terminal < Encoder
register_for :terminal
TOKEN_COLORS = {
:debug => "\e[1;37;44m",
:annotation => "\e[34m",
:attribute_name => "\e[35m",
:attribute_value => "\e[31m",
:binary => {
:self => "\e[31m",
:char => "\e[1;31m",
:delimiter => "\e[1;31m",
},
:char => {
:self => "\e[35m",
:delimiter => "\e[1;35m"
},
:class => "\e[1;35;4m",
:class_variable => "\e[36m",
:color => "\e[32m",
:comment => {
:self => "\e[1;30m",
:char => "\e[37m",
:delimiter => "\e[37m",
},
:constant => "\e[1;34;4m",
:decorator => "\e[35m",
:definition => "\e[1;33m",
:directive => "\e[33m",
:docstring => "\e[31m",
:doctype => "\e[1;34m",
:done => "\e[1;30;2m",
:entity => "\e[31m",
:error => "\e[1;37;41m",
:exception => "\e[1;31m",
:float => "\e[1;35m",
:function => "\e[1;34m",
:global_variable => "\e[1;32m",
:hex => "\e[1;36m",
:id => "\e[1;34m",
:include => "\e[31m",
:integer => "\e[1;34m",
:imaginary => "\e[1;34m",
:important => "\e[1;31m",
:key => {
:self => "\e[35m",
:char => "\e[1;35m",
:delimiter => "\e[1;35m",
},
:keyword => "\e[32m",
:label => "\e[1;33m",
:local_variable => "\e[33m",
:namespace => "\e[1;35m",
:octal => "\e[1;34m",
:predefined => "\e[36m",
:predefined_constant => "\e[1;36m",
:predefined_type => "\e[1;32m",
:preprocessor => "\e[1;36m",
:pseudo_class => "\e[1;34m",
:regexp => {
:self => "\e[35m",
:delimiter => "\e[1;35m",
:modifier => "\e[35m",
:char => "\e[1;35m",
},
:reserved => "\e[32m",
:shell => {
:self => "\e[33m",
:char => "\e[1;33m",
:delimiter => "\e[1;33m",
:escape => "\e[1;33m",
},
:string => {
:self => "\e[31m",
:modifier => "\e[1;31m",
:char => "\e[1;35m",
:delimiter => "\e[1;31m",
:escape => "\e[1;31m",
},
:symbol => {
:self => "\e[33m",
:delimiter => "\e[1;33m",
},
:tag => "\e[32m",
:type => "\e[1;34m",
:value => "\e[36m",
:variable => "\e[34m",
:insert => {
:self => "\e[42m",
:insert => "\e[1;32;42m",
:eyecatcher => "\e[102m",
},
:delete => {
:self => "\e[41m",
:delete => "\e[1;31;41m",
:eyecatcher => "\e[101m",
},
:change => {
:self => "\e[44m",
:change => "\e[37;44m",
},
:head => {
:self => "\e[45m",
:filename => "\e[37;45m"
},
}
TOKEN_COLORS[:keyword] = TOKEN_COLORS[:reserved]
TOKEN_COLORS[:method] = TOKEN_COLORS[:function]
TOKEN_COLORS[:escape] = TOKEN_COLORS[:delimiter]
protected
def setup(options)
super
@opened = []
@color_scopes = [TOKEN_COLORS]
end
public
def text_token text, kind
if color = @color_scopes.last[kind]
color = color[:self] if color.is_a? Hash
@out << color
@out << (text.index("\n") ? text.gsub("\n", "\e[0m\n" + color) : text)
@out << "\e[0m"
if outer_color = @color_scopes.last[:self]
@out << outer_color
end
else
@out << text
end
end
def begin_group kind
@opened << kind
@out << open_token(kind)
end
alias begin_line begin_group
def end_group kind
if @opened.pop
@color_scopes.pop
@out << "\e[0m"
if outer_color = @color_scopes.last[:self]
@out << outer_color
end
end
end
def end_line kind
@out << (@line_filler ||= "\t" * 100)
end_group kind
end
private
def open_token kind
if color = @color_scopes.last[kind]
if color.is_a? Hash
@color_scopes << color
color[:self]
else
@color_scopes << @color_scopes.last
color
end
else
@color_scopes << @color_scopes.last
''
end
end
end
|
[
"class",
"Terminal",
"<",
"Encoder",
"register_for",
":terminal",
"TOKEN_COLORS",
"=",
"{",
":debug",
"=>",
"\"\\e[1;37;44m\"",
",",
":annotation",
"=>",
"\"\\e[34m\"",
",",
":attribute_name",
"=>",
"\"\\e[35m\"",
",",
":attribute_value",
"=>",
"\"\\e[31m\"",
",",
":binary",
"=>",
"{",
":self",
"=>",
"\"\\e[31m\"",
",",
":char",
"=>",
"\"\\e[1;31m\"",
",",
":delimiter",
"=>",
"\"\\e[1;31m\"",
",",
"}",
",",
":char",
"=>",
"{",
":self",
"=>",
"\"\\e[35m\"",
",",
":delimiter",
"=>",
"\"\\e[1;35m\"",
"}",
",",
":class",
"=>",
"\"\\e[1;35;4m\"",
",",
":class_variable",
"=>",
"\"\\e[36m\"",
",",
":color",
"=>",
"\"\\e[32m\"",
",",
":comment",
"=>",
"{",
":self",
"=>",
"\"\\e[1;30m\"",
",",
":char",
"=>",
"\"\\e[37m\"",
",",
":delimiter",
"=>",
"\"\\e[37m\"",
",",
"}",
",",
":constant",
"=>",
"\"\\e[1;34;4m\"",
",",
":decorator",
"=>",
"\"\\e[35m\"",
",",
":definition",
"=>",
"\"\\e[1;33m\"",
",",
":directive",
"=>",
"\"\\e[33m\"",
",",
":docstring",
"=>",
"\"\\e[31m\"",
",",
":doctype",
"=>",
"\"\\e[1;34m\"",
",",
":done",
"=>",
"\"\\e[1;30;2m\"",
",",
":entity",
"=>",
"\"\\e[31m\"",
",",
":error",
"=>",
"\"\\e[1;37;41m\"",
",",
":exception",
"=>",
"\"\\e[1;31m\"",
",",
":float",
"=>",
"\"\\e[1;35m\"",
",",
":function",
"=>",
"\"\\e[1;34m\"",
",",
":global_variable",
"=>",
"\"\\e[1;32m\"",
",",
":hex",
"=>",
"\"\\e[1;36m\"",
",",
":id",
"=>",
"\"\\e[1;34m\"",
",",
":include",
"=>",
"\"\\e[31m\"",
",",
":integer",
"=>",
"\"\\e[1;34m\"",
",",
":imaginary",
"=>",
"\"\\e[1;34m\"",
",",
":important",
"=>",
"\"\\e[1;31m\"",
",",
":key",
"=>",
"{",
":self",
"=>",
"\"\\e[35m\"",
",",
":char",
"=>",
"\"\\e[1;35m\"",
",",
":delimiter",
"=>",
"\"\\e[1;35m\"",
",",
"}",
",",
":keyword",
"=>",
"\"\\e[32m\"",
",",
":label",
"=>",
"\"\\e[1;33m\"",
",",
":local_variable",
"=>",
"\"\\e[33m\"",
",",
":namespace",
"=>",
"\"\\e[1;35m\"",
",",
":octal",
"=>",
"\"\\e[1;34m\"",
",",
":predefined",
"=>",
"\"\\e[36m\"",
",",
":predefined_constant",
"=>",
"\"\\e[1;36m\"",
",",
":predefined_type",
"=>",
"\"\\e[1;32m\"",
",",
":preprocessor",
"=>",
"\"\\e[1;36m\"",
",",
":pseudo_class",
"=>",
"\"\\e[1;34m\"",
",",
":regexp",
"=>",
"{",
":self",
"=>",
"\"\\e[35m\"",
",",
":delimiter",
"=>",
"\"\\e[1;35m\"",
",",
":modifier",
"=>",
"\"\\e[35m\"",
",",
":char",
"=>",
"\"\\e[1;35m\"",
",",
"}",
",",
":reserved",
"=>",
"\"\\e[32m\"",
",",
":shell",
"=>",
"{",
":self",
"=>",
"\"\\e[33m\"",
",",
":char",
"=>",
"\"\\e[1;33m\"",
",",
":delimiter",
"=>",
"\"\\e[1;33m\"",
",",
":escape",
"=>",
"\"\\e[1;33m\"",
",",
"}",
",",
":string",
"=>",
"{",
":self",
"=>",
"\"\\e[31m\"",
",",
":modifier",
"=>",
"\"\\e[1;31m\"",
",",
":char",
"=>",
"\"\\e[1;35m\"",
",",
":delimiter",
"=>",
"\"\\e[1;31m\"",
",",
":escape",
"=>",
"\"\\e[1;31m\"",
",",
"}",
",",
":symbol",
"=>",
"{",
":self",
"=>",
"\"\\e[33m\"",
",",
":delimiter",
"=>",
"\"\\e[1;33m\"",
",",
"}",
",",
":tag",
"=>",
"\"\\e[32m\"",
",",
":type",
"=>",
"\"\\e[1;34m\"",
",",
":value",
"=>",
"\"\\e[36m\"",
",",
":variable",
"=>",
"\"\\e[34m\"",
",",
":insert",
"=>",
"{",
":self",
"=>",
"\"\\e[42m\"",
",",
":insert",
"=>",
"\"\\e[1;32;42m\"",
",",
":eyecatcher",
"=>",
"\"\\e[102m\"",
",",
"}",
",",
":delete",
"=>",
"{",
":self",
"=>",
"\"\\e[41m\"",
",",
":delete",
"=>",
"\"\\e[1;31;41m\"",
",",
":eyecatcher",
"=>",
"\"\\e[101m\"",
",",
"}",
",",
":change",
"=>",
"{",
":self",
"=>",
"\"\\e[44m\"",
",",
":change",
"=>",
"\"\\e[37;44m\"",
",",
"}",
",",
":head",
"=>",
"{",
":self",
"=>",
"\"\\e[45m\"",
",",
":filename",
"=>",
"\"\\e[37;45m\"",
"}",
",",
"}",
"TOKEN_COLORS",
"[",
":keyword",
"]",
"=",
"TOKEN_COLORS",
"[",
":reserved",
"]",
"TOKEN_COLORS",
"[",
":method",
"]",
"=",
"TOKEN_COLORS",
"[",
":function",
"]",
"TOKEN_COLORS",
"[",
":escape",
"]",
"=",
"TOKEN_COLORS",
"[",
":delimiter",
"]",
"protected",
"def",
"setup",
"(",
"options",
")",
"super",
"@opened",
"=",
"[",
"]",
"@color_scopes",
"=",
"[",
"TOKEN_COLORS",
"]",
"end",
"public",
"def",
"text_token",
"text",
",",
"kind",
"if",
"color",
"=",
"@color_scopes",
".",
"last",
"[",
"kind",
"]",
"color",
"=",
"color",
"[",
":self",
"]",
"if",
"color",
".",
"is_a?",
"Hash",
"@out",
"<<",
"color",
"@out",
"<<",
"(",
"text",
".",
"index",
"(",
"\"\\n\"",
")",
"?",
"text",
".",
"gsub",
"(",
"\"\\n\"",
",",
"\"\\e[0m\\n\"",
"+",
"color",
")",
":",
"text",
")",
"@out",
"<<",
"\"\\e[0m\"",
"if",
"outer_color",
"=",
"@color_scopes",
".",
"last",
"[",
":self",
"]",
"@out",
"<<",
"outer_color",
"end",
"else",
"@out",
"<<",
"text",
"end",
"end",
"def",
"begin_group",
"kind",
"@opened",
"<<",
"kind",
"@out",
"<<",
"open_token",
"(",
"kind",
")",
"end",
"alias",
"begin_line",
"begin_group",
"def",
"end_group",
"kind",
"if",
"@opened",
".",
"pop",
"@color_scopes",
".",
"pop",
"@out",
"<<",
"\"\\e[0m\"",
"if",
"outer_color",
"=",
"@color_scopes",
".",
"last",
"[",
":self",
"]",
"@out",
"<<",
"outer_color",
"end",
"end",
"end",
"def",
"end_line",
"kind",
"@out",
"<<",
"(",
"@line_filler",
"||=",
"\"\\t\"",
"*",
"100",
")",
"end_group",
"kind",
"end",
"private",
"def",
"open_token",
"kind",
"if",
"color",
"=",
"@color_scopes",
".",
"last",
"[",
"kind",
"]",
"if",
"color",
".",
"is_a?",
"Hash",
"@color_scopes",
"<<",
"color",
"color",
"[",
":self",
"]",
"else",
"@color_scopes",
"<<",
"@color_scopes",
".",
"last",
"color",
"end",
"else",
"@color_scopes",
"<<",
"@color_scopes",
".",
"last",
"''",
"end",
"end",
"end"
] |
Outputs code highlighted for a color terminal.
|
[
"Outputs",
"code",
"highlighted",
"for",
"a",
"color",
"terminal",
"."
] |
[] |
[
{
"param": "Encoder",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "Encoder",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 14
| 1,477
| 95
|
91eb2442134d014e5b4720af69d2622d6c99d0be
|
bnadav/nite_dependencies
|
lib/nite_dependencies/has_dependencies.rb
|
[
"MIT"
] |
Ruby
|
Nite
|
# === Example
#
# class Item < ActiveRecord::Base
# has_dependencies
# end
#
# ia = Item.create
# ib = Item.create
#
# ia.dependencies # => []
# ia.add_dependency(ib)
# ia.dependencies # => [ib]
# ia.dependent? ib # => true
# ia.dependent? (Item.create) # => false
|
Example
class Item < ActiveRecord::Base
has_dependencies
end
|
[
"Example",
"class",
"Item",
"<",
"ActiveRecord",
"::",
"Base",
"has_dependencies",
"end"
] |
module Nite
module Dependencies
module HasDependencies
extend ActiveSupport::Concern
included do
end
module ClassMethods
# Class method included into AR::Base
# When called it includes some the instance methods in LocalInstanceMethods module
# into the including class
#
def has_dependencies(options={})
#puts "class is #{self}"
include Nite::Dependencies::HasDependencies::LocalInstanceMethods
end
end
module LocalInstanceMethods
include ActiveSupport::Inflector
# getters - fetch all dependecies of self
def dependencies
klass = self.class
tableized_id = klass.to_s.tableize + ".id"
join_clause = <<-QUERY
INNER JOIN nite_dependencies
ON ((#{tableized_id}=dependentable_a_id) OR (#{tableized_id}=dependentable_b_id))
AND (dependentable_type=\"#{klass}\" AND ((dependentable_a_id = #{self.id}) OR (dependentable_b_id = #{self.id})))
QUERY
klass.where("#{tableized_id}!=#{self.id}").joins(join_clause)
end
# Boolean check of dependency of seld with some object
def dependent?(elem)
Nite::Dependency.dependent?(self, elem)
end
# setters - create new dependencies between self and objects passed as params
def add_dependency(*args)
args.each do |element|
if(self.class != element.class)
raise "Dependecy allowed only for objects of the same class: #{self} <--> #{element}"
end
Nite::Dependency.add(self, element)
end
end
end
end
end
end
|
[
"module",
"Nite",
"module",
"Dependencies",
"module",
"HasDependencies",
"extend",
"ActiveSupport",
"::",
"Concern",
"included",
"do",
"end",
"module",
"ClassMethods",
"def",
"has_dependencies",
"(",
"options",
"=",
"{",
"}",
")",
"include",
"Nite",
"::",
"Dependencies",
"::",
"HasDependencies",
"::",
"LocalInstanceMethods",
"end",
"end",
"module",
"LocalInstanceMethods",
"include",
"ActiveSupport",
"::",
"Inflector",
"def",
"dependencies",
"klass",
"=",
"self",
".",
"class",
"tableized_id",
"=",
"klass",
".",
"to_s",
".",
"tableize",
"+",
"\".id\"",
"join_clause",
"=",
"<<-QUERY",
"\n INNER JOIN nite_dependencies \n ON ((",
"#{",
"tableized_id",
"}",
"=dependentable_a_id) OR (",
"#{",
"tableized_id",
"}",
"=dependentable_b_id)) \n AND (dependentable_type=",
"\\\"",
"#{",
"klass",
"}",
"\\\"",
" AND ((dependentable_a_id = ",
"#{",
"self",
".",
"id",
"}",
") OR (dependentable_b_id = ",
"#{",
"self",
".",
"id",
"}",
")))\n ",
"QUERY",
"klass",
".",
"where",
"(",
"\"#{tableized_id}!=#{self.id}\"",
")",
".",
"joins",
"(",
"join_clause",
")",
"end",
"def",
"dependent?",
"(",
"elem",
")",
"Nite",
"::",
"Dependency",
".",
"dependent?",
"(",
"self",
",",
"elem",
")",
"end",
"def",
"add_dependency",
"(",
"*",
"args",
")",
"args",
".",
"each",
"do",
"|",
"element",
"|",
"if",
"(",
"self",
".",
"class",
"!=",
"element",
".",
"class",
")",
"raise",
"\"Dependecy allowed only for objects of the same class: #{self} <--> #{element}\"",
"end",
"Nite",
"::",
"Dependency",
".",
"add",
"(",
"self",
",",
"element",
")",
"end",
"end",
"end",
"end",
"end",
"end"
] |
Example
class Item < ActiveRecord::Base
has_dependencies
end
|
[
"Example",
"class",
"Item",
"<",
"ActiveRecord",
"::",
"Base",
"has_dependencies",
"end"
] |
[
"# Class method included into AR::Base",
"# When called it includes some the instance methods in LocalInstanceMethods module",
"# into the including class",
"#",
"#puts \"class is #{self}\"",
"# getters - fetch all dependecies of self",
"# Boolean check of dependency of seld with some object",
"# setters - create new dependencies between self and objects passed as params"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 20
| 373
| 86
|
e72a8590ea824fdaf61b93409a77c3504d7cf764
|
pat-sweeney/psi
|
Sources/Visualization/Microsoft.Psi.LiveCharts.Visualization.Windows/CartesianChartVisualizationObject.cs
|
[
"MIT"
] |
C#
|
CartesianChartVisualizationObject
|
/// <summary>
/// Implements a cartesian chart visualization object for series of a specified type which can be mapped to cartesian coordinates.
/// </summary>
/// <typeparam name="T">The underlying type of the objects to visualize.</typeparam>
/// <remarks>
/// <para>
/// This is an instant visualization object operating over a dictionary. Each entry in the dictionary denotes a
/// series. The key of the dictionary describes the name of the series, and the value of the dictionary entry contains the
/// array of objects of type T to visualize. Upon construction, a cartesian mapper needs to be provided that maps every
/// object of type T into a set of (x, y) coordinate.
/// </para>
/// <para>
/// This instant visualization object can be used as a base class to define more specific cartesian chart visualization objects,
/// for example <see cref="HistogramVisualizationObject"/>.
/// </para></remarks>
|
Implements a cartesian chart visualization object for series of a specified type which can be mapped to cartesian coordinates.
|
[
"Implements",
"a",
"cartesian",
"chart",
"visualization",
"object",
"for",
"series",
"of",
"a",
"specified",
"type",
"which",
"can",
"be",
"mapped",
"to",
"cartesian",
"coordinates",
"."
] |
[VisualizationObject("Cartesian Chart")]
public class CartesianChartVisualizationObject<T> : Instant2DVisualizationObject<Dictionary<string, T[]>>
{
protected const string UnknownCartesianChartTypeMessage = "Unknown cartesian chart type.";
private readonly Func<Dictionary<string, T[]>, string, int, (double, double)> cartesianMapper;
private readonly Dictionary<string, int> seriesMapping = new Dictionary<string, int>();
private SeriesCollection seriesCollection = new SeriesCollection();
private Func<double, string> axisXLabelFormatter;
private Func<double, string> axisYLabelFormatter;
private string[] axisXLabels;
private string[] axisYLabels;
private string axisXTitle = "X-Axis";
private string axisYTitle = "Y-Axis";
private bool disableAnimations = true;
private CartesianChartType cartesianChartType = CartesianChartType.Line;
public CartesianChartVisualizationObject(
Func<Dictionary<string, T[]>, string, int, (double, double)> cartesianMapper)
: base()
{
this.cartesianMapper = cartesianMapper;
}
[IgnoreDataMember]
public override DataTemplate DefaultViewTemplate => XamlHelper.CreateTemplate(this.GetType(), typeof(CartesianChartVisualizationObjectView));
[IgnoreDataMember]
[Browsable(false)]
public SeriesCollection SeriesCollection
{
get { return this.seriesCollection; }
set { this.Set(nameof(this.SeriesCollection), ref this.seriesCollection, value); }
}
[IgnoreDataMember]
[Browsable(false)]
public Func<double, string> AxisXLabelFormatter
{
get { return this.axisXLabelFormatter; }
set { this.Set(nameof(this.AxisXLabelFormatter), ref this.axisXLabelFormatter, value); }
}
[IgnoreDataMember]
[Browsable(false)]
public Func<double, string> AxisYLabelFormatter
{
get { return this.axisYLabelFormatter; }
set { this.Set(nameof(this.AxisYLabelFormatter), ref this.axisYLabelFormatter, value); }
}
[IgnoreDataMember]
[Browsable(false)]
public string[] AxisXLabels
{
get { return this.axisXLabels; }
set { this.Set(nameof(this.AxisXLabels), ref this.axisXLabels, value); }
}
[IgnoreDataMember]
[Browsable(false)]
public string[] AxisYLabels
{
get { return this.axisYLabels; }
set { this.Set(nameof(this.AxisYLabels), ref this.axisYLabels, value); }
}
[DataMember]
[DisplayName("X Axis Title")]
[Description("The title for the X axis.")]
public string AxisXTitle
{
get { return this.axisXTitle; }
set { this.Set(nameof(this.AxisXTitle), ref this.axisXTitle, value); }
}
[DataMember]
[DisplayName("Y Axis Title")]
[Description("The title for the Y axis.")]
public string AxisYTitle
{
get { return this.axisYTitle; }
set { this.Set(nameof(this.AxisYTitle), ref this.axisYTitle, value); }
}
[DataMember]
[DisplayName("Disable Animations")]
[Description("If checked, animations are disabled.")]
public bool DisableAnimations
{
get { return this.disableAnimations; }
set { this.Set(nameof(this.DisableAnimations), ref this.disableAnimations, value); }
}
[DataMember]
[DisplayName("Chart type")]
[Description("The type of the cartesian chart.")]
public CartesianChartType CartesianChartType
{
get { return this.cartesianChartType; }
set { this.Set(nameof(this.CartesianChartType), ref this.cartesianChartType, value); }
}
protected override void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e != null && e.PropertyName == nameof(this.CurrentData))
{
if (this.CurrentData != null)
{
foreach (var kvp in this.CurrentData)
{
var series = this.seriesMapping.ContainsKey(kvp.Key) ?
this.SeriesCollection[this.seriesMapping[kvp.Key]] : this.CreateSeries(kvp.Key);
if (series.Values == null)
{
series.Values = this.ConstructChartValues(kvp.Key);
}
else if (kvp.Value == null)
{
series.Values.Clear();
}
else
{
var min = Math.Min(series.Values.Count, kvp.Value.Length);
for (int i = 0; i < min; i++)
{
var observablePoint = (series.Values as ChartValues<ObservablePoint>)[i];
(observablePoint.X, observablePoint.Y) = this.GetXYValues(kvp.Key, i);
}
if (series.Values.Count > kvp.Value.Length)
{
while (series.Values.Count > kvp.Value.Length)
{
series.Values.RemoveAt(kvp.Value.Length);
}
}
else if (series.Values.Count < kvp.Value.Length)
{
for (int i = series.Values.Count; i < kvp.Value.Length; i++)
{
(var x, var y) = this.GetXYValues(kvp.Key, i);
series.Values.Add(new ObservablePoint(x, y));
}
}
}
if (!this.seriesMapping.ContainsKey(kvp.Key))
{
this.seriesMapping.Add(kvp.Key, this.SeriesCollection.Count);
this.SeriesCollection.Add(series);
}
}
}
else
{
if (this.SeriesCollection.Count > 0)
{
this.SeriesCollection = new SeriesCollection();
this.seriesMapping.Clear();
}
}
}
else if (e != null && e.PropertyName == nameof(this.CartesianChartType))
{
if (this.CurrentData != null)
{
this.SeriesCollection = new SeriesCollection();
this.seriesMapping.Clear();
foreach (var kvp in this.CurrentData)
{
this.seriesMapping.Add(kvp.Key, this.SeriesCollection.Count);
this.SeriesCollection.Add(this.CreateSeries(kvp.Key));
this.SeriesCollection[this.seriesMapping[kvp.Key]].Values = this.ConstructChartValues(kvp.Key);
}
}
}
base.OnPropertyChanged(sender, e);
}
private Series CreateSeries(string title)
{
return this.CartesianChartType switch
{
CartesianChartType.Line => new LineSeries() { Title = title },
CartesianChartType.VerticalLine => new VerticalLineSeries() { Title = title },
CartesianChartType.Column => new ColumnSeries() { Title = title },
CartesianChartType.Row => new RowSeries() { Title = title },
CartesianChartType.StackedArea => new StackedAreaSeries() { Title = title },
CartesianChartType.VerticalStackedArea => new VerticalStackedAreaSeries() { Title = title },
CartesianChartType.StackedColumn => new StackedColumnSeries() { Title = title },
CartesianChartType.StackedRow => new StackedRowSeries() { Title = title },
_ => throw new Exception(UnknownCartesianChartTypeMessage)
};
}
private ChartValues<ObservablePoint> ConstructChartValues(string seriesName)
{
var result = new ChartValues<ObservablePoint>();
if (this.CurrentData[seriesName] != null)
{
for (int i = 0; i < this.CurrentData[seriesName].Length; i++)
{
(var x, var y) = this.GetXYValues(seriesName, i);
result.Add(new ObservablePoint(x, y));
}
}
return result;
}
private (double X, double Y) GetXYValues(string seriesName, int index)
{
(var x, var y) = this.cartesianMapper(this.CurrentData, seriesName, index);
return this.CartesianChartType switch
{
CartesianChartType.Line => (x, y),
CartesianChartType.VerticalLine => (y, x),
CartesianChartType.Column => (x, y),
CartesianChartType.Row => (y, x),
CartesianChartType.StackedArea => (x, y),
CartesianChartType.VerticalStackedArea => (y, x),
CartesianChartType.StackedColumn => (x, y),
CartesianChartType.StackedRow => (y, x),
_ => throw new Exception(UnknownCartesianChartTypeMessage)
};
}
}
|
[
"[",
"VisualizationObject",
"(",
"\"",
"Cartesian Chart",
"\"",
")",
"]",
"public",
"class",
"CartesianChartVisualizationObject",
"<",
"T",
">",
":",
"Instant2DVisualizationObject",
"<",
"Dictionary",
"<",
"string",
",",
"T",
"[",
"]",
">",
">",
"{",
"protected",
"const",
"string",
"UnknownCartesianChartTypeMessage",
"=",
"\"",
"Unknown cartesian chart type.",
"\"",
";",
"private",
"readonly",
"Func",
"<",
"Dictionary",
"<",
"string",
",",
"T",
"[",
"]",
">",
",",
"string",
",",
"int",
",",
"(",
"double",
",",
"double",
")",
">",
"cartesianMapper",
";",
"private",
"readonly",
"Dictionary",
"<",
"string",
",",
"int",
">",
"seriesMapping",
"=",
"new",
"Dictionary",
"<",
"string",
",",
"int",
">",
"(",
")",
";",
"private",
"SeriesCollection",
"seriesCollection",
"=",
"new",
"SeriesCollection",
"(",
")",
";",
"private",
"Func",
"<",
"double",
",",
"string",
">",
"axisXLabelFormatter",
";",
"private",
"Func",
"<",
"double",
",",
"string",
">",
"axisYLabelFormatter",
";",
"private",
"string",
"[",
"]",
"axisXLabels",
";",
"private",
"string",
"[",
"]",
"axisYLabels",
";",
"private",
"string",
"axisXTitle",
"=",
"\"",
"X-Axis",
"\"",
";",
"private",
"string",
"axisYTitle",
"=",
"\"",
"Y-Axis",
"\"",
";",
"private",
"bool",
"disableAnimations",
"=",
"true",
";",
"private",
"CartesianChartType",
"cartesianChartType",
"=",
"CartesianChartType",
".",
"Line",
";",
"public",
"CartesianChartVisualizationObject",
"(",
"Func",
"<",
"Dictionary",
"<",
"string",
",",
"T",
"[",
"]",
">",
",",
"string",
",",
"int",
",",
"(",
"double",
",",
"double",
")",
">",
"cartesianMapper",
")",
":",
"base",
"(",
")",
"{",
"this",
".",
"cartesianMapper",
"=",
"cartesianMapper",
";",
"}",
"[",
"IgnoreDataMember",
"]",
"public",
"override",
"DataTemplate",
"DefaultViewTemplate",
"=>",
"XamlHelper",
".",
"CreateTemplate",
"(",
"this",
".",
"GetType",
"(",
")",
",",
"typeof",
"(",
"CartesianChartVisualizationObjectView",
")",
")",
";",
"[",
"IgnoreDataMember",
"]",
"[",
"Browsable",
"(",
"false",
")",
"]",
"public",
"SeriesCollection",
"SeriesCollection",
"{",
"get",
"{",
"return",
"this",
".",
"seriesCollection",
";",
"}",
"set",
"{",
"this",
".",
"Set",
"(",
"nameof",
"(",
"this",
".",
"SeriesCollection",
")",
",",
"ref",
"this",
".",
"seriesCollection",
",",
"value",
")",
";",
"}",
"}",
"[",
"IgnoreDataMember",
"]",
"[",
"Browsable",
"(",
"false",
")",
"]",
"public",
"Func",
"<",
"double",
",",
"string",
">",
"AxisXLabelFormatter",
"{",
"get",
"{",
"return",
"this",
".",
"axisXLabelFormatter",
";",
"}",
"set",
"{",
"this",
".",
"Set",
"(",
"nameof",
"(",
"this",
".",
"AxisXLabelFormatter",
")",
",",
"ref",
"this",
".",
"axisXLabelFormatter",
",",
"value",
")",
";",
"}",
"}",
"[",
"IgnoreDataMember",
"]",
"[",
"Browsable",
"(",
"false",
")",
"]",
"public",
"Func",
"<",
"double",
",",
"string",
">",
"AxisYLabelFormatter",
"{",
"get",
"{",
"return",
"this",
".",
"axisYLabelFormatter",
";",
"}",
"set",
"{",
"this",
".",
"Set",
"(",
"nameof",
"(",
"this",
".",
"AxisYLabelFormatter",
")",
",",
"ref",
"this",
".",
"axisYLabelFormatter",
",",
"value",
")",
";",
"}",
"}",
"[",
"IgnoreDataMember",
"]",
"[",
"Browsable",
"(",
"false",
")",
"]",
"public",
"string",
"[",
"]",
"AxisXLabels",
"{",
"get",
"{",
"return",
"this",
".",
"axisXLabels",
";",
"}",
"set",
"{",
"this",
".",
"Set",
"(",
"nameof",
"(",
"this",
".",
"AxisXLabels",
")",
",",
"ref",
"this",
".",
"axisXLabels",
",",
"value",
")",
";",
"}",
"}",
"[",
"IgnoreDataMember",
"]",
"[",
"Browsable",
"(",
"false",
")",
"]",
"public",
"string",
"[",
"]",
"AxisYLabels",
"{",
"get",
"{",
"return",
"this",
".",
"axisYLabels",
";",
"}",
"set",
"{",
"this",
".",
"Set",
"(",
"nameof",
"(",
"this",
".",
"AxisYLabels",
")",
",",
"ref",
"this",
".",
"axisYLabels",
",",
"value",
")",
";",
"}",
"}",
"[",
"DataMember",
"]",
"[",
"DisplayName",
"(",
"\"",
"X Axis Title",
"\"",
")",
"]",
"[",
"Description",
"(",
"\"",
"The title for the X axis.",
"\"",
")",
"]",
"public",
"string",
"AxisXTitle",
"{",
"get",
"{",
"return",
"this",
".",
"axisXTitle",
";",
"}",
"set",
"{",
"this",
".",
"Set",
"(",
"nameof",
"(",
"this",
".",
"AxisXTitle",
")",
",",
"ref",
"this",
".",
"axisXTitle",
",",
"value",
")",
";",
"}",
"}",
"[",
"DataMember",
"]",
"[",
"DisplayName",
"(",
"\"",
"Y Axis Title",
"\"",
")",
"]",
"[",
"Description",
"(",
"\"",
"The title for the Y axis.",
"\"",
")",
"]",
"public",
"string",
"AxisYTitle",
"{",
"get",
"{",
"return",
"this",
".",
"axisYTitle",
";",
"}",
"set",
"{",
"this",
".",
"Set",
"(",
"nameof",
"(",
"this",
".",
"AxisYTitle",
")",
",",
"ref",
"this",
".",
"axisYTitle",
",",
"value",
")",
";",
"}",
"}",
"[",
"DataMember",
"]",
"[",
"DisplayName",
"(",
"\"",
"Disable Animations",
"\"",
")",
"]",
"[",
"Description",
"(",
"\"",
"If checked, animations are disabled.",
"\"",
")",
"]",
"public",
"bool",
"DisableAnimations",
"{",
"get",
"{",
"return",
"this",
".",
"disableAnimations",
";",
"}",
"set",
"{",
"this",
".",
"Set",
"(",
"nameof",
"(",
"this",
".",
"DisableAnimations",
")",
",",
"ref",
"this",
".",
"disableAnimations",
",",
"value",
")",
";",
"}",
"}",
"[",
"DataMember",
"]",
"[",
"DisplayName",
"(",
"\"",
"Chart type",
"\"",
")",
"]",
"[",
"Description",
"(",
"\"",
"The type of the cartesian chart.",
"\"",
")",
"]",
"public",
"CartesianChartType",
"CartesianChartType",
"{",
"get",
"{",
"return",
"this",
".",
"cartesianChartType",
";",
"}",
"set",
"{",
"this",
".",
"Set",
"(",
"nameof",
"(",
"this",
".",
"CartesianChartType",
")",
",",
"ref",
"this",
".",
"cartesianChartType",
",",
"value",
")",
";",
"}",
"}",
"protected",
"override",
"void",
"OnPropertyChanged",
"(",
"object",
"sender",
",",
"PropertyChangedEventArgs",
"e",
")",
"{",
"if",
"(",
"e",
"!=",
"null",
"&&",
"e",
".",
"PropertyName",
"==",
"nameof",
"(",
"this",
".",
"CurrentData",
")",
")",
"{",
"if",
"(",
"this",
".",
"CurrentData",
"!=",
"null",
")",
"{",
"foreach",
"(",
"var",
"kvp",
"in",
"this",
".",
"CurrentData",
")",
"{",
"var",
"series",
"=",
"this",
".",
"seriesMapping",
".",
"ContainsKey",
"(",
"kvp",
".",
"Key",
")",
"?",
"this",
".",
"SeriesCollection",
"[",
"this",
".",
"seriesMapping",
"[",
"kvp",
".",
"Key",
"]",
"]",
":",
"this",
".",
"CreateSeries",
"(",
"kvp",
".",
"Key",
")",
";",
"if",
"(",
"series",
".",
"Values",
"==",
"null",
")",
"{",
"series",
".",
"Values",
"=",
"this",
".",
"ConstructChartValues",
"(",
"kvp",
".",
"Key",
")",
";",
"}",
"else",
"if",
"(",
"kvp",
".",
"Value",
"==",
"null",
")",
"{",
"series",
".",
"Values",
".",
"Clear",
"(",
")",
";",
"}",
"else",
"{",
"var",
"min",
"=",
"Math",
".",
"Min",
"(",
"series",
".",
"Values",
".",
"Count",
",",
"kvp",
".",
"Value",
".",
"Length",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"min",
";",
"i",
"++",
")",
"{",
"var",
"observablePoint",
"=",
"(",
"series",
".",
"Values",
"as",
"ChartValues",
"<",
"ObservablePoint",
">",
")",
"[",
"i",
"]",
";",
"(",
"observablePoint",
".",
"X",
",",
"observablePoint",
".",
"Y",
")",
"=",
"this",
".",
"GetXYValues",
"(",
"kvp",
".",
"Key",
",",
"i",
")",
";",
"}",
"if",
"(",
"series",
".",
"Values",
".",
"Count",
">",
"kvp",
".",
"Value",
".",
"Length",
")",
"{",
"while",
"(",
"series",
".",
"Values",
".",
"Count",
">",
"kvp",
".",
"Value",
".",
"Length",
")",
"{",
"series",
".",
"Values",
".",
"RemoveAt",
"(",
"kvp",
".",
"Value",
".",
"Length",
")",
";",
"}",
"}",
"else",
"if",
"(",
"series",
".",
"Values",
".",
"Count",
"<",
"kvp",
".",
"Value",
".",
"Length",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"series",
".",
"Values",
".",
"Count",
";",
"i",
"<",
"kvp",
".",
"Value",
".",
"Length",
";",
"i",
"++",
")",
"{",
"(",
"var",
"x",
",",
"var",
"y",
")",
"=",
"this",
".",
"GetXYValues",
"(",
"kvp",
".",
"Key",
",",
"i",
")",
";",
"series",
".",
"Values",
".",
"Add",
"(",
"new",
"ObservablePoint",
"(",
"x",
",",
"y",
")",
")",
";",
"}",
"}",
"}",
"if",
"(",
"!",
"this",
".",
"seriesMapping",
".",
"ContainsKey",
"(",
"kvp",
".",
"Key",
")",
")",
"{",
"this",
".",
"seriesMapping",
".",
"Add",
"(",
"kvp",
".",
"Key",
",",
"this",
".",
"SeriesCollection",
".",
"Count",
")",
";",
"this",
".",
"SeriesCollection",
".",
"Add",
"(",
"series",
")",
";",
"}",
"}",
"}",
"else",
"{",
"if",
"(",
"this",
".",
"SeriesCollection",
".",
"Count",
">",
"0",
")",
"{",
"this",
".",
"SeriesCollection",
"=",
"new",
"SeriesCollection",
"(",
")",
";",
"this",
".",
"seriesMapping",
".",
"Clear",
"(",
")",
";",
"}",
"}",
"}",
"else",
"if",
"(",
"e",
"!=",
"null",
"&&",
"e",
".",
"PropertyName",
"==",
"nameof",
"(",
"this",
".",
"CartesianChartType",
")",
")",
"{",
"if",
"(",
"this",
".",
"CurrentData",
"!=",
"null",
")",
"{",
"this",
".",
"SeriesCollection",
"=",
"new",
"SeriesCollection",
"(",
")",
";",
"this",
".",
"seriesMapping",
".",
"Clear",
"(",
")",
";",
"foreach",
"(",
"var",
"kvp",
"in",
"this",
".",
"CurrentData",
")",
"{",
"this",
".",
"seriesMapping",
".",
"Add",
"(",
"kvp",
".",
"Key",
",",
"this",
".",
"SeriesCollection",
".",
"Count",
")",
";",
"this",
".",
"SeriesCollection",
".",
"Add",
"(",
"this",
".",
"CreateSeries",
"(",
"kvp",
".",
"Key",
")",
")",
";",
"this",
".",
"SeriesCollection",
"[",
"this",
".",
"seriesMapping",
"[",
"kvp",
".",
"Key",
"]",
"]",
".",
"Values",
"=",
"this",
".",
"ConstructChartValues",
"(",
"kvp",
".",
"Key",
")",
";",
"}",
"}",
"}",
"base",
".",
"OnPropertyChanged",
"(",
"sender",
",",
"e",
")",
";",
"}",
"private",
"Series",
"CreateSeries",
"(",
"string",
"title",
")",
"{",
"return",
"this",
".",
"CartesianChartType",
"switch",
"{",
"CartesianChartType",
".",
"Line",
"=>",
"new",
"LineSeries",
"(",
")",
"{",
"Title",
"=",
"title",
"}",
",",
"CartesianChartType",
".",
"VerticalLine",
"=>",
"new",
"VerticalLineSeries",
"(",
")",
"{",
"Title",
"=",
"title",
"}",
",",
"CartesianChartType",
".",
"Column",
"=>",
"new",
"ColumnSeries",
"(",
")",
"{",
"Title",
"=",
"title",
"}",
",",
"CartesianChartType",
".",
"Row",
"=>",
"new",
"RowSeries",
"(",
")",
"{",
"Title",
"=",
"title",
"}",
",",
"CartesianChartType",
".",
"StackedArea",
"=>",
"new",
"StackedAreaSeries",
"(",
")",
"{",
"Title",
"=",
"title",
"}",
",",
"CartesianChartType",
".",
"VerticalStackedArea",
"=>",
"new",
"VerticalStackedAreaSeries",
"(",
")",
"{",
"Title",
"=",
"title",
"}",
",",
"CartesianChartType",
".",
"StackedColumn",
"=>",
"new",
"StackedColumnSeries",
"(",
")",
"{",
"Title",
"=",
"title",
"}",
",",
"CartesianChartType",
".",
"StackedRow",
"=>",
"new",
"StackedRowSeries",
"(",
")",
"{",
"Title",
"=",
"title",
"}",
",",
"_",
"=>",
"throw",
"new",
"Exception",
"(",
"UnknownCartesianChartTypeMessage",
")",
"}",
";",
"}",
"private",
"ChartValues",
"<",
"ObservablePoint",
">",
"ConstructChartValues",
"(",
"string",
"seriesName",
")",
"{",
"var",
"result",
"=",
"new",
"ChartValues",
"<",
"ObservablePoint",
">",
"(",
")",
";",
"if",
"(",
"this",
".",
"CurrentData",
"[",
"seriesName",
"]",
"!=",
"null",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"this",
".",
"CurrentData",
"[",
"seriesName",
"]",
".",
"Length",
";",
"i",
"++",
")",
"{",
"(",
"var",
"x",
",",
"var",
"y",
")",
"=",
"this",
".",
"GetXYValues",
"(",
"seriesName",
",",
"i",
")",
";",
"result",
".",
"Add",
"(",
"new",
"ObservablePoint",
"(",
"x",
",",
"y",
")",
")",
";",
"}",
"}",
"return",
"result",
";",
"}",
"private",
"(",
"double",
"X",
",",
"double",
"Y",
")",
"GetXYValues",
"(",
"string",
"seriesName",
",",
"int",
"index",
")",
"{",
"(",
"var",
"x",
",",
"var",
"y",
")",
"=",
"this",
".",
"cartesianMapper",
"(",
"this",
".",
"CurrentData",
",",
"seriesName",
",",
"index",
")",
";",
"return",
"this",
".",
"CartesianChartType",
"switch",
"{",
"CartesianChartType",
".",
"Line",
"=>",
"(",
"x",
",",
"y",
")",
",",
"CartesianChartType",
".",
"VerticalLine",
"=>",
"(",
"y",
",",
"x",
")",
",",
"CartesianChartType",
".",
"Column",
"=>",
"(",
"x",
",",
"y",
")",
",",
"CartesianChartType",
".",
"Row",
"=>",
"(",
"y",
",",
"x",
")",
",",
"CartesianChartType",
".",
"StackedArea",
"=>",
"(",
"x",
",",
"y",
")",
",",
"CartesianChartType",
".",
"VerticalStackedArea",
"=>",
"(",
"y",
",",
"x",
")",
",",
"CartesianChartType",
".",
"StackedColumn",
"=>",
"(",
"x",
",",
"y",
")",
",",
"CartesianChartType",
".",
"StackedRow",
"=>",
"(",
"y",
",",
"x",
")",
",",
"_",
"=>",
"throw",
"new",
"Exception",
"(",
"UnknownCartesianChartTypeMessage",
")",
"}",
";",
"}",
"}"
] |
Implements a cartesian chart visualization object for series of a specified type which can be mapped to cartesian coordinates.
|
[
"Implements",
"a",
"cartesian",
"chart",
"visualization",
"object",
"for",
"series",
"of",
"a",
"specified",
"type",
"which",
"can",
"be",
"mapped",
"to",
"cartesian",
"coordinates",
"."
] |
[
"/// <summary>",
"/// Exception message that describes encountering an unknown cartesian chart type.",
"/// </summary>",
"/// <summary>",
"/// Initializes a new instance of the <see cref=\"CartesianChartVisualizationObject{T}\"/> class.",
"/// </summary>",
"/// <param name=\"cartesianMapper\">A mapping function that projects an object of type T into (x, y) coordinates.</param>",
"/// <remarks>The cartesian mapper function will receive as input the entire dictionary corresponding to all the",
"/// series, and the name of the series and index of the datapoint to be converted. It will need to return a tuple",
"/// of doubles containing the x and y coordinates for the datapoint.</remarks>",
"/// <inheritdoc />",
"/// <summary>",
"/// Gets or sets the series collection.",
"/// </summary>",
"/// <summary>",
"/// Gets or sets the X-axis labels formatter.",
"/// </summary>",
"/// <summary>",
"/// Gets or sets the Y-axis labels formatter.",
"/// </summary>",
"/// <summary>",
"/// Gets or sets the X-axis labels.",
"/// </summary>",
"/// <summary>",
"/// Gets or sets the Y-axis labels.",
"/// </summary>",
"/// <summary>",
"/// Gets or sets the X-axis title.",
"/// </summary>",
"/// <summary>",
"/// Gets or sets the Y-axis title.",
"/// </summary>",
"/// <summary>",
"/// Gets or sets a value indicating whether to disable animations.",
"/// </summary>",
"/// <summary>",
"/// Gets or sets the type of cartesian series.",
"/// </summary>",
"/// <inheritdoc/>"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": [
{
"identifier": "typeparam",
"docstring": "The underlying type of the objects to visualize.",
"docstring_tokens": [
"The",
"underlying",
"type",
"of",
"the",
"objects",
"to",
"visualize",
"."
]
},
{
"identifier": "remarks",
"docstring": "This is an instant visualization object operating over a dictionary. Each entry in the dictionary denotes a\nseries. The key of the dictionary describes the name of the series, and the value of the dictionary entry contains the\narray of objects of type T to visualize. Upon construction, a cartesian mapper needs to be provided that maps every\nobject of type T into a set of (x, y) coordinate.\n\nThis instant visualization object can be used as a base class to define more specific cartesian chart visualization objects,\nfor example .",
"docstring_tokens": [
"This",
"is",
"an",
"instant",
"visualization",
"object",
"operating",
"over",
"a",
"dictionary",
".",
"Each",
"entry",
"in",
"the",
"dictionary",
"denotes",
"a",
"series",
".",
"The",
"key",
"of",
"the",
"dictionary",
"describes",
"the",
"name",
"of",
"the",
"series",
"and",
"the",
"value",
"of",
"the",
"dictionary",
"entry",
"contains",
"the",
"array",
"of",
"objects",
"of",
"type",
"T",
"to",
"visualize",
".",
"Upon",
"construction",
"a",
"cartesian",
"mapper",
"needs",
"to",
"be",
"provided",
"that",
"maps",
"every",
"object",
"of",
"type",
"T",
"into",
"a",
"set",
"of",
"(",
"x",
"y",
")",
"coordinate",
".",
"This",
"instant",
"visualization",
"object",
"can",
"be",
"used",
"as",
"a",
"base",
"class",
"to",
"define",
"more",
"specific",
"cartesian",
"chart",
"visualization",
"objects",
"for",
"example",
"."
]
}
]
}
| false
| 26
| 1,761
| 186
|
ad0ef407624be516051da743b12358f1f5ecf7b3
|
ugiacobbi/OpenRiaServices
|
src/VisualStudio/Templates/CSharp/BusinessApplication/Assets/Resources/SecurityQuestions.Designer.cs
|
[
"Apache-2.0"
] |
C#
|
SecurityQuestions
|
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
|
A strongly-typed resource class, for looking up localized strings, etc.
|
[
"A",
"strongly",
"-",
"typed",
"resource",
"class",
"for",
"looking",
"up",
"localized",
"strings",
"etc",
"."
] |
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
public class SecurityQuestions {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal SecurityQuestions() {
}
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("$safeprojectname$.Assets.Resources.SecurityQuestions", typeof(SecurityQuestions).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
public static string BestChildhoodFriendQuestion {
get {
return ResourceManager.GetString("BestChildhoodFriendQuestion", resourceCulture);
}
}
public static string ChildhoodNicknameQuestion {
get {
return ResourceManager.GetString("ChildhoodNicknameQuestion", resourceCulture);
}
}
public static string FirstCarColorQuestion {
get {
return ResourceManager.GetString("FirstCarColorQuestion", resourceCulture);
}
}
public static string FirstCarMakeAndModelQuestion {
get {
return ResourceManager.GetString("FirstCarMakeAndModelQuestion", resourceCulture);
}
}
public static string FirstJobCityQuestion {
get {
return ResourceManager.GetString("FirstJobCityQuestion", resourceCulture);
}
}
public static string LastVacationLocationQuestion {
get {
return ResourceManager.GetString("LastVacationLocationQuestion", resourceCulture);
}
}
public static string MaternalGrandmothersMaidenNameQuestion {
get {
return ResourceManager.GetString("MaternalGrandmothersMaidenNameQuestion", resourceCulture);
}
}
public static string MothersMaidenNameQuestion {
get {
return ResourceManager.GetString("MothersMaidenNameQuestion", resourceCulture);
}
}
public static string PetNameQuestion {
get {
return ResourceManager.GetString("PetNameQuestion", resourceCulture);
}
}
public static string SixthGradeSchoolNameQuestion {
get {
return ResourceManager.GetString("SixthGradeSchoolNameQuestion", resourceCulture);
}
}
public static string YearFatherWasBornQuestion {
get {
return ResourceManager.GetString("YearFatherWasBornQuestion", resourceCulture);
}
}
}
|
[
"[",
"global",
"::",
"System",
".",
"CodeDom",
".",
"Compiler",
".",
"GeneratedCodeAttribute",
"(",
"\"",
"System.Resources.Tools.StronglyTypedResourceBuilder",
"\"",
",",
"\"",
"4.0.0.0",
"\"",
")",
"]",
"[",
"global",
"::",
"System",
".",
"Diagnostics",
".",
"DebuggerNonUserCodeAttribute",
"(",
")",
"]",
"[",
"global",
"::",
"System",
".",
"Runtime",
".",
"CompilerServices",
".",
"CompilerGeneratedAttribute",
"(",
")",
"]",
"public",
"class",
"SecurityQuestions",
"{",
"private",
"static",
"global",
"::",
"System",
".",
"Resources",
".",
"ResourceManager",
"resourceMan",
";",
"private",
"static",
"global",
"::",
"System",
".",
"Globalization",
".",
"CultureInfo",
"resourceCulture",
";",
"[",
"global",
"::",
"System",
".",
"Diagnostics",
".",
"CodeAnalysis",
".",
"SuppressMessageAttribute",
"(",
"\"",
"Microsoft.Performance",
"\"",
",",
"\"",
"CA1811:AvoidUncalledPrivateCode",
"\"",
")",
"]",
"internal",
"SecurityQuestions",
"(",
")",
"{",
"}",
"[",
"global",
"::",
"System",
".",
"ComponentModel",
".",
"EditorBrowsableAttribute",
"(",
"global",
"::",
"System",
".",
"ComponentModel",
".",
"EditorBrowsableState",
".",
"Advanced",
")",
"]",
"public",
"static",
"global",
"::",
"System",
".",
"Resources",
".",
"ResourceManager",
"ResourceManager",
"{",
"get",
"{",
"if",
"(",
"object",
".",
"ReferenceEquals",
"(",
"resourceMan",
",",
"null",
")",
")",
"{",
"global",
"::",
"System",
".",
"Resources",
".",
"ResourceManager",
"temp",
"=",
"new",
"global",
"::",
"System",
".",
"Resources",
".",
"ResourceManager",
"(",
"\"",
"$safeprojectname$.Assets.Resources.SecurityQuestions",
"\"",
",",
"typeof",
"(",
"SecurityQuestions",
")",
".",
"Assembly",
")",
";",
"resourceMan",
"=",
"temp",
";",
"}",
"return",
"resourceMan",
";",
"}",
"}",
"[",
"global",
"::",
"System",
".",
"ComponentModel",
".",
"EditorBrowsableAttribute",
"(",
"global",
"::",
"System",
".",
"ComponentModel",
".",
"EditorBrowsableState",
".",
"Advanced",
")",
"]",
"public",
"static",
"global",
"::",
"System",
".",
"Globalization",
".",
"CultureInfo",
"Culture",
"{",
"get",
"{",
"return",
"resourceCulture",
";",
"}",
"set",
"{",
"resourceCulture",
"=",
"value",
";",
"}",
"}",
"public",
"static",
"string",
"BestChildhoodFriendQuestion",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"BestChildhoodFriendQuestion",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"ChildhoodNicknameQuestion",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"ChildhoodNicknameQuestion",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"FirstCarColorQuestion",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"FirstCarColorQuestion",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"FirstCarMakeAndModelQuestion",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"FirstCarMakeAndModelQuestion",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"FirstJobCityQuestion",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"FirstJobCityQuestion",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"LastVacationLocationQuestion",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"LastVacationLocationQuestion",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"MaternalGrandmothersMaidenNameQuestion",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"MaternalGrandmothersMaidenNameQuestion",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"MothersMaidenNameQuestion",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"MothersMaidenNameQuestion",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"PetNameQuestion",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"PetNameQuestion",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"SixthGradeSchoolNameQuestion",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"SixthGradeSchoolNameQuestion",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"YearFatherWasBornQuestion",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"YearFatherWasBornQuestion",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"}"
] |
A strongly-typed resource class, for looking up localized strings, etc.
|
[
"A",
"strongly",
"-",
"typed",
"resource",
"class",
"for",
"looking",
"up",
"localized",
"strings",
"etc",
"."
] |
[
"/// <summary>",
"/// Returns the cached ResourceManager instance used by this class.",
"/// </summary>",
"/// <summary>",
"/// Overrides the current thread's CurrentUICulture property for all",
"/// resource lookups using this strongly typed resource class.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to What is the name of your favorite childhood friend?.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to What was your childhood nickname?.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to What was the color of your first car?.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to What was the make and model of your first car?.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to In what city or town was your first job?.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Where did you vacation last year?.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to What is your maternal grandmother's maiden name?.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to What is your mother's maiden name?.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to What is your pet's name?.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to What school did you attend for sixth grade?.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to In what year was your father born?.",
"/// </summary>"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 17
| 617
| 84
|
b6d75c5ea20897514b3eaa0079f76220b0581737
|
sillsdev/web-xforge
|
src/SIL.XForge.Scripture/SharedResource.cs
|
[
"MIT"
] |
C#
|
SharedResource
|
/// <summary>
/// This class holds the Keys for looking up localizable strings in the IStringLocalizer.
/// It also provides the class which IStringLocalizer uses to find the .resx files with the strings
/// Every string in the Keys class here should also be present in the Resources\SharedResource.en.resx
/// with the english translation as the value.
/// </summary>
|
This class holds the Keys for looking up localizable strings in the IStringLocalizer.
It also provides the class which IStringLocalizer uses to find the .resx files with the strings
Every string in the Keys class here should also be present in the Resources\SharedResource.en.resx
with the english translation as the value.
|
[
"This",
"class",
"holds",
"the",
"Keys",
"for",
"looking",
"up",
"localizable",
"strings",
"in",
"the",
"IStringLocalizer",
".",
"It",
"also",
"provides",
"the",
"class",
"which",
"IStringLocalizer",
"uses",
"to",
"find",
"the",
".",
"resx",
"files",
"with",
"the",
"strings",
"Every",
"string",
"in",
"the",
"Keys",
"class",
"here",
"should",
"also",
"be",
"present",
"in",
"the",
"Resources",
"\\",
"SharedResource",
".",
"en",
".",
"resx",
"with",
"the",
"english",
"translation",
"as",
"the",
"value",
"."
] |
public class SharedResource
{
public static class Keys
{
public const string AudioOnlyQuestion = "AudioOnlyQuestion";
public const string AudioOnlyResponse = "AudioOnlyResponse";
public const string EmailBad = "EmailBad";
public const string EmailMissing = "EmailMissing";
public const string InviteEmailOption = "InviteEmailOption";
public const string InviteFacebookOption = "InviteFacebookOption";
public const string InviteGoogleOption = "InviteGoogleOption";
public const string InviteGreeting = "InviteGreeting";
public const string InviteInstructions = "InviteInstructions";
public const string InviteLinkExpires = "InviteLinkExpires";
public const string InvitePTOption = "InvitePTOption";
public const string InviteSignature = "InviteSignature";
public const string InviteSubject = "InviteSubject";
public const string Language = "Language";
public const string LearnMore = "LearnMore";
public const string LogIn = "LogIn";
public const string MessageMissing = "MessageMissing";
public const string NameMissing = "NameMissing";
public const string Privacy = "Privacy";
public const string RoleMissing = "RoleMissing";
public const string SignUp = "SignUp";
public const string Terms = "Terms";
public const string UserMissing = "UserMissing";
}
public static Dictionary<string, InterfaceLanguage> Cultures = SharedResource.getCultures();
static Dictionary<string, InterfaceLanguage> getCultures()
{
var cultureData = JsonConvert.DeserializeObject<List<InterfaceLanguage>>(File.ReadAllText("locales.json"));
var cultures = new Dictionary<string, InterfaceLanguage> { };
foreach (var culture in cultureData)
{
cultures.Add(culture.CanonicalTag, culture);
}
return cultures;
}
}
|
[
"public",
"class",
"SharedResource",
"{",
"public",
"static",
"class",
"Keys",
"{",
"public",
"const",
"string",
"AudioOnlyQuestion",
"=",
"\"",
"AudioOnlyQuestion",
"\"",
";",
"public",
"const",
"string",
"AudioOnlyResponse",
"=",
"\"",
"AudioOnlyResponse",
"\"",
";",
"public",
"const",
"string",
"EmailBad",
"=",
"\"",
"EmailBad",
"\"",
";",
"public",
"const",
"string",
"EmailMissing",
"=",
"\"",
"EmailMissing",
"\"",
";",
"public",
"const",
"string",
"InviteEmailOption",
"=",
"\"",
"InviteEmailOption",
"\"",
";",
"public",
"const",
"string",
"InviteFacebookOption",
"=",
"\"",
"InviteFacebookOption",
"\"",
";",
"public",
"const",
"string",
"InviteGoogleOption",
"=",
"\"",
"InviteGoogleOption",
"\"",
";",
"public",
"const",
"string",
"InviteGreeting",
"=",
"\"",
"InviteGreeting",
"\"",
";",
"public",
"const",
"string",
"InviteInstructions",
"=",
"\"",
"InviteInstructions",
"\"",
";",
"public",
"const",
"string",
"InviteLinkExpires",
"=",
"\"",
"InviteLinkExpires",
"\"",
";",
"public",
"const",
"string",
"InvitePTOption",
"=",
"\"",
"InvitePTOption",
"\"",
";",
"public",
"const",
"string",
"InviteSignature",
"=",
"\"",
"InviteSignature",
"\"",
";",
"public",
"const",
"string",
"InviteSubject",
"=",
"\"",
"InviteSubject",
"\"",
";",
"public",
"const",
"string",
"Language",
"=",
"\"",
"Language",
"\"",
";",
"public",
"const",
"string",
"LearnMore",
"=",
"\"",
"LearnMore",
"\"",
";",
"public",
"const",
"string",
"LogIn",
"=",
"\"",
"LogIn",
"\"",
";",
"public",
"const",
"string",
"MessageMissing",
"=",
"\"",
"MessageMissing",
"\"",
";",
"public",
"const",
"string",
"NameMissing",
"=",
"\"",
"NameMissing",
"\"",
";",
"public",
"const",
"string",
"Privacy",
"=",
"\"",
"Privacy",
"\"",
";",
"public",
"const",
"string",
"RoleMissing",
"=",
"\"",
"RoleMissing",
"\"",
";",
"public",
"const",
"string",
"SignUp",
"=",
"\"",
"SignUp",
"\"",
";",
"public",
"const",
"string",
"Terms",
"=",
"\"",
"Terms",
"\"",
";",
"public",
"const",
"string",
"UserMissing",
"=",
"\"",
"UserMissing",
"\"",
";",
"}",
"public",
"static",
"Dictionary",
"<",
"string",
",",
"InterfaceLanguage",
">",
"Cultures",
"=",
"SharedResource",
".",
"getCultures",
"(",
")",
";",
"static",
"Dictionary",
"<",
"string",
",",
"InterfaceLanguage",
">",
"getCultures",
"(",
")",
"{",
"var",
"cultureData",
"=",
"JsonConvert",
".",
"DeserializeObject",
"<",
"List",
"<",
"InterfaceLanguage",
">",
">",
"(",
"File",
".",
"ReadAllText",
"(",
"\"",
"locales.json",
"\"",
")",
")",
";",
"var",
"cultures",
"=",
"new",
"Dictionary",
"<",
"string",
",",
"InterfaceLanguage",
">",
"{",
"}",
";",
"foreach",
"(",
"var",
"culture",
"in",
"cultureData",
")",
"{",
"cultures",
".",
"Add",
"(",
"culture",
".",
"CanonicalTag",
",",
"culture",
")",
";",
"}",
"return",
"cultures",
";",
"}",
"}"
] |
This class holds the Keys for looking up localizable strings in the IStringLocalizer.
|
[
"This",
"class",
"holds",
"the",
"Keys",
"for",
"looking",
"up",
"localizable",
"strings",
"in",
"the",
"IStringLocalizer",
"."
] |
[
"/// <summary>",
"/// Map of culture identifier (language tag) to interface language object (local name displayed in the chooser)",
"/// </summary>",
"// TODO consider making file path relative to current file rather than CWD"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 15
| 373
| 81
|
fcf7dfb57400b10dab73907921bb70706d817797
|
aherbert/GDSC-Core
|
gdsc-core/src/main/java/uk/ac/sussex/gdsc/core/logging/PlainMessageFormatter.java
|
[
"Apache-2.0"
] |
Java
|
PlainMessageFormatter
|
/**
* Format a {@link LogRecord} using only the level and the message. These are output as:
*
* <pre>
* level + ":" + message
* </pre>
*
* <p>By default the level is not included if it is {@link Level#INFO}.
*
* <p>If the record contains a thrown exception then the stack trace is added to the message.
*
* <p>The formatted message is created using the log record parameters. No timestamp is added and no
* use of the record resource bundle occurs.
*/
|
Format a LogRecord using only the level and the message. These are output as:
level + ":" + message
By default the level is not included if it is Level#INFO.
If the record contains a thrown exception then the stack trace is added to the message.
The formatted message is created using the log record parameters. No timestamp is added and no
use of the record resource bundle occurs.
|
[
"Format",
"a",
"LogRecord",
"using",
"only",
"the",
"level",
"and",
"the",
"message",
".",
"These",
"are",
"output",
"as",
":",
"level",
"+",
"\"",
":",
"\"",
"+",
"message",
"By",
"default",
"the",
"level",
"is",
"not",
"included",
"if",
"it",
"is",
"Level#INFO",
".",
"If",
"the",
"record",
"contains",
"a",
"thrown",
"exception",
"then",
"the",
"stack",
"trace",
"is",
"added",
"to",
"the",
"message",
".",
"The",
"formatted",
"message",
"is",
"created",
"using",
"the",
"log",
"record",
"parameters",
".",
"No",
"timestamp",
"is",
"added",
"and",
"no",
"use",
"of",
"the",
"record",
"resource",
"bundle",
"occurs",
"."
] |
public class PlainMessageFormatter extends Formatter {
/** The include info flag. */
private boolean includeInfo;
@Override
public String format(LogRecord record) {
if (record.getThrown() != null) {
final StringWriter sw = new StringWriter();
try (PrintWriter pw = new PrintWriter(sw)) {
pw.println(getPlainMessage(record));
record.getThrown().printStackTrace(pw);
return sw.toString();
}
}
return getPlainMessage(record);
}
private String getPlainMessage(LogRecord record) {
if (!isIncludeInfo() && record.getLevel() == Level.INFO) {
return formatLogRecord(record);
}
return record.getLevel() + ":" + formatLogRecord(record);
}
/**
* Format the log record. Adapted from {@link Formatter#formatMessage(LogRecord)} but removed the
* use of resource bundle.
*
* @param record the record
* @return the string
*/
private static String formatLogRecord(LogRecord record) {
final String format = record.getMessage();
final Object[] parameters = record.getParameters();
if (parameters == null || parameters.length == 0) {
// No parameters. Just return format string.
return format;
}
// Is it a java.text style format?
// Ideally we could match with
// Pattern.compile("\\{\\d").matcher(format).find())
// However the cost is 14% higher, so we cheaply check for
// 1 of the first 4 parameters
if (format.indexOf("{0") >= 0 || format.indexOf("{1") >= 0 || format.indexOf("{2") >= 0
|| format.indexOf("{3") >= 0) {
// Do the formatting.
try {
return java.text.MessageFormat.format(format, parameters);
} catch (final Exception ex) {
// Formatting failed. Fall through to plain format string
}
}
return format;
}
/**
* Checks if {@link Level#INFO} will be included in the message. By default this is {@code false}.
*
* @return true, if is including INFO
*/
public boolean isIncludeInfo() {
return includeInfo;
}
/**
* Sets if {@link Level#INFO} will be included in the message.
*
* @param includeInfo the new include info flag
*/
public void setIncludeInfo(boolean includeInfo) {
this.includeInfo = includeInfo;
}
}
|
[
"public",
"class",
"PlainMessageFormatter",
"extends",
"Formatter",
"{",
"/** The include info flag. */",
"private",
"boolean",
"includeInfo",
";",
"@",
"Override",
"public",
"String",
"format",
"(",
"LogRecord",
"record",
")",
"{",
"if",
"(",
"record",
".",
"getThrown",
"(",
")",
"!=",
"null",
")",
"{",
"final",
"StringWriter",
"sw",
"=",
"new",
"StringWriter",
"(",
")",
";",
"try",
"(",
"PrintWriter",
"pw",
"=",
"new",
"PrintWriter",
"(",
"sw",
")",
")",
"{",
"pw",
".",
"println",
"(",
"getPlainMessage",
"(",
"record",
")",
")",
";",
"record",
".",
"getThrown",
"(",
")",
".",
"printStackTrace",
"(",
"pw",
")",
";",
"return",
"sw",
".",
"toString",
"(",
")",
";",
"}",
"}",
"return",
"getPlainMessage",
"(",
"record",
")",
";",
"}",
"private",
"String",
"getPlainMessage",
"(",
"LogRecord",
"record",
")",
"{",
"if",
"(",
"!",
"isIncludeInfo",
"(",
")",
"&&",
"record",
".",
"getLevel",
"(",
")",
"==",
"Level",
".",
"INFO",
")",
"{",
"return",
"formatLogRecord",
"(",
"record",
")",
";",
"}",
"return",
"record",
".",
"getLevel",
"(",
")",
"+",
"\"",
":",
"\"",
"+",
"formatLogRecord",
"(",
"record",
")",
";",
"}",
"/**\n * Format the log record. Adapted from {@link Formatter#formatMessage(LogRecord)} but removed the\n * use of resource bundle.\n *\n * @param record the record\n * @return the string\n */",
"private",
"static",
"String",
"formatLogRecord",
"(",
"LogRecord",
"record",
")",
"{",
"final",
"String",
"format",
"=",
"record",
".",
"getMessage",
"(",
")",
";",
"final",
"Object",
"[",
"]",
"parameters",
"=",
"record",
".",
"getParameters",
"(",
")",
";",
"if",
"(",
"parameters",
"==",
"null",
"||",
"parameters",
".",
"length",
"==",
"0",
")",
"{",
"return",
"format",
";",
"}",
"if",
"(",
"format",
".",
"indexOf",
"(",
"\"",
"{0",
"\"",
")",
">=",
"0",
"||",
"format",
".",
"indexOf",
"(",
"\"",
"{1",
"\"",
")",
">=",
"0",
"||",
"format",
".",
"indexOf",
"(",
"\"",
"{2",
"\"",
")",
">=",
"0",
"||",
"format",
".",
"indexOf",
"(",
"\"",
"{3",
"\"",
")",
">=",
"0",
")",
"{",
"try",
"{",
"return",
"java",
".",
"text",
".",
"MessageFormat",
".",
"format",
"(",
"format",
",",
"parameters",
")",
";",
"}",
"catch",
"(",
"final",
"Exception",
"ex",
")",
"{",
"}",
"}",
"return",
"format",
";",
"}",
"/**\n * Checks if {@link Level#INFO} will be included in the message. By default this is {@code false}.\n *\n * @return true, if is including INFO\n */",
"public",
"boolean",
"isIncludeInfo",
"(",
")",
"{",
"return",
"includeInfo",
";",
"}",
"/**\n * Sets if {@link Level#INFO} will be included in the message.\n *\n * @param includeInfo the new include info flag\n */",
"public",
"void",
"setIncludeInfo",
"(",
"boolean",
"includeInfo",
")",
"{",
"this",
".",
"includeInfo",
"=",
"includeInfo",
";",
"}",
"}"
] |
Format a {@link LogRecord} using only the level and the message.
|
[
"Format",
"a",
"{",
"@link",
"LogRecord",
"}",
"using",
"only",
"the",
"level",
"and",
"the",
"message",
"."
] |
[
"// No parameters. Just return format string.",
"// Is it a java.text style format?",
"// Ideally we could match with",
"// Pattern.compile(\"\\\\{\\\\d\").matcher(format).find())",
"// However the cost is 14% higher, so we cheaply check for",
"// 1 of the first 4 parameters",
"// Do the formatting.",
"// Formatting failed. Fall through to plain format string"
] |
[
{
"param": "Formatter",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "Formatter",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 14
| 535
| 112
|
08f38c35ae4de53808834b45241f2af7a3cacfc6
|
JohnBarton27/AutomatedManagement
|
sonarqube-5.2/web/WEB-INF/app/models/active_dashboard.rb
|
[
"MIT"
] |
Ruby
|
ActiveDashboard
|
#
# SonarQube, open source software quality management tool.
# Copyright (C) 2008-2014 SonarSource
# mailto:contact AT sonarsource DOT com
#
# SonarQube is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 3 of the License, or (at your option) any later version.
#
# SonarQube is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
|
SonarQube, open source software quality management tool.
Copyright (C) 2008-2014 SonarSource
mailto:contact AT sonarsource DOT com
SonarQube is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3 of the License, or (at your option) any later version.
SonarQube is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program; if not, write to the Free Software Foundation,
Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
[
"SonarQube",
"open",
"source",
"software",
"quality",
"management",
"tool",
".",
"Copyright",
"(",
"C",
")",
"2008",
"-",
"2014",
"SonarSource",
"mailto",
":",
"contact",
"AT",
"sonarsource",
"DOT",
"com",
"SonarQube",
"is",
"free",
"software",
";",
"you",
"can",
"redistribute",
"it",
"and",
"/",
"or",
"modify",
"it",
"under",
"the",
"terms",
"of",
"the",
"GNU",
"Lesser",
"General",
"Public",
"License",
"as",
"published",
"by",
"the",
"Free",
"Software",
"Foundation",
";",
"either",
"version",
"3",
"of",
"the",
"License",
"or",
"(",
"at",
"your",
"option",
")",
"any",
"later",
"version",
".",
"SonarQube",
"is",
"distributed",
"in",
"the",
"hope",
"that",
"it",
"will",
"be",
"useful",
"but",
"WITHOUT",
"ANY",
"WARRANTY",
";",
"without",
"even",
"the",
"implied",
"warranty",
"of",
"MERCHANTABILITY",
"or",
"FITNESS",
"FOR",
"A",
"PARTICULAR",
"PURPOSE",
".",
"See",
"the",
"GNU",
"Lesser",
"General",
"Public",
"License",
"for",
"more",
"details",
".",
"You",
"should",
"have",
"received",
"a",
"copy",
"of",
"the",
"GNU",
"Lesser",
"General",
"Public",
"License",
"along",
"with",
"this",
"program",
";",
"if",
"not",
"write",
"to",
"the",
"Free",
"Software",
"Foundation",
"Inc",
".",
"51",
"Franklin",
"Street",
"Fifth",
"Floor",
"Boston",
"MA",
"02110",
"-",
"1301",
"USA",
"."
] |
class ActiveDashboard < ActiveRecord::Base
belongs_to :user
belongs_to :dashboard
validates_uniqueness_of :dashboard_id, :scope => :user_id
def name(l10n=false)
dashboard.name(l10n)
end
def order_index
read_attribute(:order_index) || 1
end
def shared?
dashboard.shared
end
def global?
dashboard.global
end
def owner?(user)
dashboard.owner?(user)
end
def editable_by?(user)
dashboard.editable_by?(user)
end
def follower?(user)
self.user.nil? || self.user_id==user.id
end
def default?
user_id.nil?
end
def self.user_dashboards(user, global)
result=nil
if user && user.id
result=find_for_user(user.id).select { |a| a.global? == global}
end
if result.nil? || result.empty?
result=default_dashboards.select { |a| a.global? == global}
end
result
end
def self.default_dashboards()
find_for_user(nil)
end
private
def self.find_for_user(user_id)
find(:all, :include => 'dashboard', :conditions => {:user_id => user_id}, :order => 'order_index')
end
end
|
[
"class",
"ActiveDashboard",
"<",
"ActiveRecord",
"::",
"Base",
"belongs_to",
":user",
"belongs_to",
":dashboard",
"validates_uniqueness_of",
":dashboard_id",
",",
":scope",
"=>",
":user_id",
"def",
"name",
"(",
"l10n",
"=",
"false",
")",
"dashboard",
".",
"name",
"(",
"l10n",
")",
"end",
"def",
"order_index",
"read_attribute",
"(",
":order_index",
")",
"||",
"1",
"end",
"def",
"shared?",
"dashboard",
".",
"shared",
"end",
"def",
"global?",
"dashboard",
".",
"global",
"end",
"def",
"owner?",
"(",
"user",
")",
"dashboard",
".",
"owner?",
"(",
"user",
")",
"end",
"def",
"editable_by?",
"(",
"user",
")",
"dashboard",
".",
"editable_by?",
"(",
"user",
")",
"end",
"def",
"follower?",
"(",
"user",
")",
"self",
".",
"user",
".",
"nil?",
"||",
"self",
".",
"user_id",
"==",
"user",
".",
"id",
"end",
"def",
"default?",
"user_id",
".",
"nil?",
"end",
"def",
"self",
".",
"user_dashboards",
"(",
"user",
",",
"global",
")",
"result",
"=",
"nil",
"if",
"user",
"&&",
"user",
".",
"id",
"result",
"=",
"find_for_user",
"(",
"user",
".",
"id",
")",
".",
"select",
"{",
"|",
"a",
"|",
"a",
".",
"global?",
"==",
"global",
"}",
"end",
"if",
"result",
".",
"nil?",
"||",
"result",
".",
"empty?",
"result",
"=",
"default_dashboards",
".",
"select",
"{",
"|",
"a",
"|",
"a",
".",
"global?",
"==",
"global",
"}",
"end",
"result",
"end",
"def",
"self",
".",
"default_dashboards",
"(",
")",
"find_for_user",
"(",
"nil",
")",
"end",
"private",
"def",
"self",
".",
"find_for_user",
"(",
"user_id",
")",
"find",
"(",
":all",
",",
":include",
"=>",
"'dashboard'",
",",
":conditions",
"=>",
"{",
":user_id",
"=>",
"user_id",
"}",
",",
":order",
"=>",
"'order_index'",
")",
"end",
"end"
] |
SonarQube, open source software quality management tool.
|
[
"SonarQube",
"open",
"source",
"software",
"quality",
"management",
"tool",
"."
] |
[] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 13
| 302
| 221
|
90dc842f3a9ebc41c66e665ace753027a423578e
|
severin/exception_notification
|
lib/exception_notifier.rb
|
[
"MIT"
] |
Ruby
|
ExceptionNotifier
|
# Copyright (c) 2005 Jamis Buck
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
|
[
"The",
"above",
"copyright",
"notice",
"and",
"this",
"permission",
"notice",
"shall",
"be",
"included",
"in",
"all",
"copies",
"or",
"substantial",
"portions",
"of",
"the",
"Software",
"."
] |
class ExceptionNotifier < ActionMailer::Base
@@sender_address = %("Exception Notifier" <[email protected]>)
cattr_accessor :sender_address
@@exception_recipients = []
cattr_accessor :exception_recipients
@@email_prefix = "[ERROR] "
cattr_accessor :email_prefix
@@sections = %w(request session environment backtrace)
cattr_accessor :sections
@@condition = Proc.new { |request, error| true }
cattr_accessor :condition
self.template_root = "#{File.dirname(__FILE__)}/../views"
def self.reloadable?() false end
def exception_notification(exception, controller, request, data={})
content_type "text/plain"
subject "#{email_prefix}#{controller.controller_name}##{controller.action_name} (#{exception.class}) #{exception.message.inspect}"
recipients exception_recipients
from sender_address
body data.merge({ :controller => controller, :request => request,
:exception => exception, :host => (request.env["HTTP_X_FORWARDED_HOST"] || request.env["HTTP_HOST"]),
:backtrace => sanitize_backtrace(exception.backtrace),
:rails_root => rails_root, :data => data,
:sections => sections })
end
private
def sanitize_backtrace(trace)
return [] unless trace
re = Regexp.new(/^#{Regexp.escape(rails_root)}/)
trace.map { |line| Pathname.new(line.gsub(re, "[RAILS_ROOT]")).cleanpath.to_s }
end
def rails_root
@rails_root ||= Pathname.new(RAILS_ROOT).cleanpath.to_s
end
end
|
[
"class",
"ExceptionNotifier",
"<",
"ActionMailer",
"::",
"Base",
"@@sender_address",
"=",
"%(\"Exception Notifier\" <[email protected]>)",
"cattr_accessor",
":sender_address",
"@@exception_recipients",
"=",
"[",
"]",
"cattr_accessor",
":exception_recipients",
"@@email_prefix",
"=",
"\"[ERROR] \"",
"cattr_accessor",
":email_prefix",
"@@sections",
"=",
"%w(",
"request",
"session",
"environment",
"backtrace",
")",
"cattr_accessor",
":sections",
"@@condition",
"=",
"Proc",
".",
"new",
"{",
"|",
"request",
",",
"error",
"|",
"true",
"}",
"cattr_accessor",
":condition",
"self",
".",
"template_root",
"=",
"\"#{File.dirname(__FILE__)}/../views\"",
"def",
"self",
".",
"reloadable?",
"(",
")",
"false",
"end",
"def",
"exception_notification",
"(",
"exception",
",",
"controller",
",",
"request",
",",
"data",
"=",
"{",
"}",
")",
"content_type",
"\"text/plain\"",
"subject",
"\"#{email_prefix}#{controller.controller_name}##{controller.action_name} (#{exception.class}) #{exception.message.inspect}\"",
"recipients",
"exception_recipients",
"from",
"sender_address",
"body",
"data",
".",
"merge",
"(",
"{",
":controller",
"=>",
"controller",
",",
":request",
"=>",
"request",
",",
":exception",
"=>",
"exception",
",",
":host",
"=>",
"(",
"request",
".",
"env",
"[",
"\"HTTP_X_FORWARDED_HOST\"",
"]",
"||",
"request",
".",
"env",
"[",
"\"HTTP_HOST\"",
"]",
")",
",",
":backtrace",
"=>",
"sanitize_backtrace",
"(",
"exception",
".",
"backtrace",
")",
",",
":rails_root",
"=>",
"rails_root",
",",
":data",
"=>",
"data",
",",
":sections",
"=>",
"sections",
"}",
")",
"end",
"private",
"def",
"sanitize_backtrace",
"(",
"trace",
")",
"return",
"[",
"]",
"unless",
"trace",
"re",
"=",
"Regexp",
".",
"new",
"(",
"/",
"^",
"#{",
"Regexp",
".",
"escape",
"(",
"rails_root",
")",
"}",
"/",
")",
"trace",
".",
"map",
"{",
"|",
"line",
"|",
"Pathname",
".",
"new",
"(",
"line",
".",
"gsub",
"(",
"re",
",",
"\"[RAILS_ROOT]\"",
")",
")",
".",
"cleanpath",
".",
"to_s",
"}",
"end",
"def",
"rails_root",
"@rails_root",
"||=",
"Pathname",
".",
"new",
"(",
"RAILS_ROOT",
")",
".",
"cleanpath",
".",
"to_s",
"end",
"end"
] |
Copyright (c) 2005 Jamis Buck
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
|
[
"Copyright",
"(",
"c",
")",
"2005",
"Jamis",
"Buck",
"Permission",
"is",
"hereby",
"granted",
"free",
"of",
"charge",
"to",
"any",
"person",
"obtaining",
"a",
"copy",
"of",
"this",
"software",
"and",
"associated",
"documentation",
"files",
"(",
"the",
"\"",
"Software",
"\"",
")",
"to",
"deal",
"in",
"the",
"Software",
"without",
"restriction",
"including",
"without",
"limitation",
"the",
"rights",
"to",
"use",
"copy",
"modify",
"merge",
"publish",
"distribute",
"sublicense",
"and",
"/",
"or",
"sell",
"copies",
"of",
"the",
"Software",
"and",
"to",
"permit",
"persons",
"to",
"whom",
"the",
"Software",
"is",
"furnished",
"to",
"do",
"so",
"subject",
"to",
"the",
"following",
"conditions",
":"
] |
[] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 15
| 358
| 236
|
9f3e822570f6d2a695acecfadc777624064c32fe
|
sorah/aws-sdk-ruby
|
lib/aws/core/collection/simple.rb
|
[
"Apache-2.0"
] |
Ruby
|
AWS
|
# Copyright 2011-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
|
or in the "license" file accompanying this file.
|
[
"or",
"in",
"the",
"\"",
"license",
"\"",
"file",
"accompanying",
"this",
"file",
"."
] |
module AWS
module Core
module Collection
# AWS::Core::Collection::Simple is used by collections that always
# recieve every matching items in a single response.
#
# This means:
#
# * Paging methods are simulated
#
# * Next tokens are artificial (guessable numeric offsets)
#
# AWS services generally return all items only for requests with a
# small maximum number of results.
#
# See {AWS::Core::Collection} for documentation on the available
# collection methods.
module Simple
include Model
include Enumerable
include Collection
protected
def _each_batch options = {}, &block
limit = _extract_limit(options)
next_token = _extract_next_token(options)
offset = next_token ? next_token.to_i - 1 : 0
total = 0
skipped = 0
simulated_next_token = nil
batch = []
_each_item(options.dup) do |item|
total += 1
# skip until we reach our offset (derived from the "next token")
if skipped < offset
skipped += 1
next
end
if limit
if batch.size < limit
batch << item
else
simulated_next_token = total
break
end
else
batch << item
end
end
yield(batch)
simulated_next_token
end
end
end
end
end
|
[
"module",
"AWS",
"module",
"Core",
"module",
"Collection",
"module",
"Simple",
"include",
"Model",
"include",
"Enumerable",
"include",
"Collection",
"protected",
"def",
"_each_batch",
"options",
"=",
"{",
"}",
",",
"&",
"block",
"limit",
"=",
"_extract_limit",
"(",
"options",
")",
"next_token",
"=",
"_extract_next_token",
"(",
"options",
")",
"offset",
"=",
"next_token",
"?",
"next_token",
".",
"to_i",
"-",
"1",
":",
"0",
"total",
"=",
"0",
"skipped",
"=",
"0",
"simulated_next_token",
"=",
"nil",
"batch",
"=",
"[",
"]",
"_each_item",
"(",
"options",
".",
"dup",
")",
"do",
"|",
"item",
"|",
"total",
"+=",
"1",
"if",
"skipped",
"<",
"offset",
"skipped",
"+=",
"1",
"next",
"end",
"if",
"limit",
"if",
"batch",
".",
"size",
"<",
"limit",
"batch",
"<<",
"item",
"else",
"simulated_next_token",
"=",
"total",
"break",
"end",
"else",
"batch",
"<<",
"item",
"end",
"end",
"yield",
"(",
"batch",
")",
"simulated_next_token",
"end",
"end",
"end",
"end",
"end"
] |
Copyright 2011-2013 Amazon.com, Inc. or its affiliates.
|
[
"Copyright",
"2011",
"-",
"2013",
"Amazon",
".",
"com",
"Inc",
".",
"or",
"its",
"affiliates",
"."
] |
[
"# AWS::Core::Collection::Simple is used by collections that always",
"# recieve every matching items in a single response.",
"#",
"# This means:",
"#",
"# * Paging methods are simulated",
"#",
"# * Next tokens are artificial (guessable numeric offsets)",
"#",
"# AWS services generally return all items only for requests with a",
"# small maximum number of results.",
"#",
"# See {AWS::Core::Collection} for documentation on the available",
"# collection methods.",
"# skip until we reach our offset (derived from the \"next token\")"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 19
| 325
| 141
|
84f07ca7be9292c1c79acc46d11caf75e7153792
|
jdm7dv/visual-studio
|
VSSDK/VisualStudioIntegration/Common/Source/CSharp/Shell100/Settings/ShellSettingsManager.cs
|
[
"Apache-2.0"
] |
C#
|
ShellSettingsManager
|
/// <summary>
/// This is the gateway class to reach for the settings stored inside the Visual Studio. It provides two basic
/// functionality. It allows to search for properties and collections inside the scopes. It hands the
/// <see cref="SettingsScope"/> and <see cref="WritableSettingsStore"/> classes for further manipulation of the
/// collections and properties within the scopes. This class implements the <see cref="IDisposable"/> pattern
/// hence it needs to be disposed after it is no longer necessary.
/// </summary>
|
This is the gateway class to reach for the settings stored inside the Visual Studio. It provides two basic
functionality. It allows to search for properties and collections inside the scopes. It hands the
and classes for further manipulation of the
collections and properties within the scopes. This class implements the pattern
hence it needs to be disposed after it is no longer necessary.
|
[
"This",
"is",
"the",
"gateway",
"class",
"to",
"reach",
"for",
"the",
"settings",
"stored",
"inside",
"the",
"Visual",
"Studio",
".",
"It",
"provides",
"two",
"basic",
"functionality",
".",
"It",
"allows",
"to",
"search",
"for",
"properties",
"and",
"collections",
"inside",
"the",
"scopes",
".",
"It",
"hands",
"the",
"and",
"classes",
"for",
"further",
"manipulation",
"of",
"the",
"collections",
"and",
"properties",
"within",
"the",
"scopes",
".",
"This",
"class",
"implements",
"the",
"pattern",
"hence",
"it",
"needs",
"to",
"be",
"disposed",
"after",
"it",
"is",
"no",
"longer",
"necessary",
"."
] |
[CLSCompliant(false)]
public sealed class ShellSettingsManager : SettingsManager
{
public ShellSettingsManager(IServiceProvider serviceProvider)
{
HelperMethods.CheckNullArgument(serviceProvider, "serviceProvider");
this.settingsManager = serviceProvider.GetService(typeof(SVsSettingsManager)) as IVsSettingsManager;
if (this.settingsManager == null)
{
throw new NotSupportedException(typeof(SVsSettingsManager).FullName);
}
}
public override EnclosingScopes GetCollectionScopes(string collectionPath)
{
HelperMethods.CheckNullArgument(collectionPath, "collectionPath");
uint scopes;
int hr = this.settingsManager.GetCollectionScopes(collectionPath, out scopes);
Marshal.ThrowExceptionForHR(hr);
return (EnclosingScopes)scopes;
}
public override EnclosingScopes GetPropertyScopes(string collectionPath, string propertyName)
{
HelperMethods.CheckNullArgument(collectionPath, "collectionPath");
HelperMethods.CheckNullArgument(propertyName, "propertyName");
uint scopes;
int hr = this.settingsManager.GetPropertyScopes(collectionPath, propertyName, out scopes);
Marshal.ThrowExceptionForHR(hr);
return (EnclosingScopes)scopes;
}
public override SettingsStore GetReadOnlySettingsStore(SettingsScope scope)
{
IVsSettingsStore settingsStore;
int hr = this.settingsManager.GetReadOnlySettingsStore((uint)scope, out settingsStore);
Marshal.ThrowExceptionForHR(hr);
return new ShellSettingsStore(settingsStore);
}
public override WritableSettingsStore GetWritableSettingsStore(SettingsScope scope)
{
IVsWritableSettingsStore writableSettingsStore;
int hr = this.settingsManager.GetWritableSettingsStore((uint)scope, out writableSettingsStore);
Marshal.ThrowExceptionForHR(hr);
return new ShellWritableSettingsStore(writableSettingsStore);
}
public override string GetApplicationDataFolder(ApplicationDataFolder folder)
{
string folderPath;
int hr = this.settingsManager.GetApplicationDataFolder((uint)folder, out folderPath);
Marshal.ThrowExceptionForHR(hr);
return folderPath;
}
public override IEnumerable<string> GetCommonExtensionsSearchPaths()
{
uint arraySize;
int hr = this.settingsManager.GetCommonExtensionsSearchPaths(0, null, out arraySize);
Marshal.ThrowExceptionForHR(hr);
string[] searchPaths = new string[arraySize];
hr = this.settingsManager.GetCommonExtensionsSearchPaths((uint)searchPaths.Length, searchPaths, out arraySize);
Marshal.ThrowExceptionForHR(hr);
return searchPaths;
}
private IVsSettingsManager settingsManager;
}
|
[
"[",
"CLSCompliant",
"(",
"false",
")",
"]",
"public",
"sealed",
"class",
"ShellSettingsManager",
":",
"SettingsManager",
"{",
"public",
"ShellSettingsManager",
"(",
"IServiceProvider",
"serviceProvider",
")",
"{",
"HelperMethods",
".",
"CheckNullArgument",
"(",
"serviceProvider",
",",
"\"",
"serviceProvider",
"\"",
")",
";",
"this",
".",
"settingsManager",
"=",
"serviceProvider",
".",
"GetService",
"(",
"typeof",
"(",
"SVsSettingsManager",
")",
")",
"as",
"IVsSettingsManager",
";",
"if",
"(",
"this",
".",
"settingsManager",
"==",
"null",
")",
"{",
"throw",
"new",
"NotSupportedException",
"(",
"typeof",
"(",
"SVsSettingsManager",
")",
".",
"FullName",
")",
";",
"}",
"}",
"public",
"override",
"EnclosingScopes",
"GetCollectionScopes",
"(",
"string",
"collectionPath",
")",
"{",
"HelperMethods",
".",
"CheckNullArgument",
"(",
"collectionPath",
",",
"\"",
"collectionPath",
"\"",
")",
";",
"uint",
"scopes",
";",
"int",
"hr",
"=",
"this",
".",
"settingsManager",
".",
"GetCollectionScopes",
"(",
"collectionPath",
",",
"out",
"scopes",
")",
";",
"Marshal",
".",
"ThrowExceptionForHR",
"(",
"hr",
")",
";",
"return",
"(",
"EnclosingScopes",
")",
"scopes",
";",
"}",
"public",
"override",
"EnclosingScopes",
"GetPropertyScopes",
"(",
"string",
"collectionPath",
",",
"string",
"propertyName",
")",
"{",
"HelperMethods",
".",
"CheckNullArgument",
"(",
"collectionPath",
",",
"\"",
"collectionPath",
"\"",
")",
";",
"HelperMethods",
".",
"CheckNullArgument",
"(",
"propertyName",
",",
"\"",
"propertyName",
"\"",
")",
";",
"uint",
"scopes",
";",
"int",
"hr",
"=",
"this",
".",
"settingsManager",
".",
"GetPropertyScopes",
"(",
"collectionPath",
",",
"propertyName",
",",
"out",
"scopes",
")",
";",
"Marshal",
".",
"ThrowExceptionForHR",
"(",
"hr",
")",
";",
"return",
"(",
"EnclosingScopes",
")",
"scopes",
";",
"}",
"public",
"override",
"SettingsStore",
"GetReadOnlySettingsStore",
"(",
"SettingsScope",
"scope",
")",
"{",
"IVsSettingsStore",
"settingsStore",
";",
"int",
"hr",
"=",
"this",
".",
"settingsManager",
".",
"GetReadOnlySettingsStore",
"(",
"(",
"uint",
")",
"scope",
",",
"out",
"settingsStore",
")",
";",
"Marshal",
".",
"ThrowExceptionForHR",
"(",
"hr",
")",
";",
"return",
"new",
"ShellSettingsStore",
"(",
"settingsStore",
")",
";",
"}",
"public",
"override",
"WritableSettingsStore",
"GetWritableSettingsStore",
"(",
"SettingsScope",
"scope",
")",
"{",
"IVsWritableSettingsStore",
"writableSettingsStore",
";",
"int",
"hr",
"=",
"this",
".",
"settingsManager",
".",
"GetWritableSettingsStore",
"(",
"(",
"uint",
")",
"scope",
",",
"out",
"writableSettingsStore",
")",
";",
"Marshal",
".",
"ThrowExceptionForHR",
"(",
"hr",
")",
";",
"return",
"new",
"ShellWritableSettingsStore",
"(",
"writableSettingsStore",
")",
";",
"}",
"public",
"override",
"string",
"GetApplicationDataFolder",
"(",
"ApplicationDataFolder",
"folder",
")",
"{",
"string",
"folderPath",
";",
"int",
"hr",
"=",
"this",
".",
"settingsManager",
".",
"GetApplicationDataFolder",
"(",
"(",
"uint",
")",
"folder",
",",
"out",
"folderPath",
")",
";",
"Marshal",
".",
"ThrowExceptionForHR",
"(",
"hr",
")",
";",
"return",
"folderPath",
";",
"}",
"public",
"override",
"IEnumerable",
"<",
"string",
">",
"GetCommonExtensionsSearchPaths",
"(",
")",
"{",
"uint",
"arraySize",
";",
"int",
"hr",
"=",
"this",
".",
"settingsManager",
".",
"GetCommonExtensionsSearchPaths",
"(",
"0",
",",
"null",
",",
"out",
"arraySize",
")",
";",
"Marshal",
".",
"ThrowExceptionForHR",
"(",
"hr",
")",
";",
"string",
"[",
"]",
"searchPaths",
"=",
"new",
"string",
"[",
"arraySize",
"]",
";",
"hr",
"=",
"this",
".",
"settingsManager",
".",
"GetCommonExtensionsSearchPaths",
"(",
"(",
"uint",
")",
"searchPaths",
".",
"Length",
",",
"searchPaths",
",",
"out",
"arraySize",
")",
";",
"Marshal",
".",
"ThrowExceptionForHR",
"(",
"hr",
")",
";",
"return",
"searchPaths",
";",
"}",
"private",
"IVsSettingsManager",
"settingsManager",
";",
"}"
] |
This is the gateway class to reach for the settings stored inside the Visual Studio.
|
[
"This",
"is",
"the",
"gateway",
"class",
"to",
"reach",
"for",
"the",
"settings",
"stored",
"inside",
"the",
"Visual",
"Studio",
"."
] |
[
"// Methods of this class have enumeration return values",
"/// <summary>",
"/// Constructor for the SettingsManager class. It requires Service Provider to reach IVsSettingsManager",
"/// which is the interop COM interface of the service that provides the Settings related functionalities.",
"/// </summary>",
"/// <param name=\"serviceProvider\">Service provider of the VS.</param>",
"/// <summary>",
"/// Outputs the scopes that contain the given collection. If more than one scope contains the collection,",
"/// the corresponding bit flags of those scopes are set.",
"/// </summary>",
"/// <param name=\"collectionPath\">Path of the collection to be searched.</param>",
"/// <returns>Enclosing scopes.</returns>",
"/// <summary>",
"/// Outputs the scopes that contain the given property. If more than one scope contains the property,",
"/// the corresponding bit flags of those scopes are set.",
"/// </summary>",
"/// <param name=\"collectionPath\">Path of the collection of the property.</param>",
"/// <param name=\"propertyName\">Name of the property to be searched.</param>",
"/// <returns>Enclosing scopes.</returns>",
"/// <summary>",
"/// Provides the <see cref=\"SettingsStore\"/> class for the requested scope which can be used for read-only ",
"/// operations.",
"/// </summary>",
"/// <param name=\"scope\">Requested scope.</param>",
"/// <returns><see cref=\"SettingsStore\"/> instance that can be used for accessing the scope.</returns>",
"/// <summary>",
"/// Provides the <see cref=\"WritableSettingsStore\"/> class for the requested scope which can be used both for",
"/// reading and writing.",
"/// </summary>",
"/// <param name=\"scope\">Requested scope.</param>",
"/// <exception cref=\"ArgumentException\">If the given scope is not a writable one.</exception>",
"/// <returns><see cref=\"WritableSettingsStore\"/> instance that can be used for accessing the scope.</returns>",
"/// <summary>",
"/// Returns the folder that Visual Studio uses for storing various cache, backup, template, etc. files",
"/// </summary>",
"/// <param name=\"folder\">Requested folder.</param> ",
"/// <returns>Full path of the requested folder.</returns>",
"/// <summary>",
"/// Returns the list of folders that Visual Studio uses for installing/discovering machine-wide extensions.",
"/// </summary>",
"/// <returns>List of extensions root paths.</returns>",
"// Thunked interop COM interface."
] |
[
{
"param": "SettingsManager",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "SettingsManager",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 13
| 547
| 108
|
36345abd62f02a4c5cf40bbbace106d4c93c1fdc
|
clumio-code/clumio-python-sdk
|
clumioapi/models/vcenter.py
|
[
"Apache-2.0"
] |
Python
|
Vcenter
|
Implementation of the 'Vcenter' model.
Attributes:
embedded:
Embedded responses related to the resource.
links:
URLs to pages related to the resource.
backup_region:
The region to which data is backed-up to for the vCenter server. If the vCenter
server's back up region is unavailable, this field has a value of `unavailable`.
Refer to the Back up Regions table for a complete list of back up regions.
cloud_connector_download_url:
The URL at which the Clumio Cloud Connector for this vCenter server can be
downloaded.
endpoint:
The IP address or FQDN of the vCenter server.
id:
The Clumio-assigned ID of the vCenter server.
ip_address:
The IP address or FQDN of the vCenter server.
This field has been replaced by the `endpoint` field
and is being retained for backward compatibility reasons.
organizational_unit_id:
The Clumio-assigned ID of the organizational unit associated with the vCenter.
status:
The connection status of the Clumio Cloud Connector. Examples include "pending",
"connected", "disconnected", "invalid_credentials", "partial", and
"unavailable".
type:
The type of vCenter server. If the vCenter server's type is unavailable, this
field has a value of `unavailable`. Refer to the vCenter Types table for a
complete list of vCenter types.
vcenter_token:
The token given to the Clumio Cloud Connectors to identify the vCenter server.
|
Implementation of the 'Vcenter' model.
|
[
"Implementation",
"of",
"the",
"'",
"Vcenter",
"'",
"model",
"."
] |
class Vcenter:
"""Implementation of the 'Vcenter' model.
Attributes:
embedded:
Embedded responses related to the resource.
links:
URLs to pages related to the resource.
backup_region:
The region to which data is backed-up to for the vCenter server. If the vCenter
server's back up region is unavailable, this field has a value of `unavailable`.
Refer to the Back up Regions table for a complete list of back up regions.
cloud_connector_download_url:
The URL at which the Clumio Cloud Connector for this vCenter server can be
downloaded.
endpoint:
The IP address or FQDN of the vCenter server.
id:
The Clumio-assigned ID of the vCenter server.
ip_address:
The IP address or FQDN of the vCenter server.
This field has been replaced by the `endpoint` field
and is being retained for backward compatibility reasons.
organizational_unit_id:
The Clumio-assigned ID of the organizational unit associated with the vCenter.
status:
The connection status of the Clumio Cloud Connector. Examples include "pending",
"connected", "disconnected", "invalid_credentials", "partial", and
"unavailable".
type:
The type of vCenter server. If the vCenter server's type is unavailable, this
field has a value of `unavailable`. Refer to the vCenter Types table for a
complete list of vCenter types.
vcenter_token:
The token given to the Clumio Cloud Connectors to identify the vCenter server.
"""
# Create a mapping from Model property names to API property names
_names = {
'embedded': '_embedded',
'links': '_links',
'backup_region': 'backup_region',
'cloud_connector_download_url': 'cloud_connector_download_url',
'endpoint': 'endpoint',
'id': 'id',
'ip_address': 'ip_address',
'organizational_unit_id': 'organizational_unit_id',
'status': 'status',
'type': 'type',
'vcenter_token': 'vcenter_token',
}
def __init__(
self,
embedded: vcenter_embedded.VcenterEmbedded = None,
links: vcenter_links.VcenterLinks = None,
backup_region: str = None,
cloud_connector_download_url: str = None,
endpoint: str = None,
id: str = None,
ip_address: str = None,
organizational_unit_id: str = None,
status: str = None,
type: str = None,
vcenter_token: str = None,
) -> None:
"""Constructor for the Vcenter class."""
# Initialize members of the class
self.embedded: vcenter_embedded.VcenterEmbedded = embedded
self.links: vcenter_links.VcenterLinks = links
self.backup_region: str = backup_region
self.cloud_connector_download_url: str = cloud_connector_download_url
self.endpoint: str = endpoint
self.id: str = id
self.ip_address: str = ip_address
self.organizational_unit_id: str = organizational_unit_id
self.status: str = status
self.type: str = type
self.vcenter_token: str = vcenter_token
@classmethod
def from_dictionary(cls: Type, dictionary: Mapping[str, Any]) -> Optional[T]:
"""Creates an instance of this model from a dictionary
Args:
dictionary: A dictionary representation of the object as obtained
from the deserialization of the server's response. The keys
MUST match property names in the API description.
Returns:
object: An instance of this structure class.
"""
if not dictionary:
return None
# Extract variables from the dictionary
key = '_embedded'
embedded = (
vcenter_embedded.VcenterEmbedded.from_dictionary(dictionary.get(key))
if dictionary.get(key)
else None
)
key = '_links'
links = (
vcenter_links.VcenterLinks.from_dictionary(dictionary.get(key))
if dictionary.get(key)
else None
)
backup_region = dictionary.get('backup_region')
cloud_connector_download_url = dictionary.get('cloud_connector_download_url')
endpoint = dictionary.get('endpoint')
id = dictionary.get('id')
ip_address = dictionary.get('ip_address')
organizational_unit_id = dictionary.get('organizational_unit_id')
status = dictionary.get('status')
type = dictionary.get('type')
vcenter_token = dictionary.get('vcenter_token')
# Return an object of this model
return cls(
embedded,
links,
backup_region,
cloud_connector_download_url,
endpoint,
id,
ip_address,
organizational_unit_id,
status,
type,
vcenter_token,
)
|
[
"class",
"Vcenter",
":",
"_names",
"=",
"{",
"'embedded'",
":",
"'_embedded'",
",",
"'links'",
":",
"'_links'",
",",
"'backup_region'",
":",
"'backup_region'",
",",
"'cloud_connector_download_url'",
":",
"'cloud_connector_download_url'",
",",
"'endpoint'",
":",
"'endpoint'",
",",
"'id'",
":",
"'id'",
",",
"'ip_address'",
":",
"'ip_address'",
",",
"'organizational_unit_id'",
":",
"'organizational_unit_id'",
",",
"'status'",
":",
"'status'",
",",
"'type'",
":",
"'type'",
",",
"'vcenter_token'",
":",
"'vcenter_token'",
",",
"}",
"def",
"__init__",
"(",
"self",
",",
"embedded",
":",
"vcenter_embedded",
".",
"VcenterEmbedded",
"=",
"None",
",",
"links",
":",
"vcenter_links",
".",
"VcenterLinks",
"=",
"None",
",",
"backup_region",
":",
"str",
"=",
"None",
",",
"cloud_connector_download_url",
":",
"str",
"=",
"None",
",",
"endpoint",
":",
"str",
"=",
"None",
",",
"id",
":",
"str",
"=",
"None",
",",
"ip_address",
":",
"str",
"=",
"None",
",",
"organizational_unit_id",
":",
"str",
"=",
"None",
",",
"status",
":",
"str",
"=",
"None",
",",
"type",
":",
"str",
"=",
"None",
",",
"vcenter_token",
":",
"str",
"=",
"None",
",",
")",
"->",
"None",
":",
"\"\"\"Constructor for the Vcenter class.\"\"\"",
"self",
".",
"embedded",
":",
"vcenter_embedded",
".",
"VcenterEmbedded",
"=",
"embedded",
"self",
".",
"links",
":",
"vcenter_links",
".",
"VcenterLinks",
"=",
"links",
"self",
".",
"backup_region",
":",
"str",
"=",
"backup_region",
"self",
".",
"cloud_connector_download_url",
":",
"str",
"=",
"cloud_connector_download_url",
"self",
".",
"endpoint",
":",
"str",
"=",
"endpoint",
"self",
".",
"id",
":",
"str",
"=",
"id",
"self",
".",
"ip_address",
":",
"str",
"=",
"ip_address",
"self",
".",
"organizational_unit_id",
":",
"str",
"=",
"organizational_unit_id",
"self",
".",
"status",
":",
"str",
"=",
"status",
"self",
".",
"type",
":",
"str",
"=",
"type",
"self",
".",
"vcenter_token",
":",
"str",
"=",
"vcenter_token",
"@",
"classmethod",
"def",
"from_dictionary",
"(",
"cls",
":",
"Type",
",",
"dictionary",
":",
"Mapping",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"Optional",
"[",
"T",
"]",
":",
"\"\"\"Creates an instance of this model from a dictionary\n\n Args:\n dictionary: A dictionary representation of the object as obtained\n from the deserialization of the server's response. The keys\n MUST match property names in the API description.\n\n Returns:\n object: An instance of this structure class.\n \"\"\"",
"if",
"not",
"dictionary",
":",
"return",
"None",
"key",
"=",
"'_embedded'",
"embedded",
"=",
"(",
"vcenter_embedded",
".",
"VcenterEmbedded",
".",
"from_dictionary",
"(",
"dictionary",
".",
"get",
"(",
"key",
")",
")",
"if",
"dictionary",
".",
"get",
"(",
"key",
")",
"else",
"None",
")",
"key",
"=",
"'_links'",
"links",
"=",
"(",
"vcenter_links",
".",
"VcenterLinks",
".",
"from_dictionary",
"(",
"dictionary",
".",
"get",
"(",
"key",
")",
")",
"if",
"dictionary",
".",
"get",
"(",
"key",
")",
"else",
"None",
")",
"backup_region",
"=",
"dictionary",
".",
"get",
"(",
"'backup_region'",
")",
"cloud_connector_download_url",
"=",
"dictionary",
".",
"get",
"(",
"'cloud_connector_download_url'",
")",
"endpoint",
"=",
"dictionary",
".",
"get",
"(",
"'endpoint'",
")",
"id",
"=",
"dictionary",
".",
"get",
"(",
"'id'",
")",
"ip_address",
"=",
"dictionary",
".",
"get",
"(",
"'ip_address'",
")",
"organizational_unit_id",
"=",
"dictionary",
".",
"get",
"(",
"'organizational_unit_id'",
")",
"status",
"=",
"dictionary",
".",
"get",
"(",
"'status'",
")",
"type",
"=",
"dictionary",
".",
"get",
"(",
"'type'",
")",
"vcenter_token",
"=",
"dictionary",
".",
"get",
"(",
"'vcenter_token'",
")",
"return",
"cls",
"(",
"embedded",
",",
"links",
",",
"backup_region",
",",
"cloud_connector_download_url",
",",
"endpoint",
",",
"id",
",",
"ip_address",
",",
"organizational_unit_id",
",",
"status",
",",
"type",
",",
"vcenter_token",
",",
")"
] |
Implementation of the 'Vcenter' model.
|
[
"Implementation",
"of",
"the",
"'",
"Vcenter",
"'",
"model",
"."
] |
[
"\"\"\"Implementation of the 'Vcenter' model.\n\n Attributes:\n embedded:\n Embedded responses related to the resource.\n links:\n URLs to pages related to the resource.\n backup_region:\n The region to which data is backed-up to for the vCenter server. If the vCenter\n server's back up region is unavailable, this field has a value of `unavailable`.\n Refer to the Back up Regions table for a complete list of back up regions.\n cloud_connector_download_url:\n The URL at which the Clumio Cloud Connector for this vCenter server can be\n downloaded.\n endpoint:\n The IP address or FQDN of the vCenter server.\n id:\n The Clumio-assigned ID of the vCenter server.\n ip_address:\n The IP address or FQDN of the vCenter server.\n This field has been replaced by the `endpoint` field\n and is being retained for backward compatibility reasons.\n organizational_unit_id:\n The Clumio-assigned ID of the organizational unit associated with the vCenter.\n status:\n The connection status of the Clumio Cloud Connector. Examples include \"pending\",\n \"connected\", \"disconnected\", \"invalid_credentials\", \"partial\", and\n \"unavailable\".\n type:\n The type of vCenter server. If the vCenter server's type is unavailable, this\n field has a value of `unavailable`. Refer to the vCenter Types table for a\n complete list of vCenter types.\n vcenter_token:\n The token given to the Clumio Cloud Connectors to identify the vCenter server.\n \"\"\"",
"# Create a mapping from Model property names to API property names",
"\"\"\"Constructor for the Vcenter class.\"\"\"",
"# Initialize members of the class",
"\"\"\"Creates an instance of this model from a dictionary\n\n Args:\n dictionary: A dictionary representation of the object as obtained\n from the deserialization of the server's response. The keys\n MUST match property names in the API description.\n\n Returns:\n object: An instance of this structure class.\n \"\"\"",
"# Extract variables from the dictionary",
"# Return an object of this model"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [
{
"identifier": "embedded",
"type": null,
"docstring": "Embedded responses related to the resource.",
"docstring_tokens": [
"Embedded",
"responses",
"related",
"to",
"the",
"resource",
"."
],
"default": null,
"is_optional": null
},
{
"identifier": "links",
"type": null,
"docstring": "URLs to pages related to the resource.",
"docstring_tokens": [
"URLs",
"to",
"pages",
"related",
"to",
"the",
"resource",
"."
],
"default": null,
"is_optional": null
},
{
"identifier": "backup_region",
"type": null,
"docstring": "The region to which data is backed-up to for the vCenter server. If the vCenter\nserver's back up region is unavailable, this field has a value of `unavailable`.\nRefer to the Back up Regions table for a complete list of back up regions.",
"docstring_tokens": [
"The",
"region",
"to",
"which",
"data",
"is",
"backed",
"-",
"up",
"to",
"for",
"the",
"vCenter",
"server",
".",
"If",
"the",
"vCenter",
"server",
"'",
"s",
"back",
"up",
"region",
"is",
"unavailable",
"this",
"field",
"has",
"a",
"value",
"of",
"`",
"unavailable",
"`",
".",
"Refer",
"to",
"the",
"Back",
"up",
"Regions",
"table",
"for",
"a",
"complete",
"list",
"of",
"back",
"up",
"regions",
"."
],
"default": null,
"is_optional": null
},
{
"identifier": "cloud_connector_download_url",
"type": null,
"docstring": "The URL at which the Clumio Cloud Connector for this vCenter server can be\ndownloaded.",
"docstring_tokens": [
"The",
"URL",
"at",
"which",
"the",
"Clumio",
"Cloud",
"Connector",
"for",
"this",
"vCenter",
"server",
"can",
"be",
"downloaded",
"."
],
"default": null,
"is_optional": null
},
{
"identifier": "endpoint",
"type": null,
"docstring": "The IP address or FQDN of the vCenter server.",
"docstring_tokens": [
"The",
"IP",
"address",
"or",
"FQDN",
"of",
"the",
"vCenter",
"server",
"."
],
"default": null,
"is_optional": null
},
{
"identifier": "id",
"type": null,
"docstring": "The Clumio-assigned ID of the vCenter server.",
"docstring_tokens": [
"The",
"Clumio",
"-",
"assigned",
"ID",
"of",
"the",
"vCenter",
"server",
"."
],
"default": null,
"is_optional": null
},
{
"identifier": "ip_address",
"type": null,
"docstring": "The IP address or FQDN of the vCenter server.\nThis field has been replaced by the `endpoint` field\nand is being retained for backward compatibility reasons.",
"docstring_tokens": [
"The",
"IP",
"address",
"or",
"FQDN",
"of",
"the",
"vCenter",
"server",
".",
"This",
"field",
"has",
"been",
"replaced",
"by",
"the",
"`",
"endpoint",
"`",
"field",
"and",
"is",
"being",
"retained",
"for",
"backward",
"compatibility",
"reasons",
"."
],
"default": null,
"is_optional": null
},
{
"identifier": "organizational_unit_id",
"type": null,
"docstring": "The Clumio-assigned ID of the organizational unit associated with the vCenter.",
"docstring_tokens": [
"The",
"Clumio",
"-",
"assigned",
"ID",
"of",
"the",
"organizational",
"unit",
"associated",
"with",
"the",
"vCenter",
"."
],
"default": null,
"is_optional": null
},
{
"identifier": "status",
"type": null,
"docstring": "The connection status of the Clumio Cloud Connector. Examples include \"pending\",\n\"connected\", \"disconnected\", \"invalid_credentials\", \"partial\", and\n\"unavailable\".",
"docstring_tokens": [
"The",
"connection",
"status",
"of",
"the",
"Clumio",
"Cloud",
"Connector",
".",
"Examples",
"include",
"\"",
"pending",
"\"",
"\"",
"connected",
"\"",
"\"",
"disconnected",
"\"",
"\"",
"invalid_credentials",
"\"",
"\"",
"partial",
"\"",
"and",
"\"",
"unavailable",
"\"",
"."
],
"default": null,
"is_optional": null
},
{
"identifier": "type",
"type": null,
"docstring": "The type of vCenter server. If the vCenter server's type is unavailable, this\nfield has a value of `unavailable`. Refer to the vCenter Types table for a\ncomplete list of vCenter types.",
"docstring_tokens": [
"The",
"type",
"of",
"vCenter",
"server",
".",
"If",
"the",
"vCenter",
"server",
"'",
"s",
"type",
"is",
"unavailable",
"this",
"field",
"has",
"a",
"value",
"of",
"`",
"unavailable",
"`",
".",
"Refer",
"to",
"the",
"vCenter",
"Types",
"table",
"for",
"a",
"complete",
"list",
"of",
"vCenter",
"types",
"."
],
"default": null,
"is_optional": null
},
{
"identifier": "vcenter_token",
"type": null,
"docstring": "The token given to the Clumio Cloud Connectors to identify the vCenter server.",
"docstring_tokens": [
"The",
"token",
"given",
"to",
"the",
"Clumio",
"Cloud",
"Connectors",
"to",
"identify",
"the",
"vCenter",
"server",
"."
],
"default": null,
"is_optional": null
}
],
"others": []
}
| false
| 14
| 1,036
| 340
|
a039b0f69a367fc984263c5501f8d2da01a345d0
|
PrivadoTest/arcobjects-sdk-community-samples
|
Net/Raster/CustomRasterFunction/CSharp/TestWatermarkFunction/Resources.Designer.cs
|
[
"Apache-2.0"
] |
C#
|
Resources
|
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
|
A strongly-typed resource class, for looking up localized strings, etc.
|
[
"A",
"strongly",
"-",
"typed",
"resource",
"class",
"for",
"looking",
"up",
"localized",
"strings",
"etc",
"."
] |
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if (object.ReferenceEquals(resourceMan, null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("TestRasterBuilder.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
internal static string CoclassName
{
get
{
return ResourceManager.GetString("CoclassName", resourceCulture);
}
}
internal static string InterfaceName
{
get
{
return ResourceManager.GetString("InterfaceName", resourceCulture);
}
}
internal static string SourceFile
{
get
{
return ResourceManager.GetString("SourceFile", resourceCulture);
}
}
internal static string TableName
{
get
{
return ResourceManager.GetString("TableName", resourceCulture);
}
}
internal static string TestDataCoverages
{
get
{
return ResourceManager.GetString("TestDataCoverages", resourceCulture);
}
}
internal static string TestDataFGDB
{
get
{
return ResourceManager.GetString("TestDataFGDB", resourceCulture);
}
}
internal static string TestDataPGDB
{
get
{
return ResourceManager.GetString("TestDataPGDB", resourceCulture);
}
}
internal static string TestDataSDC
{
get
{
return ResourceManager.GetString("TestDataSDC", resourceCulture);
}
}
internal static string TestDataShapefiles
{
get
{
return ResourceManager.GetString("TestDataShapefiles", resourceCulture);
}
}
internal static string TestDescription
{
get
{
return ResourceManager.GetString("TestDescription", resourceCulture);
}
}
}
|
[
"[",
"global",
"::",
"System",
".",
"CodeDom",
".",
"Compiler",
".",
"GeneratedCodeAttribute",
"(",
"\"",
"System.Resources.Tools.StronglyTypedResourceBuilder",
"\"",
",",
"\"",
"2.0.0.0",
"\"",
")",
"]",
"[",
"global",
"::",
"System",
".",
"Diagnostics",
".",
"DebuggerNonUserCodeAttribute",
"(",
")",
"]",
"[",
"global",
"::",
"System",
".",
"Runtime",
".",
"CompilerServices",
".",
"CompilerGeneratedAttribute",
"(",
")",
"]",
"internal",
"class",
"Resources",
"{",
"private",
"static",
"global",
"::",
"System",
".",
"Resources",
".",
"ResourceManager",
"resourceMan",
";",
"private",
"static",
"global",
"::",
"System",
".",
"Globalization",
".",
"CultureInfo",
"resourceCulture",
";",
"[",
"global",
"::",
"System",
".",
"Diagnostics",
".",
"CodeAnalysis",
".",
"SuppressMessageAttribute",
"(",
"\"",
"Microsoft.Performance",
"\"",
",",
"\"",
"CA1811:AvoidUncalledPrivateCode",
"\"",
")",
"]",
"internal",
"Resources",
"(",
")",
"{",
"}",
"[",
"global",
"::",
"System",
".",
"ComponentModel",
".",
"EditorBrowsableAttribute",
"(",
"global",
"::",
"System",
".",
"ComponentModel",
".",
"EditorBrowsableState",
".",
"Advanced",
")",
"]",
"internal",
"static",
"global",
"::",
"System",
".",
"Resources",
".",
"ResourceManager",
"ResourceManager",
"{",
"get",
"{",
"if",
"(",
"object",
".",
"ReferenceEquals",
"(",
"resourceMan",
",",
"null",
")",
")",
"{",
"global",
"::",
"System",
".",
"Resources",
".",
"ResourceManager",
"temp",
"=",
"new",
"global",
"::",
"System",
".",
"Resources",
".",
"ResourceManager",
"(",
"\"",
"TestRasterBuilder.Resources",
"\"",
",",
"typeof",
"(",
"Resources",
")",
".",
"Assembly",
")",
";",
"resourceMan",
"=",
"temp",
";",
"}",
"return",
"resourceMan",
";",
"}",
"}",
"[",
"global",
"::",
"System",
".",
"ComponentModel",
".",
"EditorBrowsableAttribute",
"(",
"global",
"::",
"System",
".",
"ComponentModel",
".",
"EditorBrowsableState",
".",
"Advanced",
")",
"]",
"internal",
"static",
"global",
"::",
"System",
".",
"Globalization",
".",
"CultureInfo",
"Culture",
"{",
"get",
"{",
"return",
"resourceCulture",
";",
"}",
"set",
"{",
"resourceCulture",
"=",
"value",
";",
"}",
"}",
"internal",
"static",
"string",
"CoclassName",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"CoclassName",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"InterfaceName",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"InterfaceName",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"SourceFile",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"SourceFile",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"TableName",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"TableName",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"TestDataCoverages",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"TestDataCoverages",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"TestDataFGDB",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"TestDataFGDB",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"TestDataPGDB",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"TestDataPGDB",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"TestDataSDC",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"TestDataSDC",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"TestDataShapefiles",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"TestDataShapefiles",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"TestDescription",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"TestDescription",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"}"
] |
A strongly-typed resource class, for looking up localized strings, etc.
|
[
"A",
"strongly",
"-",
"typed",
"resource",
"class",
"for",
"looking",
"up",
"localized",
"strings",
"etc",
"."
] |
[
"/// <summary>",
"/// Returns the cached ResourceManager instance used by this class.",
"/// </summary>",
"/// <summary>",
"/// Overrides the current thread's CurrentUICulture property for all",
"/// resource lookups using this strongly typed resource class.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to MyCoclass.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to IMyInterface.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Program.cs.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to MyTable.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Geodatabase\\CS94\\Example\\MyCoverages\\.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Geodatabase\\CS94\\Example\\MyData.gdb.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Geodatabase\\CS94\\Example\\MyData.mdb.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Geodatabase\\CS94\\Example\\MySdcData\\.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Geodatabase\\CS94\\Example\\MyShapefiles\\.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to The Geodatabase test template..",
"/// </summary>"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 17
| 575
| 84
|
64f4dc65356f4f7b46825a1fd7bc6a07510e1086
|
eylvisaker/tbsuite
|
src/ErikMath/ErikMath/GeneralMatrix/CholeskyDecomposition.cs
|
[
"MIT"
] |
C#
|
CholeskyDecomposition
|
/// <summary>Cholesky Decomposition.
/// For a symmetric, positive definite matrix A, the Cholesky decomposition
/// is an lower triangular matrix L so that A = L*L'.
/// If the matrix is not symmetric or positive definite, the constructor
/// returns a partial decomposition and sets an internal flag that may
/// be queried by the isSPD() method.
/// </summary>
|
Cholesky Decomposition.
For a symmetric, positive definite matrix A, the Cholesky decomposition
is an lower triangular matrix L so that A = L*L'.
If the matrix is not symmetric or positive definite, the constructor
returns a partial decomposition and sets an internal flag that may
be queried by the isSPD() method.
|
[
"Cholesky",
"Decomposition",
".",
"For",
"a",
"symmetric",
"positive",
"definite",
"matrix",
"A",
"the",
"Cholesky",
"decomposition",
"is",
"an",
"lower",
"triangular",
"matrix",
"L",
"so",
"that",
"A",
"=",
"L",
"*",
"L",
"'",
".",
"If",
"the",
"matrix",
"is",
"not",
"symmetric",
"or",
"positive",
"definite",
"the",
"constructor",
"returns",
"a",
"partial",
"decomposition",
"and",
"sets",
"an",
"internal",
"flag",
"that",
"may",
"be",
"queried",
"by",
"the",
"isSPD",
"()",
"method",
"."
] |
[Serializable]
public class CholeskyDecomposition : System.Runtime.Serialization.ISerializable
{
#region Class variables
private double[][] L;
private int n;
private bool isspd;
#endregion
#region Constructor
public CholeskyDecomposition(GeneralMatrix Arg)
{
double[][] A = Arg.Array;
n = Arg.RowDimension;
L = new double[n][];
for (int i = 0; i < n; i++)
{
L[i] = new double[n];
}
isspd = (Arg.ColumnDimension == n);
for (int j = 0; j < n; j++)
{
double[] Lrowj = L[j];
double d = 0.0;
for (int k = 0; k < j; k++)
{
double[] Lrowk = L[k];
double s = 0.0;
for (int i = 0; i < k; i++)
{
s += Lrowk[i] * Lrowj[i];
}
Lrowj[k] = s = (A[j][k] - s) / L[k][k];
d = d + s * s;
isspd = isspd & (A[k][j] == A[j][k]);
}
d = A[j][j] - d;
isspd = isspd & (d > 0.0);
L[j][j] = System.Math.Sqrt(System.Math.Max(d, 0.0));
for (int k = j + 1; k < n; k++)
{
L[j][k] = 0.0;
}
}
}
#endregion
#region Public Properties
virtual public bool SPD
{
get
{
return isspd;
}
}
#endregion
#region Public Methods
public virtual GeneralMatrix GetL()
{
return new GeneralMatrix(L, n, n);
}
public virtual GeneralMatrix Solve(GeneralMatrix B)
{
if (B.RowDimension != n)
{
throw new System.ArgumentException("Matrix row dimensions must agree.");
}
if (!isspd)
{
throw new System.SystemException("Matrix is not symmetric positive definite.");
}
double[][] X = B.ArrayCopy;
int nx = B.ColumnDimension;
for (int k = 0; k < n; k++)
{
for (int i = k + 1; i < n; i++)
{
for (int j = 0; j < nx; j++)
{
X[i][j] -= X[k][j] * L[i][k];
}
}
for (int j = 0; j < nx; j++)
{
X[k][j] /= L[k][k];
}
}
for (int k = n - 1; k >= 0; k--)
{
for (int j = 0; j < nx; j++)
{
X[k][j] /= L[k][k];
}
for (int i = 0; i < k; i++)
{
for (int j = 0; j < nx; j++)
{
X[i][j] -= X[k][j] * L[k][i];
}
}
}
return new GeneralMatrix(X, n, nx);
}
#endregion
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
}
}
|
[
"[",
"Serializable",
"]",
"public",
"class",
"CholeskyDecomposition",
":",
"System",
".",
"Runtime",
".",
"Serialization",
".",
"ISerializable",
"{",
"region",
" Class variables",
"private",
"double",
"[",
"]",
"[",
"]",
"L",
";",
"private",
"int",
"n",
";",
"private",
"bool",
"isspd",
";",
"endregion",
"region",
" Constructor",
"public",
"CholeskyDecomposition",
"(",
"GeneralMatrix",
"Arg",
")",
"{",
"double",
"[",
"]",
"[",
"]",
"A",
"=",
"Arg",
".",
"Array",
";",
"n",
"=",
"Arg",
".",
"RowDimension",
";",
"L",
"=",
"new",
"double",
"[",
"n",
"]",
"[",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"n",
";",
"i",
"++",
")",
"{",
"L",
"[",
"i",
"]",
"=",
"new",
"double",
"[",
"n",
"]",
";",
"}",
"isspd",
"=",
"(",
"Arg",
".",
"ColumnDimension",
"==",
"n",
")",
";",
"for",
"(",
"int",
"j",
"=",
"0",
";",
"j",
"<",
"n",
";",
"j",
"++",
")",
"{",
"double",
"[",
"]",
"Lrowj",
"=",
"L",
"[",
"j",
"]",
";",
"double",
"d",
"=",
"0.0",
";",
"for",
"(",
"int",
"k",
"=",
"0",
";",
"k",
"<",
"j",
";",
"k",
"++",
")",
"{",
"double",
"[",
"]",
"Lrowk",
"=",
"L",
"[",
"k",
"]",
";",
"double",
"s",
"=",
"0.0",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"k",
";",
"i",
"++",
")",
"{",
"s",
"+=",
"Lrowk",
"[",
"i",
"]",
"*",
"Lrowj",
"[",
"i",
"]",
";",
"}",
"Lrowj",
"[",
"k",
"]",
"=",
"s",
"=",
"(",
"A",
"[",
"j",
"]",
"[",
"k",
"]",
"-",
"s",
")",
"/",
"L",
"[",
"k",
"]",
"[",
"k",
"]",
";",
"d",
"=",
"d",
"+",
"s",
"*",
"s",
";",
"isspd",
"=",
"isspd",
"&",
"(",
"A",
"[",
"k",
"]",
"[",
"j",
"]",
"==",
"A",
"[",
"j",
"]",
"[",
"k",
"]",
")",
";",
"}",
"d",
"=",
"A",
"[",
"j",
"]",
"[",
"j",
"]",
"-",
"d",
";",
"isspd",
"=",
"isspd",
"&",
"(",
"d",
">",
"0.0",
")",
";",
"L",
"[",
"j",
"]",
"[",
"j",
"]",
"=",
"System",
".",
"Math",
".",
"Sqrt",
"(",
"System",
".",
"Math",
".",
"Max",
"(",
"d",
",",
"0.0",
")",
")",
";",
"for",
"(",
"int",
"k",
"=",
"j",
"+",
"1",
";",
"k",
"<",
"n",
";",
"k",
"++",
")",
"{",
"L",
"[",
"j",
"]",
"[",
"k",
"]",
"=",
"0.0",
";",
"}",
"}",
"}",
"endregion",
"region",
" Public Properties",
"virtual",
"public",
"bool",
"SPD",
"{",
"get",
"{",
"return",
"isspd",
";",
"}",
"}",
"endregion",
"region",
" Public Methods",
"public",
"virtual",
"GeneralMatrix",
"GetL",
"(",
")",
"{",
"return",
"new",
"GeneralMatrix",
"(",
"L",
",",
"n",
",",
"n",
")",
";",
"}",
"public",
"virtual",
"GeneralMatrix",
"Solve",
"(",
"GeneralMatrix",
"B",
")",
"{",
"if",
"(",
"B",
".",
"RowDimension",
"!=",
"n",
")",
"{",
"throw",
"new",
"System",
".",
"ArgumentException",
"(",
"\"",
"Matrix row dimensions must agree.",
"\"",
")",
";",
"}",
"if",
"(",
"!",
"isspd",
")",
"{",
"throw",
"new",
"System",
".",
"SystemException",
"(",
"\"",
"Matrix is not symmetric positive definite.",
"\"",
")",
";",
"}",
"double",
"[",
"]",
"[",
"]",
"X",
"=",
"B",
".",
"ArrayCopy",
";",
"int",
"nx",
"=",
"B",
".",
"ColumnDimension",
";",
"for",
"(",
"int",
"k",
"=",
"0",
";",
"k",
"<",
"n",
";",
"k",
"++",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"k",
"+",
"1",
";",
"i",
"<",
"n",
";",
"i",
"++",
")",
"{",
"for",
"(",
"int",
"j",
"=",
"0",
";",
"j",
"<",
"nx",
";",
"j",
"++",
")",
"{",
"X",
"[",
"i",
"]",
"[",
"j",
"]",
"-=",
"X",
"[",
"k",
"]",
"[",
"j",
"]",
"*",
"L",
"[",
"i",
"]",
"[",
"k",
"]",
";",
"}",
"}",
"for",
"(",
"int",
"j",
"=",
"0",
";",
"j",
"<",
"nx",
";",
"j",
"++",
")",
"{",
"X",
"[",
"k",
"]",
"[",
"j",
"]",
"/=",
"L",
"[",
"k",
"]",
"[",
"k",
"]",
";",
"}",
"}",
"for",
"(",
"int",
"k",
"=",
"n",
"-",
"1",
";",
"k",
">=",
"0",
";",
"k",
"--",
")",
"{",
"for",
"(",
"int",
"j",
"=",
"0",
";",
"j",
"<",
"nx",
";",
"j",
"++",
")",
"{",
"X",
"[",
"k",
"]",
"[",
"j",
"]",
"/=",
"L",
"[",
"k",
"]",
"[",
"k",
"]",
";",
"}",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"k",
";",
"i",
"++",
")",
"{",
"for",
"(",
"int",
"j",
"=",
"0",
";",
"j",
"<",
"nx",
";",
"j",
"++",
")",
"{",
"X",
"[",
"i",
"]",
"[",
"j",
"]",
"-=",
"X",
"[",
"k",
"]",
"[",
"j",
"]",
"*",
"L",
"[",
"k",
"]",
"[",
"i",
"]",
";",
"}",
"}",
"}",
"return",
"new",
"GeneralMatrix",
"(",
"X",
",",
"n",
",",
"nx",
")",
";",
"}",
"endregion",
"void",
"ISerializable",
".",
"GetObjectData",
"(",
"SerializationInfo",
"info",
",",
"StreamingContext",
"context",
")",
"{",
"}",
"}"
] |
Cholesky Decomposition.
|
[
"Cholesky",
"Decomposition",
"."
] |
[
"/// <summary>Array for internal storage of decomposition.",
"/// @serial internal array storage.",
"/// </summary>",
"/// <summary>Row and column dimension (square matrix).",
"/// @serial matrix dimension.",
"/// </summary>",
"/// <summary>Symmetric and positive definite flag.",
"/// @serial is symmetric and positive definite flag.",
"/// </summary>",
" // Class variables",
"/// <summary>Cholesky algorithm for symmetric and positive definite matrix.</summary>",
"/// <param name=\"Arg\"> Square, symmetric matrix.",
"/// </param>",
"/// <returns> Structure to access L and isspd flag.",
"/// </returns>",
"// Initialize.",
"// Main loop.",
" // Constructor",
"/// <summary>Is the matrix symmetric and positive definite?</summary>",
"/// <returns> true if A is symmetric and positive definite.",
"/// </returns>",
" // Public Properties",
"/// <summary>Return triangular factor.</summary>",
"/// <returns> L",
"/// </returns>",
"/// <summary>Solve A*X = B</summary>",
"/// <param name=\"B\"> A Matrix with as many rows as A and any number of columns.",
"/// </param>",
"/// <returns> X so that L*L'*X = B",
"/// </returns>",
"/// <exception cref=\"System.ArgumentException\"> Matrix row dimensions must agree.",
"/// </exception>",
"/// <exception cref=\"System.SystemException\"> Matrix is not symmetric positive definite.",
"/// </exception>",
"// Copy right hand side.",
"// Solve L*Y = B;",
"// Solve L'*X = Y;",
" // Public Methods",
"// A method called when serializing this class."
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 19
| 819
| 82
|
ef9fe5efaff976d4a088b8724ead6ea943f3fcd0
|
kartoflanka/slawomirjodynski-iosched
|
android/src/com/google/android/apps/iosched/ui/widget/ShowHideMasterLayout.java
|
[
"Apache-2.0"
] |
Java
|
ShowHideMasterLayout
|
/**
* A layout that supports the Show/Hide pattern for portrait tablet layouts. See <a
* href="http://developer.android.com/design/patterns/multi-pane-layouts.html#orientation">Android
* Design > Patterns > Multi-pane Layouts & gt; Compound Views and Orientation Changes</a> for
* more details on this pattern. This layout should normally be used in association with the Up
* button. Specifically, show the master pane using {@link #showMaster(boolean, int)} when the Up
* button is pressed. If the master pane is visible, defer to normal Up behavior.
*
* <p>TODO: swiping should be more tactile and actually follow the user's finger.
*
* <p>Requires API level 11
*/
|
A layout that supports the Show/Hide pattern for portrait tablet layouts. See Android
Design > Patterns > Multi-pane Layouts & gt; Compound Views and Orientation Changes for
more details on this pattern. This layout should normally be used in association with the Up
button. Specifically, show the master pane using #showMaster(boolean, int) when the Up
button is pressed. If the master pane is visible, defer to normal Up behavior.
Requires API level 11
|
[
"A",
"layout",
"that",
"supports",
"the",
"Show",
"/",
"Hide",
"pattern",
"for",
"portrait",
"tablet",
"layouts",
".",
"See",
"Android",
"Design",
">",
"Patterns",
">",
"Multi",
"-",
"pane",
"Layouts",
"&",
"gt",
";",
"Compound",
"Views",
"and",
"Orientation",
"Changes",
"for",
"more",
"details",
"on",
"this",
"pattern",
".",
"This",
"layout",
"should",
"normally",
"be",
"used",
"in",
"association",
"with",
"the",
"Up",
"button",
".",
"Specifically",
"show",
"the",
"master",
"pane",
"using",
"#showMaster",
"(",
"boolean",
"int",
")",
"when",
"the",
"Up",
"button",
"is",
"pressed",
".",
"If",
"the",
"master",
"pane",
"is",
"visible",
"defer",
"to",
"normal",
"Up",
"behavior",
".",
"Requires",
"API",
"level",
"11"
] |
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class ShowHideMasterLayout extends ViewGroup implements Animator.AnimatorListener {
private static final String TAG = makeLogTag(ShowHideMasterLayout.class);
/**
* A flag for {@link #showMaster(boolean, int)} indicating that the change in visiblity should
* not be animated.
*/
public static final int FLAG_IMMEDIATE = 0x1;
private boolean mFirstShow = true;
private boolean mMasterVisible = true;
private View mMasterView;
private View mDetailView;
private OnMasterVisibilityChangedListener mOnMasterVisibilityChangedListener;
private GestureDetector mGestureDetector;
private boolean mFlingToExposeMaster;
private boolean mIsAnimating;
private Runnable mShowMasterCompleteRunnable;
// The last measured master width, including its margins.
private int mTranslateAmount;
public interface OnMasterVisibilityChangedListener {
public void onMasterVisibilityChanged(boolean visible);
}
public ShowHideMasterLayout(Context context) {
super(context);
init();
}
public ShowHideMasterLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public ShowHideMasterLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
mGestureDetector = new GestureDetector(getContext(), mGestureListener);
}
@Override
public LayoutParams generateLayoutParams(AttributeSet attrs) {
return new MarginLayoutParams(getContext(), attrs);
}
@Override
protected LayoutParams generateLayoutParams(LayoutParams p) {
return new MarginLayoutParams(p);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int count = getChildCount();
// Measure once to find the maximum child size.
int maxHeight = 0;
int maxWidth = 0;
int childState = 0;
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() == GONE) {
continue;
}
measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
maxWidth = Math.max(maxWidth, child.getMeasuredWidth()
+ lp.leftMargin + lp.rightMargin);
maxHeight = Math.max(maxHeight, child.getMeasuredHeight()
+ lp.topMargin + lp.bottomMargin);
childState = combineMeasuredStates(childState, child.getMeasuredState());
}
// Account for padding too
maxWidth += getPaddingLeft() + getPaddingRight();
maxHeight += getPaddingLeft() + getPaddingRight();
// Check against our minimum height and width
maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());
maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());
// Set our own measured size
setMeasuredDimension(
resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
resolveSizeAndState(maxHeight, heightMeasureSpec,
childState << MEASURED_HEIGHT_STATE_SHIFT));
// Measure children for them to set their measured dimensions
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() == GONE) {
continue;
}
final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
int childWidthMeasureSpec;
int childHeightMeasureSpec;
if (lp.width == LayoutParams.MATCH_PARENT) {
childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth() -
getPaddingLeft() - getPaddingRight() -
lp.leftMargin - lp.rightMargin,
MeasureSpec.EXACTLY);
} else {
childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec,
getPaddingLeft() + getPaddingRight() + lp.leftMargin + lp.rightMargin,
lp.width);
}
if (lp.height == LayoutParams.MATCH_PARENT) {
childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight() -
getPaddingTop() - getPaddingBottom() -
lp.topMargin - lp.bottomMargin,
MeasureSpec.EXACTLY);
} else {
childHeightMeasureSpec = getChildMeasureSpec(heightMeasureSpec,
getPaddingTop() + getPaddingBottom() + lp.topMargin + lp.bottomMargin,
lp.height);
}
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
updateChildReferences();
if (mMasterView == null || mDetailView == null) {
LOGW(TAG, "Master or detail is missing (need 2 children), can't layout.");
return;
}
int masterWidth = mMasterView.getMeasuredWidth();
MarginLayoutParams masterLp = (MarginLayoutParams) mMasterView.getLayoutParams();
MarginLayoutParams detailLp = (MarginLayoutParams) mDetailView.getLayoutParams();
mTranslateAmount = masterWidth + masterLp.leftMargin + masterLp.rightMargin;
mMasterView.layout(
l + masterLp.leftMargin,
t + masterLp.topMargin,
l + masterLp.leftMargin + masterWidth,
b - masterLp.bottomMargin);
mDetailView.layout(
l + detailLp.leftMargin + mTranslateAmount,
t + detailLp.topMargin,
r - detailLp.rightMargin + mTranslateAmount,
b - detailLp.bottomMargin);
// Update translationX values
if (!mIsAnimating) {
final float translationX = mMasterVisible ? 0 : -mTranslateAmount;
mMasterView.setTranslationX(translationX);
mDetailView.setTranslationX(translationX);
}
}
private void updateChildReferences() {
int childCount = getChildCount();
mMasterView = (childCount > 0) ? getChildAt(0) : null;
mDetailView = (childCount > 1) ? getChildAt(1) : null;
}
/**
* Allow or disallow the user to flick right on the detail pane to expose the master pane.
* @param enabled Whether or not to enable this interaction.
*/
public void setFlingToExposeMasterEnabled(boolean enabled) {
mFlingToExposeMaster = enabled;
}
/**
* Request the given listener be notified when the master pane is shown or hidden.
*
* @param listener The listener to notify when the master pane is shown or hidden.
*/
public void setOnMasterVisibilityChangedListener(OnMasterVisibilityChangedListener listener) {
mOnMasterVisibilityChangedListener = listener;
}
/**
* Returns whether or not the master pane is visible.
*
* @return True if the master pane is visible.
*/
public boolean isMasterVisible() {
return mMasterVisible;
}
/**
* Calls {@link #showMaster(boolean, int, Runnable)} with a null runnable.
*/
public void showMaster(boolean show, int flags) {
showMaster(show, flags, null);
}
/**
* Shows or hides the master pane.
*
* @param show Whether or not to show the master pane.
* @param flags {@link #FLAG_IMMEDIATE} to show/hide immediately, or 0 to animate.
* @param completeRunnable An optional runnable to run when any animations related to this are
* complete.
*/
public void showMaster(boolean show, int flags, Runnable completeRunnable) {
if (!mFirstShow && mMasterVisible == show) {
return;
}
mShowMasterCompleteRunnable = completeRunnable;
mFirstShow = false;
mMasterVisible = show;
if (mOnMasterVisibilityChangedListener != null) {
mOnMasterVisibilityChangedListener.onMasterVisibilityChanged(show);
}
updateChildReferences();
if (mMasterView == null || mDetailView == null) {
LOGW(TAG, "Master or detail is missing (need 2 children), can't change translation.");
return;
}
final float translationX = show ? 0 : -mTranslateAmount;
if ((flags & FLAG_IMMEDIATE) != 0) {
mMasterView.setTranslationX(translationX);
mDetailView.setTranslationX(translationX);
if (mShowMasterCompleteRunnable != null) {
mShowMasterCompleteRunnable.run();
mShowMasterCompleteRunnable = null;
}
} else {
final long duration = getResources().getInteger(android.R.integer.config_shortAnimTime);
// Animate if we have Honeycomb APIs, don't animate otherwise
mIsAnimating = true;
AnimatorSet animatorSet = new AnimatorSet();
mMasterView.setLayerType(LAYER_TYPE_HARDWARE, null);
mDetailView.setLayerType(LAYER_TYPE_HARDWARE, null);
animatorSet
.play(ObjectAnimator
.ofFloat(mMasterView, "translationX", translationX)
.setDuration(duration))
.with(ObjectAnimator
.ofFloat(mDetailView, "translationX", translationX)
.setDuration(duration));
animatorSet.addListener(this);
animatorSet.start();
// For API level 12+, use this instead:
// mMasterView.animate().translationX().setDuration(duration);
// mDetailView.animate().translationX(show ? masterWidth : 0).setDuration(duration);
}
}
@Override
public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
// Really bad hack... we really shouldn't do this.
//super.requestDisallowInterceptTouchEvent(disallowIntercept);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
if (mFlingToExposeMaster
&& !mMasterVisible) {
mGestureDetector.onTouchEvent(event);
}
if (event.getAction() == MotionEvent.ACTION_DOWN && mMasterView != null && mMasterVisible) {
// If the master is visible, touching in the detail area should hide the master.
if (event.getX() > mTranslateAmount) {
return true;
}
}
return super.onInterceptTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (mFlingToExposeMaster
&& !mMasterVisible
&& mGestureDetector.onTouchEvent(event)) {
return true;
}
if (event.getAction() == MotionEvent.ACTION_DOWN && mMasterView != null && mMasterVisible) {
// If the master is visible, touching in the detail area should hide the master.
if (event.getX() > mTranslateAmount) {
showMaster(false, 0);
return true;
}
}
return super.onTouchEvent(event);
}
@Override
public void onAnimationStart(Animator animator) {
}
@Override
public void onAnimationEnd(Animator animator) {
mIsAnimating = false;
mMasterView.setLayerType(LAYER_TYPE_NONE, null);
mDetailView.setLayerType(LAYER_TYPE_NONE, null);
requestLayout();
if (mShowMasterCompleteRunnable != null) {
mShowMasterCompleteRunnable.run();
mShowMasterCompleteRunnable = null;
}
}
@Override
public void onAnimationCancel(Animator animator) {
mIsAnimating = false;
mMasterView.setLayerType(LAYER_TYPE_NONE, null);
mDetailView.setLayerType(LAYER_TYPE_NONE, null);
requestLayout();
if (mShowMasterCompleteRunnable != null) {
mShowMasterCompleteRunnable.run();
mShowMasterCompleteRunnable = null;
}
}
@Override
public void onAnimationRepeat(Animator animator) {
}
private final GestureDetector.OnGestureListener mGestureListener =
new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onDown(MotionEvent e) {
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
ViewConfiguration viewConfig = ViewConfiguration.get(getContext());
float absVelocityX = Math.abs(velocityX);
float absVelocityY = Math.abs(velocityY);
if (mFlingToExposeMaster
&& !mMasterVisible
&& velocityX > 0
&& absVelocityX >= absVelocityY // Fling at least as hard in X as in Y
&& absVelocityX > viewConfig.getScaledMinimumFlingVelocity()
&& absVelocityX < viewConfig.getScaledMaximumFlingVelocity()) {
showMaster(true, 0);
return true;
}
return super.onFling(e1, e2, velocityX, velocityY);
}
};
}
|
[
"@",
"TargetApi",
"(",
"Build",
".",
"VERSION_CODES",
".",
"HONEYCOMB",
")",
"public",
"class",
"ShowHideMasterLayout",
"extends",
"ViewGroup",
"implements",
"Animator",
".",
"AnimatorListener",
"{",
"private",
"static",
"final",
"String",
"TAG",
"=",
"makeLogTag",
"(",
"ShowHideMasterLayout",
".",
"class",
")",
";",
"/**\n * A flag for {@link #showMaster(boolean, int)} indicating that the change in visiblity should\n * not be animated.\n */",
"public",
"static",
"final",
"int",
"FLAG_IMMEDIATE",
"=",
"0x1",
";",
"private",
"boolean",
"mFirstShow",
"=",
"true",
";",
"private",
"boolean",
"mMasterVisible",
"=",
"true",
";",
"private",
"View",
"mMasterView",
";",
"private",
"View",
"mDetailView",
";",
"private",
"OnMasterVisibilityChangedListener",
"mOnMasterVisibilityChangedListener",
";",
"private",
"GestureDetector",
"mGestureDetector",
";",
"private",
"boolean",
"mFlingToExposeMaster",
";",
"private",
"boolean",
"mIsAnimating",
";",
"private",
"Runnable",
"mShowMasterCompleteRunnable",
";",
"private",
"int",
"mTranslateAmount",
";",
"public",
"interface",
"OnMasterVisibilityChangedListener",
"{",
"public",
"void",
"onMasterVisibilityChanged",
"(",
"boolean",
"visible",
")",
";",
"}",
"public",
"ShowHideMasterLayout",
"(",
"Context",
"context",
")",
"{",
"super",
"(",
"context",
")",
";",
"init",
"(",
")",
";",
"}",
"public",
"ShowHideMasterLayout",
"(",
"Context",
"context",
",",
"AttributeSet",
"attrs",
")",
"{",
"super",
"(",
"context",
",",
"attrs",
")",
";",
"init",
"(",
")",
";",
"}",
"public",
"ShowHideMasterLayout",
"(",
"Context",
"context",
",",
"AttributeSet",
"attrs",
",",
"int",
"defStyle",
")",
"{",
"super",
"(",
"context",
",",
"attrs",
",",
"defStyle",
")",
";",
"init",
"(",
")",
";",
"}",
"private",
"void",
"init",
"(",
")",
"{",
"mGestureDetector",
"=",
"new",
"GestureDetector",
"(",
"getContext",
"(",
")",
",",
"mGestureListener",
")",
";",
"}",
"@",
"Override",
"public",
"LayoutParams",
"generateLayoutParams",
"(",
"AttributeSet",
"attrs",
")",
"{",
"return",
"new",
"MarginLayoutParams",
"(",
"getContext",
"(",
")",
",",
"attrs",
")",
";",
"}",
"@",
"Override",
"protected",
"LayoutParams",
"generateLayoutParams",
"(",
"LayoutParams",
"p",
")",
"{",
"return",
"new",
"MarginLayoutParams",
"(",
"p",
")",
";",
"}",
"@",
"Override",
"protected",
"void",
"onMeasure",
"(",
"int",
"widthMeasureSpec",
",",
"int",
"heightMeasureSpec",
")",
"{",
"int",
"count",
"=",
"getChildCount",
"(",
")",
";",
"int",
"maxHeight",
"=",
"0",
";",
"int",
"maxWidth",
"=",
"0",
";",
"int",
"childState",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"count",
";",
"i",
"++",
")",
"{",
"final",
"View",
"child",
"=",
"getChildAt",
"(",
"i",
")",
";",
"if",
"(",
"child",
".",
"getVisibility",
"(",
")",
"==",
"GONE",
")",
"{",
"continue",
";",
"}",
"measureChildWithMargins",
"(",
"child",
",",
"widthMeasureSpec",
",",
"0",
",",
"heightMeasureSpec",
",",
"0",
")",
";",
"final",
"MarginLayoutParams",
"lp",
"=",
"(",
"MarginLayoutParams",
")",
"child",
".",
"getLayoutParams",
"(",
")",
";",
"maxWidth",
"=",
"Math",
".",
"max",
"(",
"maxWidth",
",",
"child",
".",
"getMeasuredWidth",
"(",
")",
"+",
"lp",
".",
"leftMargin",
"+",
"lp",
".",
"rightMargin",
")",
";",
"maxHeight",
"=",
"Math",
".",
"max",
"(",
"maxHeight",
",",
"child",
".",
"getMeasuredHeight",
"(",
")",
"+",
"lp",
".",
"topMargin",
"+",
"lp",
".",
"bottomMargin",
")",
";",
"childState",
"=",
"combineMeasuredStates",
"(",
"childState",
",",
"child",
".",
"getMeasuredState",
"(",
")",
")",
";",
"}",
"maxWidth",
"+=",
"getPaddingLeft",
"(",
")",
"+",
"getPaddingRight",
"(",
")",
";",
"maxHeight",
"+=",
"getPaddingLeft",
"(",
")",
"+",
"getPaddingRight",
"(",
")",
";",
"maxHeight",
"=",
"Math",
".",
"max",
"(",
"maxHeight",
",",
"getSuggestedMinimumHeight",
"(",
")",
")",
";",
"maxWidth",
"=",
"Math",
".",
"max",
"(",
"maxWidth",
",",
"getSuggestedMinimumWidth",
"(",
")",
")",
";",
"setMeasuredDimension",
"(",
"resolveSizeAndState",
"(",
"maxWidth",
",",
"widthMeasureSpec",
",",
"childState",
")",
",",
"resolveSizeAndState",
"(",
"maxHeight",
",",
"heightMeasureSpec",
",",
"childState",
"<<",
"MEASURED_HEIGHT_STATE_SHIFT",
")",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"count",
";",
"i",
"++",
")",
"{",
"final",
"View",
"child",
"=",
"getChildAt",
"(",
"i",
")",
";",
"if",
"(",
"child",
".",
"getVisibility",
"(",
")",
"==",
"GONE",
")",
"{",
"continue",
";",
"}",
"final",
"MarginLayoutParams",
"lp",
"=",
"(",
"MarginLayoutParams",
")",
"child",
".",
"getLayoutParams",
"(",
")",
";",
"int",
"childWidthMeasureSpec",
";",
"int",
"childHeightMeasureSpec",
";",
"if",
"(",
"lp",
".",
"width",
"==",
"LayoutParams",
".",
"MATCH_PARENT",
")",
"{",
"childWidthMeasureSpec",
"=",
"MeasureSpec",
".",
"makeMeasureSpec",
"(",
"getMeasuredWidth",
"(",
")",
"-",
"getPaddingLeft",
"(",
")",
"-",
"getPaddingRight",
"(",
")",
"-",
"lp",
".",
"leftMargin",
"-",
"lp",
".",
"rightMargin",
",",
"MeasureSpec",
".",
"EXACTLY",
")",
";",
"}",
"else",
"{",
"childWidthMeasureSpec",
"=",
"getChildMeasureSpec",
"(",
"widthMeasureSpec",
",",
"getPaddingLeft",
"(",
")",
"+",
"getPaddingRight",
"(",
")",
"+",
"lp",
".",
"leftMargin",
"+",
"lp",
".",
"rightMargin",
",",
"lp",
".",
"width",
")",
";",
"}",
"if",
"(",
"lp",
".",
"height",
"==",
"LayoutParams",
".",
"MATCH_PARENT",
")",
"{",
"childHeightMeasureSpec",
"=",
"MeasureSpec",
".",
"makeMeasureSpec",
"(",
"getMeasuredHeight",
"(",
")",
"-",
"getPaddingTop",
"(",
")",
"-",
"getPaddingBottom",
"(",
")",
"-",
"lp",
".",
"topMargin",
"-",
"lp",
".",
"bottomMargin",
",",
"MeasureSpec",
".",
"EXACTLY",
")",
";",
"}",
"else",
"{",
"childHeightMeasureSpec",
"=",
"getChildMeasureSpec",
"(",
"heightMeasureSpec",
",",
"getPaddingTop",
"(",
")",
"+",
"getPaddingBottom",
"(",
")",
"+",
"lp",
".",
"topMargin",
"+",
"lp",
".",
"bottomMargin",
",",
"lp",
".",
"height",
")",
";",
"}",
"child",
".",
"measure",
"(",
"childWidthMeasureSpec",
",",
"childHeightMeasureSpec",
")",
";",
"}",
"}",
"@",
"Override",
"protected",
"void",
"onLayout",
"(",
"boolean",
"changed",
",",
"int",
"l",
",",
"int",
"t",
",",
"int",
"r",
",",
"int",
"b",
")",
"{",
"updateChildReferences",
"(",
")",
";",
"if",
"(",
"mMasterView",
"==",
"null",
"||",
"mDetailView",
"==",
"null",
")",
"{",
"LOGW",
"(",
"TAG",
",",
"\"",
"Master or detail is missing (need 2 children), can't layout.",
"\"",
")",
";",
"return",
";",
"}",
"int",
"masterWidth",
"=",
"mMasterView",
".",
"getMeasuredWidth",
"(",
")",
";",
"MarginLayoutParams",
"masterLp",
"=",
"(",
"MarginLayoutParams",
")",
"mMasterView",
".",
"getLayoutParams",
"(",
")",
";",
"MarginLayoutParams",
"detailLp",
"=",
"(",
"MarginLayoutParams",
")",
"mDetailView",
".",
"getLayoutParams",
"(",
")",
";",
"mTranslateAmount",
"=",
"masterWidth",
"+",
"masterLp",
".",
"leftMargin",
"+",
"masterLp",
".",
"rightMargin",
";",
"mMasterView",
".",
"layout",
"(",
"l",
"+",
"masterLp",
".",
"leftMargin",
",",
"t",
"+",
"masterLp",
".",
"topMargin",
",",
"l",
"+",
"masterLp",
".",
"leftMargin",
"+",
"masterWidth",
",",
"b",
"-",
"masterLp",
".",
"bottomMargin",
")",
";",
"mDetailView",
".",
"layout",
"(",
"l",
"+",
"detailLp",
".",
"leftMargin",
"+",
"mTranslateAmount",
",",
"t",
"+",
"detailLp",
".",
"topMargin",
",",
"r",
"-",
"detailLp",
".",
"rightMargin",
"+",
"mTranslateAmount",
",",
"b",
"-",
"detailLp",
".",
"bottomMargin",
")",
";",
"if",
"(",
"!",
"mIsAnimating",
")",
"{",
"final",
"float",
"translationX",
"=",
"mMasterVisible",
"?",
"0",
":",
"-",
"mTranslateAmount",
";",
"mMasterView",
".",
"setTranslationX",
"(",
"translationX",
")",
";",
"mDetailView",
".",
"setTranslationX",
"(",
"translationX",
")",
";",
"}",
"}",
"private",
"void",
"updateChildReferences",
"(",
")",
"{",
"int",
"childCount",
"=",
"getChildCount",
"(",
")",
";",
"mMasterView",
"=",
"(",
"childCount",
">",
"0",
")",
"?",
"getChildAt",
"(",
"0",
")",
":",
"null",
";",
"mDetailView",
"=",
"(",
"childCount",
">",
"1",
")",
"?",
"getChildAt",
"(",
"1",
")",
":",
"null",
";",
"}",
"/**\n * Allow or disallow the user to flick right on the detail pane to expose the master pane.\n * @param enabled Whether or not to enable this interaction.\n */",
"public",
"void",
"setFlingToExposeMasterEnabled",
"(",
"boolean",
"enabled",
")",
"{",
"mFlingToExposeMaster",
"=",
"enabled",
";",
"}",
"/**\n * Request the given listener be notified when the master pane is shown or hidden.\n *\n * @param listener The listener to notify when the master pane is shown or hidden.\n */",
"public",
"void",
"setOnMasterVisibilityChangedListener",
"(",
"OnMasterVisibilityChangedListener",
"listener",
")",
"{",
"mOnMasterVisibilityChangedListener",
"=",
"listener",
";",
"}",
"/**\n * Returns whether or not the master pane is visible.\n *\n * @return True if the master pane is visible.\n */",
"public",
"boolean",
"isMasterVisible",
"(",
")",
"{",
"return",
"mMasterVisible",
";",
"}",
"/**\n * Calls {@link #showMaster(boolean, int, Runnable)} with a null runnable.\n */",
"public",
"void",
"showMaster",
"(",
"boolean",
"show",
",",
"int",
"flags",
")",
"{",
"showMaster",
"(",
"show",
",",
"flags",
",",
"null",
")",
";",
"}",
"/**\n * Shows or hides the master pane.\n *\n * @param show Whether or not to show the master pane.\n * @param flags {@link #FLAG_IMMEDIATE} to show/hide immediately, or 0 to animate.\n * @param completeRunnable An optional runnable to run when any animations related to this are\n * complete.\n */",
"public",
"void",
"showMaster",
"(",
"boolean",
"show",
",",
"int",
"flags",
",",
"Runnable",
"completeRunnable",
")",
"{",
"if",
"(",
"!",
"mFirstShow",
"&&",
"mMasterVisible",
"==",
"show",
")",
"{",
"return",
";",
"}",
"mShowMasterCompleteRunnable",
"=",
"completeRunnable",
";",
"mFirstShow",
"=",
"false",
";",
"mMasterVisible",
"=",
"show",
";",
"if",
"(",
"mOnMasterVisibilityChangedListener",
"!=",
"null",
")",
"{",
"mOnMasterVisibilityChangedListener",
".",
"onMasterVisibilityChanged",
"(",
"show",
")",
";",
"}",
"updateChildReferences",
"(",
")",
";",
"if",
"(",
"mMasterView",
"==",
"null",
"||",
"mDetailView",
"==",
"null",
")",
"{",
"LOGW",
"(",
"TAG",
",",
"\"",
"Master or detail is missing (need 2 children), can't change translation.",
"\"",
")",
";",
"return",
";",
"}",
"final",
"float",
"translationX",
"=",
"show",
"?",
"0",
":",
"-",
"mTranslateAmount",
";",
"if",
"(",
"(",
"flags",
"&",
"FLAG_IMMEDIATE",
")",
"!=",
"0",
")",
"{",
"mMasterView",
".",
"setTranslationX",
"(",
"translationX",
")",
";",
"mDetailView",
".",
"setTranslationX",
"(",
"translationX",
")",
";",
"if",
"(",
"mShowMasterCompleteRunnable",
"!=",
"null",
")",
"{",
"mShowMasterCompleteRunnable",
".",
"run",
"(",
")",
";",
"mShowMasterCompleteRunnable",
"=",
"null",
";",
"}",
"}",
"else",
"{",
"final",
"long",
"duration",
"=",
"getResources",
"(",
")",
".",
"getInteger",
"(",
"android",
".",
"R",
".",
"integer",
".",
"config_shortAnimTime",
")",
";",
"mIsAnimating",
"=",
"true",
";",
"AnimatorSet",
"animatorSet",
"=",
"new",
"AnimatorSet",
"(",
")",
";",
"mMasterView",
".",
"setLayerType",
"(",
"LAYER_TYPE_HARDWARE",
",",
"null",
")",
";",
"mDetailView",
".",
"setLayerType",
"(",
"LAYER_TYPE_HARDWARE",
",",
"null",
")",
";",
"animatorSet",
".",
"play",
"(",
"ObjectAnimator",
".",
"ofFloat",
"(",
"mMasterView",
",",
"\"",
"translationX",
"\"",
",",
"translationX",
")",
".",
"setDuration",
"(",
"duration",
")",
")",
".",
"with",
"(",
"ObjectAnimator",
".",
"ofFloat",
"(",
"mDetailView",
",",
"\"",
"translationX",
"\"",
",",
"translationX",
")",
".",
"setDuration",
"(",
"duration",
")",
")",
";",
"animatorSet",
".",
"addListener",
"(",
"this",
")",
";",
"animatorSet",
".",
"start",
"(",
")",
";",
"}",
"}",
"@",
"Override",
"public",
"void",
"requestDisallowInterceptTouchEvent",
"(",
"boolean",
"disallowIntercept",
")",
"{",
"}",
"@",
"Override",
"public",
"boolean",
"onInterceptTouchEvent",
"(",
"MotionEvent",
"event",
")",
"{",
"if",
"(",
"mFlingToExposeMaster",
"&&",
"!",
"mMasterVisible",
")",
"{",
"mGestureDetector",
".",
"onTouchEvent",
"(",
"event",
")",
";",
"}",
"if",
"(",
"event",
".",
"getAction",
"(",
")",
"==",
"MotionEvent",
".",
"ACTION_DOWN",
"&&",
"mMasterView",
"!=",
"null",
"&&",
"mMasterVisible",
")",
"{",
"if",
"(",
"event",
".",
"getX",
"(",
")",
">",
"mTranslateAmount",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"super",
".",
"onInterceptTouchEvent",
"(",
"event",
")",
";",
"}",
"@",
"Override",
"public",
"boolean",
"onTouchEvent",
"(",
"MotionEvent",
"event",
")",
"{",
"if",
"(",
"mFlingToExposeMaster",
"&&",
"!",
"mMasterVisible",
"&&",
"mGestureDetector",
".",
"onTouchEvent",
"(",
"event",
")",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"event",
".",
"getAction",
"(",
")",
"==",
"MotionEvent",
".",
"ACTION_DOWN",
"&&",
"mMasterView",
"!=",
"null",
"&&",
"mMasterVisible",
")",
"{",
"if",
"(",
"event",
".",
"getX",
"(",
")",
">",
"mTranslateAmount",
")",
"{",
"showMaster",
"(",
"false",
",",
"0",
")",
";",
"return",
"true",
";",
"}",
"}",
"return",
"super",
".",
"onTouchEvent",
"(",
"event",
")",
";",
"}",
"@",
"Override",
"public",
"void",
"onAnimationStart",
"(",
"Animator",
"animator",
")",
"{",
"}",
"@",
"Override",
"public",
"void",
"onAnimationEnd",
"(",
"Animator",
"animator",
")",
"{",
"mIsAnimating",
"=",
"false",
";",
"mMasterView",
".",
"setLayerType",
"(",
"LAYER_TYPE_NONE",
",",
"null",
")",
";",
"mDetailView",
".",
"setLayerType",
"(",
"LAYER_TYPE_NONE",
",",
"null",
")",
";",
"requestLayout",
"(",
")",
";",
"if",
"(",
"mShowMasterCompleteRunnable",
"!=",
"null",
")",
"{",
"mShowMasterCompleteRunnable",
".",
"run",
"(",
")",
";",
"mShowMasterCompleteRunnable",
"=",
"null",
";",
"}",
"}",
"@",
"Override",
"public",
"void",
"onAnimationCancel",
"(",
"Animator",
"animator",
")",
"{",
"mIsAnimating",
"=",
"false",
";",
"mMasterView",
".",
"setLayerType",
"(",
"LAYER_TYPE_NONE",
",",
"null",
")",
";",
"mDetailView",
".",
"setLayerType",
"(",
"LAYER_TYPE_NONE",
",",
"null",
")",
";",
"requestLayout",
"(",
")",
";",
"if",
"(",
"mShowMasterCompleteRunnable",
"!=",
"null",
")",
"{",
"mShowMasterCompleteRunnable",
".",
"run",
"(",
")",
";",
"mShowMasterCompleteRunnable",
"=",
"null",
";",
"}",
"}",
"@",
"Override",
"public",
"void",
"onAnimationRepeat",
"(",
"Animator",
"animator",
")",
"{",
"}",
"private",
"final",
"GestureDetector",
".",
"OnGestureListener",
"mGestureListener",
"=",
"new",
"GestureDetector",
".",
"SimpleOnGestureListener",
"(",
")",
"{",
"@",
"Override",
"public",
"boolean",
"onDown",
"(",
"MotionEvent",
"e",
")",
"{",
"return",
"true",
";",
"}",
"@",
"Override",
"public",
"boolean",
"onFling",
"(",
"MotionEvent",
"e1",
",",
"MotionEvent",
"e2",
",",
"float",
"velocityX",
",",
"float",
"velocityY",
")",
"{",
"ViewConfiguration",
"viewConfig",
"=",
"ViewConfiguration",
".",
"get",
"(",
"getContext",
"(",
")",
")",
";",
"float",
"absVelocityX",
"=",
"Math",
".",
"abs",
"(",
"velocityX",
")",
";",
"float",
"absVelocityY",
"=",
"Math",
".",
"abs",
"(",
"velocityY",
")",
";",
"if",
"(",
"mFlingToExposeMaster",
"&&",
"!",
"mMasterVisible",
"&&",
"velocityX",
">",
"0",
"&&",
"absVelocityX",
">=",
"absVelocityY",
"&&",
"absVelocityX",
">",
"viewConfig",
".",
"getScaledMinimumFlingVelocity",
"(",
")",
"&&",
"absVelocityX",
"<",
"viewConfig",
".",
"getScaledMaximumFlingVelocity",
"(",
")",
")",
"{",
"showMaster",
"(",
"true",
",",
"0",
")",
";",
"return",
"true",
";",
"}",
"return",
"super",
".",
"onFling",
"(",
"e1",
",",
"e2",
",",
"velocityX",
",",
"velocityY",
")",
";",
"}",
"}",
";",
"}"
] |
A layout that supports the Show/Hide pattern for portrait tablet layouts.
|
[
"A",
"layout",
"that",
"supports",
"the",
"Show",
"/",
"Hide",
"pattern",
"for",
"portrait",
"tablet",
"layouts",
"."
] |
[
"// The last measured master width, including its margins.",
"// Measure once to find the maximum child size.",
"// Account for padding too",
"// Check against our minimum height and width",
"// Set our own measured size",
"// Measure children for them to set their measured dimensions",
"// Update translationX values",
"// Animate if we have Honeycomb APIs, don't animate otherwise",
"// For API level 12+, use this instead:",
"// mMasterView.animate().translationX().setDuration(duration);",
"// mDetailView.animate().translationX(show ? masterWidth : 0).setDuration(duration);",
"// Really bad hack... we really shouldn't do this.",
"//super.requestDisallowInterceptTouchEvent(disallowIntercept);",
"// If the master is visible, touching in the detail area should hide the master.",
"// If the master is visible, touching in the detail area should hide the master.",
"// Fling at least as hard in X as in Y"
] |
[
{
"param": "ViewGroup",
"type": null
},
{
"param": "Animator.AnimatorListener",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "ViewGroup",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "Animator.AnimatorListener",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 19
| 2,720
| 163
|
0e98aa8743ddc6cf6c00b0badb941ae3bbeab601
|
AnomalousMedical/Engine
|
Engine/Behavior/BehaviorObject.cs
|
[
"MIT"
] |
C#
|
BehaviorObject
|
/// <summary>
/// This abstract class allows subclasses to be used as part of behaviors.
/// Classes deriving from this one must provide an empty constructor and a
/// private constructor that takes a LoadInfo object. That must be passed to
/// the BehaviorObject(LoadInfo info) protected constructor. Otherwise the
/// same rules apply to these objects as far as editing and saving is
/// concerned.
/// </summary>
|
This abstract class allows subclasses to be used as part of behaviors.
Classes deriving from this one must provide an empty constructor and a
private constructor that takes a LoadInfo object. That must be passed to
the BehaviorObject(LoadInfo info) protected constructor. Otherwise the
same rules apply to these objects as far as editing and saving is
concerned.
|
[
"This",
"abstract",
"class",
"allows",
"subclasses",
"to",
"be",
"used",
"as",
"part",
"of",
"behaviors",
".",
"Classes",
"deriving",
"from",
"this",
"one",
"must",
"provide",
"an",
"empty",
"constructor",
"and",
"a",
"private",
"constructor",
"that",
"takes",
"a",
"LoadInfo",
"object",
".",
"That",
"must",
"be",
"passed",
"to",
"the",
"BehaviorObject",
"(",
"LoadInfo",
"info",
")",
"protected",
"constructor",
".",
"Otherwise",
"the",
"same",
"rules",
"apply",
"to",
"these",
"objects",
"as",
"far",
"as",
"editing",
"and",
"saving",
"is",
"concerned",
"."
] |
public abstract class BehaviorObject : BehaviorObjectBase
{
[DoNotCopy]
[DoNotSave]
private EditInterface editInterface;
public BehaviorObject()
{
}
public EditInterface getEditInterface(string memberName, MemberScanner scanner)
{
if (editInterface == null)
{
editInterface = ReflectedEditInterface.createEditInterface(this, BehaviorEditMemberScanner.Scanner, memberName + " - " + this.GetType().Name, null);
customizeEditInterface(editInterface);
}
return editInterface;
}
protected virtual void customizeEditInterface(EditInterface editInterface)
{
}
protected BehaviorObject(LoadInfo info)
{
ReflectedSaver.RestoreObject(this, info, BehaviorSaveMemberScanner.Scanner);
}
public void getInfo(SaveInfo info)
{
ReflectedSaver.SaveObject(this, info, BehaviorSaveMemberScanner.Scanner);
customizeSave(info);
}
protected virtual void customizeSave(SaveInfo info)
{
}
}
|
[
"public",
"abstract",
"class",
"BehaviorObject",
":",
"BehaviorObjectBase",
"{",
"[",
"DoNotCopy",
"]",
"[",
"DoNotSave",
"]",
"private",
"EditInterface",
"editInterface",
";",
"public",
"BehaviorObject",
"(",
")",
"{",
"}",
"public",
"EditInterface",
"getEditInterface",
"(",
"string",
"memberName",
",",
"MemberScanner",
"scanner",
")",
"{",
"if",
"(",
"editInterface",
"==",
"null",
")",
"{",
"editInterface",
"=",
"ReflectedEditInterface",
".",
"createEditInterface",
"(",
"this",
",",
"BehaviorEditMemberScanner",
".",
"Scanner",
",",
"memberName",
"+",
"\"",
" - ",
"\"",
"+",
"this",
".",
"GetType",
"(",
")",
".",
"Name",
",",
"null",
")",
";",
"customizeEditInterface",
"(",
"editInterface",
")",
";",
"}",
"return",
"editInterface",
";",
"}",
"protected",
"virtual",
"void",
"customizeEditInterface",
"(",
"EditInterface",
"editInterface",
")",
"{",
"}",
"protected",
"BehaviorObject",
"(",
"LoadInfo",
"info",
")",
"{",
"ReflectedSaver",
".",
"RestoreObject",
"(",
"this",
",",
"info",
",",
"BehaviorSaveMemberScanner",
".",
"Scanner",
")",
";",
"}",
"public",
"void",
"getInfo",
"(",
"SaveInfo",
"info",
")",
"{",
"ReflectedSaver",
".",
"SaveObject",
"(",
"this",
",",
"info",
",",
"BehaviorSaveMemberScanner",
".",
"Scanner",
")",
";",
"customizeSave",
"(",
"info",
")",
";",
"}",
"protected",
"virtual",
"void",
"customizeSave",
"(",
"SaveInfo",
"info",
")",
"{",
"}",
"}"
] |
This abstract class allows subclasses to be used as part of behaviors.
|
[
"This",
"abstract",
"class",
"allows",
"subclasses",
"to",
"be",
"used",
"as",
"part",
"of",
"behaviors",
"."
] |
[
"/// <summary>",
"/// Constructor.",
"/// </summary>",
"/// <summary>",
"/// This function will provide the customized EditInterface for this",
"/// class when it is scanned by the ReflectedEditInterface scanner. If",
"/// it is not scanned with that scanner this function is not",
"/// automatically called.",
"/// </summary>",
"/// <param name=\"memberName\">The name of the member that contains this object.</param>",
"/// <param name=\"scanner\">The MemberScanner used to scan the parent object.</param>",
"/// <returns>A new EditInterface for this class.</returns>",
"/// <summary>",
"/// Add any custom properties to the edit interface.",
"/// </summary>",
"/// <param name=\"editInterface\">The EditInterface to modify.</param>",
"/// <summary>",
"/// Create a new instance using the provided LoadInfo. This must be",
"/// called from any deriving classes.",
"/// </summary>",
"/// <param name=\"info\"></param>",
"/// <summary>",
"/// Get the info to save for the implementing class.",
"/// </summary>",
"/// <param name=\"info\">The SaveInfo class to save into.</param>",
"/// <summary>",
"/// Add any custom properties to the save info.",
"/// </summary>",
"/// <param name=\"info\">The SaveInfo to modify.</param>"
] |
[
{
"param": "BehaviorObjectBase",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "BehaviorObjectBase",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 16
| 215
| 85
|
cb1c7adbbf92654f423cfb76bb37c1e095e460c0
|
JeanOUINA/shards-react
|
components/container/docs/02-layout-explained.js
|
[
"MIT"
] |
JavaScript
|
Example
|
/**
* ## Containers
*
* Containers are the most fundamental and required layout element for your application or website's layout. You can use the `Container` component for a fixed container, and apply the `fluid` prop for a fluid container.
*
* ## Rows
*
* The `Row` component must be placed inside a `Container` component and it's used to define a row of columns. You can also apply the `form` prop onto a `Row` component to turn it into a `form-row` better suited for building form layouts that help you create a layout with more compact margins.
*
* ## Columns
*
* The `Col` component is used to represent a column and must be placed inside a `Row` component.
*/
|
Containers
Containers are the most fundamental and required layout element for your application or website's layout. You can use the `Container` component for a fixed container, and apply the `fluid` prop for a fluid container.
Rows
The `Row` component must be placed inside a `Container` component and it's used to define a row of columns.
Columns
The `Col` component is used to represent a column and must be placed inside a `Row` component.
|
[
"Containers",
"Containers",
"are",
"the",
"most",
"fundamental",
"and",
"required",
"layout",
"element",
"for",
"your",
"application",
"or",
"website",
"'",
"s",
"layout",
".",
"You",
"can",
"use",
"the",
"`",
"Container",
"`",
"component",
"for",
"a",
"fixed",
"container",
"and",
"apply",
"the",
"`",
"fluid",
"`",
"prop",
"for",
"a",
"fluid",
"container",
".",
"Rows",
"The",
"`",
"Row",
"`",
"component",
"must",
"be",
"placed",
"inside",
"a",
"`",
"Container",
"`",
"component",
"and",
"it",
"'",
"s",
"used",
"to",
"define",
"a",
"row",
"of",
"columns",
".",
"Columns",
"The",
"`",
"Col",
"`",
"component",
"is",
"used",
"to",
"represent",
"a",
"column",
"and",
"must",
"be",
"placed",
"inside",
"a",
"`",
"Row",
"`",
"component",
"."
] |
class Example extends React.Component {
render() {
return (
<Container className="dr-example-container">
<Row>
<Col sm="12" lg="6">
sm=12 lg=6
</Col>
<Col sm="12" lg="6">
sm=12 lg=6
</Col>
</Row>
<Row>
<Col sm="12" md="4" lg="3">
sm=12 md=4 lg=3
</Col>
<Col sm="12" md="4" lg="6">
sm=12 md=4 lg=6
</Col>
<Col sm="12" md="4" lg="3">
sm=12 md=4 lg=3
</Col>
</Row>
<Row>
<Col sm={{ size: 8, order: 2, offset: 2 }}>
.col-sm-8 .order-sm-2 .offset-sm-2
</Col>
</Row>
</Container>
);
}
}
|
[
"class",
"Example",
"extends",
"React",
".",
"Component",
"{",
"render",
"(",
")",
"{",
"return",
"(",
"<",
"Container",
"className",
"=",
"\"dr-example-container\"",
">",
"\n ",
"<",
"Row",
">",
"\n ",
"<",
"Col",
"sm",
"=",
"\"12\"",
"lg",
"=",
"\"6\"",
">",
"\n sm=12 lg=6\n ",
"<",
"/",
"Col",
">",
"\n ",
"<",
"Col",
"sm",
"=",
"\"12\"",
"lg",
"=",
"\"6\"",
">",
"\n sm=12 lg=6\n ",
"<",
"/",
"Col",
">",
"\n ",
"<",
"/",
"Row",
">",
"\n\n ",
"<",
"Row",
">",
"\n ",
"<",
"Col",
"sm",
"=",
"\"12\"",
"md",
"=",
"\"4\"",
"lg",
"=",
"\"3\"",
">",
"\n sm=12 md=4 lg=3\n ",
"<",
"/",
"Col",
">",
"\n ",
"<",
"Col",
"sm",
"=",
"\"12\"",
"md",
"=",
"\"4\"",
"lg",
"=",
"\"6\"",
">",
"\n sm=12 md=4 lg=6\n ",
"<",
"/",
"Col",
">",
"\n ",
"<",
"Col",
"sm",
"=",
"\"12\"",
"md",
"=",
"\"4\"",
"lg",
"=",
"\"3\"",
">",
"\n sm=12 md=4 lg=3\n ",
"<",
"/",
"Col",
">",
"\n ",
"<",
"/",
"Row",
">",
"\n\n ",
"<",
"Row",
">",
"\n ",
"<",
"Col",
"sm",
"=",
"{",
"{",
"size",
":",
"8",
",",
"order",
":",
"2",
",",
"offset",
":",
"2",
"}",
"}",
">",
"\n .col-sm-8 .order-sm-2 .offset-sm-2\n ",
"<",
"/",
"Col",
">",
"\n ",
"<",
"/",
"Row",
">",
"\n ",
"<",
"/",
"Container",
">",
")",
";",
"}",
"}"
] |
## Containers
Containers are the most fundamental and required layout element for your application or website's layout.
|
[
"##",
"Containers",
"Containers",
"are",
"the",
"most",
"fundamental",
"and",
"required",
"layout",
"element",
"for",
"your",
"application",
"or",
"website",
"'",
"s",
"layout",
"."
] |
[] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 15
| 242
| 153
|
ad8d32fef29be222a69dfc5d55fa775a4b496bae
|
unitycoder/GoRogue
|
GoRogue/MapGeneration/Connectors/DirectLineTunnelCreator.cs
|
[
"MIT"
] |
C#
|
DirectLineTunnelCreator
|
/// <summary>
/// Implements a tunnel creation algorithm that sets as walkable a direct line between the two
/// points. In the case that MAHNATTAN distance is being used, the line is calculated via the
/// Coord.CardinalPositionOnLine function. Otherwise, the line is calculated using
/// Coord.PositionsOnLine (brensham's).
/// </summary>
|
Implements a tunnel creation algorithm that sets as walkable a direct line between the two
points. In the case that MAHNATTAN distance is being used, the line is calculated via the
Coord.CardinalPositionOnLine function. Otherwise, the line is calculated using
Coord.PositionsOnLine (brensham's).
|
[
"Implements",
"a",
"tunnel",
"creation",
"algorithm",
"that",
"sets",
"as",
"walkable",
"a",
"direct",
"line",
"between",
"the",
"two",
"points",
".",
"In",
"the",
"case",
"that",
"MAHNATTAN",
"distance",
"is",
"being",
"used",
"the",
"line",
"is",
"calculated",
"via",
"the",
"Coord",
".",
"CardinalPositionOnLine",
"function",
".",
"Otherwise",
"the",
"line",
"is",
"calculated",
"using",
"Coord",
".",
"PositionsOnLine",
"(",
"brensham",
"'",
"s",
")",
"."
] |
public class DirectLineTunnelCreator : ITunnelCreator
{
private AdjacencyRule adjacencyRule;
public DirectLineTunnelCreator(AdjacencyRule adjacencyRule)
{
if (adjacencyRule == AdjacencyRule.DIAGONALS) throw new System.ArgumentException("Cannot use diagonal adjacency to create tunnels", nameof(adjacencyRule));
this.adjacencyRule = adjacencyRule;
}
public void CreateTunnel(ISettableMapView<bool> map, Coord start, Coord end)
{
var lineAlgorithm = (adjacencyRule == AdjacencyRule.CARDINALS) ? Lines.Algorithm.ORTHO : Lines.Algorithm.BRESENHAM;
Coord previous = Coord.NONE;
foreach (var pos in Lines.Get(start, end, lineAlgorithm))
{
map[pos] = true;
if (previous != Coord.NONE)
if (pos.Y != previous.Y)
if (pos.X + 1 < map.Width - 1)
map[pos.X + 1, pos.Y] = true;
previous = pos;
}
}
public void CreateTunnel(ISettableMapView<bool> map, int startX, int startY, int endX, int endY) => CreateTunnel(map, new Coord(startX, startY), new Coord(endX, endY));
}
|
[
"public",
"class",
"DirectLineTunnelCreator",
":",
"ITunnelCreator",
"{",
"private",
"AdjacencyRule",
"adjacencyRule",
";",
"public",
"DirectLineTunnelCreator",
"(",
"AdjacencyRule",
"adjacencyRule",
")",
"{",
"if",
"(",
"adjacencyRule",
"==",
"AdjacencyRule",
".",
"DIAGONALS",
")",
"throw",
"new",
"System",
".",
"ArgumentException",
"(",
"\"",
"Cannot use diagonal adjacency to create tunnels",
"\"",
",",
"nameof",
"(",
"adjacencyRule",
")",
")",
";",
"this",
".",
"adjacencyRule",
"=",
"adjacencyRule",
";",
"}",
"public",
"void",
"CreateTunnel",
"(",
"ISettableMapView",
"<",
"bool",
">",
"map",
",",
"Coord",
"start",
",",
"Coord",
"end",
")",
"{",
"var",
"lineAlgorithm",
"=",
"(",
"adjacencyRule",
"==",
"AdjacencyRule",
".",
"CARDINALS",
")",
"?",
"Lines",
".",
"Algorithm",
".",
"ORTHO",
":",
"Lines",
".",
"Algorithm",
".",
"BRESENHAM",
";",
"Coord",
"previous",
"=",
"Coord",
".",
"NONE",
";",
"foreach",
"(",
"var",
"pos",
"in",
"Lines",
".",
"Get",
"(",
"start",
",",
"end",
",",
"lineAlgorithm",
")",
")",
"{",
"map",
"[",
"pos",
"]",
"=",
"true",
";",
"if",
"(",
"previous",
"!=",
"Coord",
".",
"NONE",
")",
"if",
"(",
"pos",
".",
"Y",
"!=",
"previous",
".",
"Y",
")",
"if",
"(",
"pos",
".",
"X",
"+",
"1",
"<",
"map",
".",
"Width",
"-",
"1",
")",
"map",
"[",
"pos",
".",
"X",
"+",
"1",
",",
"pos",
".",
"Y",
"]",
"=",
"true",
";",
"previous",
"=",
"pos",
";",
"}",
"}",
"public",
"void",
"CreateTunnel",
"(",
"ISettableMapView",
"<",
"bool",
">",
"map",
",",
"int",
"startX",
",",
"int",
"startY",
",",
"int",
"endX",
",",
"int",
"endY",
")",
"=>",
"CreateTunnel",
"(",
"map",
",",
"new",
"Coord",
"(",
"startX",
",",
"startY",
")",
",",
"new",
"Coord",
"(",
"endX",
",",
"endY",
")",
")",
";",
"}"
] |
Implements a tunnel creation algorithm that sets as walkable a direct line between the two
points.
|
[
"Implements",
"a",
"tunnel",
"creation",
"algorithm",
"that",
"sets",
"as",
"walkable",
"a",
"direct",
"line",
"between",
"the",
"two",
"points",
"."
] |
[
"/// <summary>",
"/// Constructor. Takes the distance calculation to use, which determines whether brensham's",
"/// or CardinalPositionOnLine is used to create the tunnel.",
"/// </summary>",
"/// <param name=\"adjacencyRule\">",
"/// Method of adjacency to respect when creating tunnels. Cannot be diagonal.",
"/// </param>",
"/// <summary>",
"/// Implements the algorithm, creating the tunnel as specified in the class description.",
"/// </summary>",
"/// <param name=\"map\">The map to create the tunnel on.</param>",
"/// <param name=\"start\">Start coordinate of the tunnel.</param>",
"/// <param name=\"end\">End coordinate of the tunnel.</param>",
"// Previous cell, and we're going vertical, go 2 wide so it looks nicer Make sure not",
"// to break rectangles (less than last index)!",
"// TODO: Make double wide vert an option",
"/// <summary>",
"/// Implements the algorithm, creating the tunnel as specified in the class description.",
"/// </summary>",
"/// <param name=\"map\">The map to create the tunnel on.</param>",
"/// <param name=\"startX\">X-value of the start position of the tunnel.</param>",
"/// <param name=\"startY\">Y-value of the start position of the tunnel.</param>",
"/// <param name=\"endX\">X-value of the end position of the tunnel.</param>",
"/// <param name=\"endY\">Y-value of the end position of the tunnel.</param>"
] |
[
{
"param": "ITunnelCreator",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "ITunnelCreator",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 17
| 285
| 79
|
d386edf5db78c1764502664232be63bc02284069
|
heyProto/PROTOGraph
|
app/models/feed_link.rb
|
[
"MIT"
] |
Ruby
|
FeedLink
|
# == Schema Information
#
# Table name: feed_links
#
# id :integer not null, primary key
# ref_category_id :integer
# feed_id :integer
# view_cast_id :integer
# link :text
# headline :text
# published_at :datetime
# description :text
# cover_image :text
# author :string(255)
# created_at :datetime not null
# updated_at :datetime not null
#
|
Schema Information
Table name: feed_links
|
[
"Schema",
"Information",
"Table",
"name",
":",
"feed_links"
] |
class FeedLink < ApplicationRecord
#CONSTANTS
#CUSTOM TABLES
#GEMS
#CONCERNS
#ASSOCIATIONS
belongs_to :ref_category
belongs_to :feed
has_one :view_cast, class_name: "ViewCast", foreign_key: "id", primary_key: "view_cast_id" #, dependent: :destroy
#ACCESSORS
attr_accessor :temp_headline
#VALIDATIONS
validates :link, presence: true, format: {:with => /[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]\.[a-zA-Z]{2,}/ }
validates :ref_category_id, presence: true
validates :feed_id, presence: true
#CALLBACKS
#SCOPE
#OTHER
def create_or_update_view_cast
ref_category = self.ref_category
feed = self.feed
payload_json = create_datacast_json
if self.view_cast.present?
view_cast = self.view_cast
view_cast.update({
name: self.temp_headline || self.headline,
seo_blockquote: TemplateCard.to_cluster_render_SEO(payload_json["data"]),
folder_id: ref_category.folder.present? ? ref_category.folder.id : nil,
is_autogenerated: true,
optionalconfigjson: {},
updated_by: feed.updated_by,
published_at: self.published_at,
data_json: create_datacast_json
})
else
view_cast = ViewCast.create({
name: self.temp_headline || self.headline,
site_id: ref_category.site.id,
template_card_id: TemplateCard.where(name: 'toCluster').first.id,
template_datum_id: TemplateDatum.where(name: 'toCluster').first.id,
seo_blockquote: TemplateCard.to_cluster_render_SEO(payload_json["data"]),
folder_id: ref_category.folder.present? ? ref_category.folder.id : nil,
default_view: "title_text",
created_by: feed.created_by,
updated_by: feed.updated_by,
is_autogenerated: true,
optionalconfigjson: {},
published_at: self.published_at,
data_json: create_datacast_json
})
end
payload = {}
payload["payload"] = payload_json.to_json
payload["api_slug"] = view_cast.datacast_identifier
payload["schema_url"] = view_cast.template_datum.schema_json
payload["source"] = "form"
payload["bucket_name"] = ref_category.site.cdn_bucket
if self.view_cast.present?
r = Api::ProtoGraph::Datacast.update(payload)
else
r = Api::ProtoGraph::Datacast.create(payload)
self.update_column(:view_cast_id, view_cast.id)
add_card_to_stream
end
Api::ProtoGraph::CloudFront.invalidate(self.ref_category.site, ["/#{view_cast.datacast_identifier}/*"], 1)
end
def create_datacast_json
require 'uri'
data = {"data" => {}}
data["data"]["section"] = self.temp_headline || self.headline
data["data"]["title"] = self.temp_headline || self.headline
data["data"]["published_date"] = self.published_at.utc
data["data"]["links"] = []
data["data"]["links"][0] = {}
data["data"]["links"][0]["link"] = self.link if self.link.present?
parsed_link = URI.parse(self.link)
link = "#{parsed_link.scheme}://#{parsed_link.host}"
data["data"]["links"][0]["favicon_url"] = "https://utils.pro.to/lib/toCluster_default_favicon.png"
data["data"]["links"][0]["publication_name"] = parsed_link.host
data
end
def add_card_to_stream
page = self.ref_category.vertical_page #self.ref_category.pages.where(template_page_id: TemplatePage.find_by(name: "Homepage: Vertical").id).first
if page.present?
feed_stream = page.streams.where(title: "#{page.id}_Section_3c").first
if feed_stream.present?
s = StreamEntity.create({
"entity_value": "#{self.view_cast_id}",
"entity_type": "view_cast_id",
"stream_id": feed_stream.id,
"is_excluded": false
})
feed_stream.reload
feed_stream.publish_cards
feed_stream.publish_rss
end
end
true
end
#PRIVATE
private
end
|
[
"class",
"FeedLink",
"<",
"ApplicationRecord",
"belongs_to",
":ref_category",
"belongs_to",
":feed",
"has_one",
":view_cast",
",",
"class_name",
":",
"\"ViewCast\"",
",",
"foreign_key",
":",
"\"id\"",
",",
"primary_key",
":",
"\"view_cast_id\"",
"attr_accessor",
":temp_headline",
"validates",
":link",
",",
"presence",
":",
"true",
",",
"format",
":",
"{",
":with",
"=>",
"/",
"[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]",
"\\.",
"[a-zA-Z]{2,}",
"/",
"}",
"validates",
":ref_category_id",
",",
"presence",
":",
"true",
"validates",
":feed_id",
",",
"presence",
":",
"true",
"def",
"create_or_update_view_cast",
"ref_category",
"=",
"self",
".",
"ref_category",
"feed",
"=",
"self",
".",
"feed",
"payload_json",
"=",
"create_datacast_json",
"if",
"self",
".",
"view_cast",
".",
"present?",
"view_cast",
"=",
"self",
".",
"view_cast",
"view_cast",
".",
"update",
"(",
"{",
"name",
":",
"self",
".",
"temp_headline",
"||",
"self",
".",
"headline",
",",
"seo_blockquote",
":",
"TemplateCard",
".",
"to_cluster_render_SEO",
"(",
"payload_json",
"[",
"\"data\"",
"]",
")",
",",
"folder_id",
":",
"ref_category",
".",
"folder",
".",
"present?",
"?",
"ref_category",
".",
"folder",
".",
"id",
":",
"nil",
",",
"is_autogenerated",
":",
"true",
",",
"optionalconfigjson",
":",
"{",
"}",
",",
"updated_by",
":",
"feed",
".",
"updated_by",
",",
"published_at",
":",
"self",
".",
"published_at",
",",
"data_json",
":",
"create_datacast_json",
"}",
")",
"else",
"view_cast",
"=",
"ViewCast",
".",
"create",
"(",
"{",
"name",
":",
"self",
".",
"temp_headline",
"||",
"self",
".",
"headline",
",",
"site_id",
":",
"ref_category",
".",
"site",
".",
"id",
",",
"template_card_id",
":",
"TemplateCard",
".",
"where",
"(",
"name",
":",
"'toCluster'",
")",
".",
"first",
".",
"id",
",",
"template_datum_id",
":",
"TemplateDatum",
".",
"where",
"(",
"name",
":",
"'toCluster'",
")",
".",
"first",
".",
"id",
",",
"seo_blockquote",
":",
"TemplateCard",
".",
"to_cluster_render_SEO",
"(",
"payload_json",
"[",
"\"data\"",
"]",
")",
",",
"folder_id",
":",
"ref_category",
".",
"folder",
".",
"present?",
"?",
"ref_category",
".",
"folder",
".",
"id",
":",
"nil",
",",
"default_view",
":",
"\"title_text\"",
",",
"created_by",
":",
"feed",
".",
"created_by",
",",
"updated_by",
":",
"feed",
".",
"updated_by",
",",
"is_autogenerated",
":",
"true",
",",
"optionalconfigjson",
":",
"{",
"}",
",",
"published_at",
":",
"self",
".",
"published_at",
",",
"data_json",
":",
"create_datacast_json",
"}",
")",
"end",
"payload",
"=",
"{",
"}",
"payload",
"[",
"\"payload\"",
"]",
"=",
"payload_json",
".",
"to_json",
"payload",
"[",
"\"api_slug\"",
"]",
"=",
"view_cast",
".",
"datacast_identifier",
"payload",
"[",
"\"schema_url\"",
"]",
"=",
"view_cast",
".",
"template_datum",
".",
"schema_json",
"payload",
"[",
"\"source\"",
"]",
"=",
"\"form\"",
"payload",
"[",
"\"bucket_name\"",
"]",
"=",
"ref_category",
".",
"site",
".",
"cdn_bucket",
"if",
"self",
".",
"view_cast",
".",
"present?",
"r",
"=",
"Api",
"::",
"ProtoGraph",
"::",
"Datacast",
".",
"update",
"(",
"payload",
")",
"else",
"r",
"=",
"Api",
"::",
"ProtoGraph",
"::",
"Datacast",
".",
"create",
"(",
"payload",
")",
"self",
".",
"update_column",
"(",
":view_cast_id",
",",
"view_cast",
".",
"id",
")",
"add_card_to_stream",
"end",
"Api",
"::",
"ProtoGraph",
"::",
"CloudFront",
".",
"invalidate",
"(",
"self",
".",
"ref_category",
".",
"site",
",",
"[",
"\"/#{view_cast.datacast_identifier}/*\"",
"]",
",",
"1",
")",
"end",
"def",
"create_datacast_json",
"require",
"'uri'",
"data",
"=",
"{",
"\"data\"",
"=>",
"{",
"}",
"}",
"data",
"[",
"\"data\"",
"]",
"[",
"\"section\"",
"]",
"=",
"self",
".",
"temp_headline",
"||",
"self",
".",
"headline",
"data",
"[",
"\"data\"",
"]",
"[",
"\"title\"",
"]",
"=",
"self",
".",
"temp_headline",
"||",
"self",
".",
"headline",
"data",
"[",
"\"data\"",
"]",
"[",
"\"published_date\"",
"]",
"=",
"self",
".",
"published_at",
".",
"utc",
"data",
"[",
"\"data\"",
"]",
"[",
"\"links\"",
"]",
"=",
"[",
"]",
"data",
"[",
"\"data\"",
"]",
"[",
"\"links\"",
"]",
"[",
"0",
"]",
"=",
"{",
"}",
"data",
"[",
"\"data\"",
"]",
"[",
"\"links\"",
"]",
"[",
"0",
"]",
"[",
"\"link\"",
"]",
"=",
"self",
".",
"link",
"if",
"self",
".",
"link",
".",
"present?",
"parsed_link",
"=",
"URI",
".",
"parse",
"(",
"self",
".",
"link",
")",
"link",
"=",
"\"#{parsed_link.scheme}://#{parsed_link.host}\"",
"data",
"[",
"\"data\"",
"]",
"[",
"\"links\"",
"]",
"[",
"0",
"]",
"[",
"\"favicon_url\"",
"]",
"=",
"\"https://utils.pro.to/lib/toCluster_default_favicon.png\"",
"data",
"[",
"\"data\"",
"]",
"[",
"\"links\"",
"]",
"[",
"0",
"]",
"[",
"\"publication_name\"",
"]",
"=",
"parsed_link",
".",
"host",
"data",
"end",
"def",
"add_card_to_stream",
"page",
"=",
"self",
".",
"ref_category",
".",
"vertical_page",
"if",
"page",
".",
"present?",
"feed_stream",
"=",
"page",
".",
"streams",
".",
"where",
"(",
"title",
":",
"\"#{page.id}_Section_3c\"",
")",
".",
"first",
"if",
"feed_stream",
".",
"present?",
"s",
"=",
"StreamEntity",
".",
"create",
"(",
"{",
"\"entity_value\"",
":",
"\"#{self.view_cast_id}\"",
",",
"\"entity_type\"",
":",
"\"view_cast_id\"",
",",
"\"stream_id\"",
":",
"feed_stream",
".",
"id",
",",
"\"is_excluded\"",
":",
"false",
"}",
")",
"feed_stream",
".",
"reload",
"feed_stream",
".",
"publish_cards",
"feed_stream",
".",
"publish_rss",
"end",
"end",
"true",
"end",
"private",
"end"
] |
Schema Information
Table name: feed_links
|
[
"Schema",
"Information",
"Table",
"name",
":",
"feed_links"
] |
[
"#CONSTANTS",
"#CUSTOM TABLES",
"#GEMS",
"#CONCERNS",
"#ASSOCIATIONS",
"#, dependent: :destroy",
"#ACCESSORS",
"#VALIDATIONS",
"#CALLBACKS",
"#SCOPE",
"#OTHER",
"#self.ref_category.pages.where(template_page_id: TemplatePage.find_by(name: \"Homepage: Vertical\").id).first",
"#PRIVATE"
] |
[
{
"param": "ApplicationRecord",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "ApplicationRecord",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 18
| 978
| 123
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.