id
int32 0
58k
| repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
list | docstring
stringlengths 4
11.8k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 86
226
|
---|---|---|---|---|---|---|---|---|---|---|---|
38,100 |
byron-dupreez/aws-core-utils
|
dynamodb-utils.js
|
toValueFromAttributeValue
|
function toValueFromAttributeValue(attributeValue) {
if (!attributeValue || typeof attributeValue !== 'object') {
return attributeValue;
}
const values = Object.getOwnPropertyNames(attributeValue).map(type => {
return toValueFromAttributeTypeAndValue(type, attributeValue[type])
});
if (values.length !== 1) {
throw new Error(`Found ${values.length} values on DynamoDB AttributeValue (${stringify(attributeValue)}), but expected only one!`);
}
return values[0];
}
|
javascript
|
function toValueFromAttributeValue(attributeValue) {
if (!attributeValue || typeof attributeValue !== 'object') {
return attributeValue;
}
const values = Object.getOwnPropertyNames(attributeValue).map(type => {
return toValueFromAttributeTypeAndValue(type, attributeValue[type])
});
if (values.length !== 1) {
throw new Error(`Found ${values.length} values on DynamoDB AttributeValue (${stringify(attributeValue)}), but expected only one!`);
}
return values[0];
}
|
[
"function",
"toValueFromAttributeValue",
"(",
"attributeValue",
")",
"{",
"if",
"(",
"!",
"attributeValue",
"||",
"typeof",
"attributeValue",
"!==",
"'object'",
")",
"{",
"return",
"attributeValue",
";",
"}",
"const",
"values",
"=",
"Object",
".",
"getOwnPropertyNames",
"(",
"attributeValue",
")",
".",
"map",
"(",
"type",
"=>",
"{",
"return",
"toValueFromAttributeTypeAndValue",
"(",
"type",
",",
"attributeValue",
"[",
"type",
"]",
")",
"}",
")",
";",
"if",
"(",
"values",
".",
"length",
"!==",
"1",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"values",
".",
"length",
"}",
"${",
"stringify",
"(",
"attributeValue",
")",
"}",
"`",
")",
";",
"}",
"return",
"values",
"[",
"0",
"]",
";",
"}"
] |
Attempts to convert the given DynamoDB AttributeValue object into its equivalent JavaScript value.
@param {Object} attributeValue - a DynamoDB AttributeValue object
@returns {*} a JavaScript value
|
[
"Attempts",
"to",
"convert",
"the",
"given",
"DynamoDB",
"AttributeValue",
"object",
"into",
"its",
"equivalent",
"JavaScript",
"value",
"."
] |
2530155b5afc102f61658b28183a16027ecae86a
|
https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/dynamodb-utils.js#L56-L67
|
38,101 |
byron-dupreez/aws-core-utils
|
dynamodb-utils.js
|
toValueFromAttributeTypeAndValue
|
function toValueFromAttributeTypeAndValue(attributeType, value) {
switch (attributeType) {
case 'S':
return value;
case 'N':
return toNumberOrIntegerLike(value);
case 'BOOL':
return value === true || value === 'true';
case 'NULL':
return null;
case 'M':
return toObjectFromDynamoDBMap(value);
case 'L':
return value.map(v => toValueFromAttributeValue(v));
case 'SS':
return value;
case 'NS':
return value.map(v => toNumberOrIntegerLike(v));
case 'B':
case 'BS':
return value;
default:
throw new Error(`Unexpected DynamoDB attribute value type (${attributeType})`);
}
}
|
javascript
|
function toValueFromAttributeTypeAndValue(attributeType, value) {
switch (attributeType) {
case 'S':
return value;
case 'N':
return toNumberOrIntegerLike(value);
case 'BOOL':
return value === true || value === 'true';
case 'NULL':
return null;
case 'M':
return toObjectFromDynamoDBMap(value);
case 'L':
return value.map(v => toValueFromAttributeValue(v));
case 'SS':
return value;
case 'NS':
return value.map(v => toNumberOrIntegerLike(v));
case 'B':
case 'BS':
return value;
default:
throw new Error(`Unexpected DynamoDB attribute value type (${attributeType})`);
}
}
|
[
"function",
"toValueFromAttributeTypeAndValue",
"(",
"attributeType",
",",
"value",
")",
"{",
"switch",
"(",
"attributeType",
")",
"{",
"case",
"'S'",
":",
"return",
"value",
";",
"case",
"'N'",
":",
"return",
"toNumberOrIntegerLike",
"(",
"value",
")",
";",
"case",
"'BOOL'",
":",
"return",
"value",
"===",
"true",
"||",
"value",
"===",
"'true'",
";",
"case",
"'NULL'",
":",
"return",
"null",
";",
"case",
"'M'",
":",
"return",
"toObjectFromDynamoDBMap",
"(",
"value",
")",
";",
"case",
"'L'",
":",
"return",
"value",
".",
"map",
"(",
"v",
"=>",
"toValueFromAttributeValue",
"(",
"v",
")",
")",
";",
"case",
"'SS'",
":",
"return",
"value",
";",
"case",
"'NS'",
":",
"return",
"value",
".",
"map",
"(",
"v",
"=>",
"toNumberOrIntegerLike",
"(",
"v",
")",
")",
";",
"case",
"'B'",
":",
"case",
"'BS'",
":",
"return",
"value",
";",
"default",
":",
"throw",
"new",
"Error",
"(",
"`",
"${",
"attributeType",
"}",
"`",
")",
";",
"}",
"}"
] |
Attempts to convert the given DynamoDB AttributeValue value into its original type based on the given DynamoDB
AttributeValue type.
@param {string} attributeType - a DynamoDB AttributeValue type
@param {*} value - a DynamoDB AttributeValue value
@returns {*} a JavaScript value
|
[
"Attempts",
"to",
"convert",
"the",
"given",
"DynamoDB",
"AttributeValue",
"value",
"into",
"its",
"original",
"type",
"based",
"on",
"the",
"given",
"DynamoDB",
"AttributeValue",
"type",
"."
] |
2530155b5afc102f61658b28183a16027ecae86a
|
https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/dynamodb-utils.js#L76-L100
|
38,102 |
byron-dupreez/aws-core-utils
|
dynamodb-utils.js
|
toKeyValueStrings
|
function toKeyValueStrings(dynamoDBMap) {
return dynamoDBMap && typeof dynamoDBMap === 'object' ?
Object.getOwnPropertyNames(dynamoDBMap).map(key => `${key}:${stringify(toValueFromAttributeValue(dynamoDBMap[key]))}`) : [];
}
|
javascript
|
function toKeyValueStrings(dynamoDBMap) {
return dynamoDBMap && typeof dynamoDBMap === 'object' ?
Object.getOwnPropertyNames(dynamoDBMap).map(key => `${key}:${stringify(toValueFromAttributeValue(dynamoDBMap[key]))}`) : [];
}
|
[
"function",
"toKeyValueStrings",
"(",
"dynamoDBMap",
")",
"{",
"return",
"dynamoDBMap",
"&&",
"typeof",
"dynamoDBMap",
"===",
"'object'",
"?",
"Object",
".",
"getOwnPropertyNames",
"(",
"dynamoDBMap",
")",
".",
"map",
"(",
"key",
"=>",
"`",
"${",
"key",
"}",
"${",
"stringify",
"(",
"toValueFromAttributeValue",
"(",
"dynamoDBMap",
"[",
"key",
"]",
")",
")",
"}",
"`",
")",
":",
"[",
"]",
";",
"}"
] |
Extracts an array of colon-separated key name and value strings from the given DynamoDB map object.
@param {Object} dynamoDBMap - a DynamoDB map object
@returns {string[]} an array of colon-separated key name and value strings
|
[
"Extracts",
"an",
"array",
"of",
"colon",
"-",
"separated",
"key",
"name",
"and",
"value",
"strings",
"from",
"the",
"given",
"DynamoDB",
"map",
"object",
"."
] |
2530155b5afc102f61658b28183a16027ecae86a
|
https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/dynamodb-utils.js#L107-L110
|
38,103 |
byron-dupreez/aws-core-utils
|
dynamodb-utils.js
|
toKeyValuePairs
|
function toKeyValuePairs(dynamoDBMap) {
return dynamoDBMap && typeof dynamoDBMap === 'object' ?
Object.getOwnPropertyNames(dynamoDBMap).map(key => [key, toValueFromAttributeValue(dynamoDBMap[key])]) : [];
}
|
javascript
|
function toKeyValuePairs(dynamoDBMap) {
return dynamoDBMap && typeof dynamoDBMap === 'object' ?
Object.getOwnPropertyNames(dynamoDBMap).map(key => [key, toValueFromAttributeValue(dynamoDBMap[key])]) : [];
}
|
[
"function",
"toKeyValuePairs",
"(",
"dynamoDBMap",
")",
"{",
"return",
"dynamoDBMap",
"&&",
"typeof",
"dynamoDBMap",
"===",
"'object'",
"?",
"Object",
".",
"getOwnPropertyNames",
"(",
"dynamoDBMap",
")",
".",
"map",
"(",
"key",
"=>",
"[",
"key",
",",
"toValueFromAttributeValue",
"(",
"dynamoDBMap",
"[",
"key",
"]",
")",
"]",
")",
":",
"[",
"]",
";",
"}"
] |
Extracts an array of key value pairs from the given DynamoDB map object. Each key value pair is represented as an
array containing a key property name followed by its associated value.
@param {Object} dynamoDBMap - a DynamoDB map object
@returns {KeyValuePair[]} an array of key value pairs
|
[
"Extracts",
"an",
"array",
"of",
"key",
"value",
"pairs",
"from",
"the",
"given",
"DynamoDB",
"map",
"object",
".",
"Each",
"key",
"value",
"pair",
"is",
"represented",
"as",
"an",
"array",
"containing",
"a",
"key",
"property",
"name",
"followed",
"by",
"its",
"associated",
"value",
"."
] |
2530155b5afc102f61658b28183a16027ecae86a
|
https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/dynamodb-utils.js#L118-L121
|
38,104 |
gegeyang0124/react-native-navigation-cus
|
src/views/CardStack/CardStackStyleInterpolator.js
|
forInitial
|
function forInitial(props) {
const { navigation, scene } = props;
const focused = navigation.state.index === scene.index;
const opacity = focused ? 1 : 0;
// If not focused, move the scene far away.
const translate = focused ? 0 : 1000000;
return {
opacity,
transform: [{ translateX: translate }, { translateY: translate }],
};
}
|
javascript
|
function forInitial(props) {
const { navigation, scene } = props;
const focused = navigation.state.index === scene.index;
const opacity = focused ? 1 : 0;
// If not focused, move the scene far away.
const translate = focused ? 0 : 1000000;
return {
opacity,
transform: [{ translateX: translate }, { translateY: translate }],
};
}
|
[
"function",
"forInitial",
"(",
"props",
")",
"{",
"const",
"{",
"navigation",
",",
"scene",
"}",
"=",
"props",
";",
"const",
"focused",
"=",
"navigation",
".",
"state",
".",
"index",
"===",
"scene",
".",
"index",
";",
"const",
"opacity",
"=",
"focused",
"?",
"1",
":",
"0",
";",
"// If not focused, move the scene far away.",
"const",
"translate",
"=",
"focused",
"?",
"0",
":",
"1000000",
";",
"return",
"{",
"opacity",
",",
"transform",
":",
"[",
"{",
"translateX",
":",
"translate",
"}",
",",
"{",
"translateY",
":",
"translate",
"}",
"]",
",",
"}",
";",
"}"
] |
Utility that builds the style for the card in the cards stack.
+------------+
+-+ |
+-+ | |
| | | |
| | | Focused |
| | | Card |
| | | |
+-+ | |
+-+ |
+------------+
Render the initial style when the initial layout isn't measured yet.
|
[
"Utility",
"that",
"builds",
"the",
"style",
"for",
"the",
"card",
"in",
"the",
"cards",
"stack",
"."
] |
37bf130e0a459ed8f8671ebf87efcb425aaeb775
|
https://github.com/gegeyang0124/react-native-navigation-cus/blob/37bf130e0a459ed8f8671ebf87efcb425aaeb775/src/views/CardStack/CardStackStyleInterpolator.js#L22-L33
|
38,105 |
gegeyang0124/react-native-navigation-cus
|
src/views/CardStack/CardStackStyleInterpolator.js
|
forHorizontal
|
function forHorizontal(props) {
const { layout, position, scene } = props;
if (!layout.isMeasured) {
return forInitial(props);
}
const interpolate = getSceneIndicesForInterpolationInputRange(props);
if (!interpolate) return { opacity: 0 };
const { first, last } = interpolate;
const index = scene.index;
const opacity = position.interpolate({
inputRange: [first, first + 0.01, index, last - 0.01, last],
outputRange: [0, 1, 1, 0.85, 0],
});
const width = layout.initWidth;
const translateX = position.interpolate({
inputRange: [first, index, last],
outputRange: I18nManager.isRTL
? [-width, 0, width * 0.3]
: [width, 0, width * -0.3],
});
const translateY = 0;
return {
opacity,
transform: [{ translateX }, { translateY }],
};
}
|
javascript
|
function forHorizontal(props) {
const { layout, position, scene } = props;
if (!layout.isMeasured) {
return forInitial(props);
}
const interpolate = getSceneIndicesForInterpolationInputRange(props);
if (!interpolate) return { opacity: 0 };
const { first, last } = interpolate;
const index = scene.index;
const opacity = position.interpolate({
inputRange: [first, first + 0.01, index, last - 0.01, last],
outputRange: [0, 1, 1, 0.85, 0],
});
const width = layout.initWidth;
const translateX = position.interpolate({
inputRange: [first, index, last],
outputRange: I18nManager.isRTL
? [-width, 0, width * 0.3]
: [width, 0, width * -0.3],
});
const translateY = 0;
return {
opacity,
transform: [{ translateX }, { translateY }],
};
}
|
[
"function",
"forHorizontal",
"(",
"props",
")",
"{",
"const",
"{",
"layout",
",",
"position",
",",
"scene",
"}",
"=",
"props",
";",
"if",
"(",
"!",
"layout",
".",
"isMeasured",
")",
"{",
"return",
"forInitial",
"(",
"props",
")",
";",
"}",
"const",
"interpolate",
"=",
"getSceneIndicesForInterpolationInputRange",
"(",
"props",
")",
";",
"if",
"(",
"!",
"interpolate",
")",
"return",
"{",
"opacity",
":",
"0",
"}",
";",
"const",
"{",
"first",
",",
"last",
"}",
"=",
"interpolate",
";",
"const",
"index",
"=",
"scene",
".",
"index",
";",
"const",
"opacity",
"=",
"position",
".",
"interpolate",
"(",
"{",
"inputRange",
":",
"[",
"first",
",",
"first",
"+",
"0.01",
",",
"index",
",",
"last",
"-",
"0.01",
",",
"last",
"]",
",",
"outputRange",
":",
"[",
"0",
",",
"1",
",",
"1",
",",
"0.85",
",",
"0",
"]",
",",
"}",
")",
";",
"const",
"width",
"=",
"layout",
".",
"initWidth",
";",
"const",
"translateX",
"=",
"position",
".",
"interpolate",
"(",
"{",
"inputRange",
":",
"[",
"first",
",",
"index",
",",
"last",
"]",
",",
"outputRange",
":",
"I18nManager",
".",
"isRTL",
"?",
"[",
"-",
"width",
",",
"0",
",",
"width",
"*",
"0.3",
"]",
":",
"[",
"width",
",",
"0",
",",
"width",
"*",
"-",
"0.3",
"]",
",",
"}",
")",
";",
"const",
"translateY",
"=",
"0",
";",
"return",
"{",
"opacity",
",",
"transform",
":",
"[",
"{",
"translateX",
"}",
",",
"{",
"translateY",
"}",
"]",
",",
"}",
";",
"}"
] |
Standard iOS-style slide in from the right.
|
[
"Standard",
"iOS",
"-",
"style",
"slide",
"in",
"from",
"the",
"right",
"."
] |
37bf130e0a459ed8f8671ebf87efcb425aaeb775
|
https://github.com/gegeyang0124/react-native-navigation-cus/blob/37bf130e0a459ed8f8671ebf87efcb425aaeb775/src/views/CardStack/CardStackStyleInterpolator.js#L38-L68
|
38,106 |
gegeyang0124/react-native-navigation-cus
|
src/views/CardStack/CardStackStyleInterpolator.js
|
forFadeFromBottomAndroid
|
function forFadeFromBottomAndroid(props) {
const { layout, position, scene } = props;
if (!layout.isMeasured) {
return forInitial(props);
}
const interpolate = getSceneIndicesForInterpolationInputRange(props);
if (!interpolate) return { opacity: 0 };
const { first, last } = interpolate;
const index = scene.index;
const inputRange = [first, index, last - 0.01, last];
const opacity = position.interpolate({
inputRange,
outputRange: [0, 1, 1, 0],
});
const translateY = position.interpolate({
inputRange,
outputRange: [50, 0, 0, 0],
});
const translateX = 0;
return {
opacity,
transform: [{ translateX }, { translateY }],
};
}
|
javascript
|
function forFadeFromBottomAndroid(props) {
const { layout, position, scene } = props;
if (!layout.isMeasured) {
return forInitial(props);
}
const interpolate = getSceneIndicesForInterpolationInputRange(props);
if (!interpolate) return { opacity: 0 };
const { first, last } = interpolate;
const index = scene.index;
const inputRange = [first, index, last - 0.01, last];
const opacity = position.interpolate({
inputRange,
outputRange: [0, 1, 1, 0],
});
const translateY = position.interpolate({
inputRange,
outputRange: [50, 0, 0, 0],
});
const translateX = 0;
return {
opacity,
transform: [{ translateX }, { translateY }],
};
}
|
[
"function",
"forFadeFromBottomAndroid",
"(",
"props",
")",
"{",
"const",
"{",
"layout",
",",
"position",
",",
"scene",
"}",
"=",
"props",
";",
"if",
"(",
"!",
"layout",
".",
"isMeasured",
")",
"{",
"return",
"forInitial",
"(",
"props",
")",
";",
"}",
"const",
"interpolate",
"=",
"getSceneIndicesForInterpolationInputRange",
"(",
"props",
")",
";",
"if",
"(",
"!",
"interpolate",
")",
"return",
"{",
"opacity",
":",
"0",
"}",
";",
"const",
"{",
"first",
",",
"last",
"}",
"=",
"interpolate",
";",
"const",
"index",
"=",
"scene",
".",
"index",
";",
"const",
"inputRange",
"=",
"[",
"first",
",",
"index",
",",
"last",
"-",
"0.01",
",",
"last",
"]",
";",
"const",
"opacity",
"=",
"position",
".",
"interpolate",
"(",
"{",
"inputRange",
",",
"outputRange",
":",
"[",
"0",
",",
"1",
",",
"1",
",",
"0",
"]",
",",
"}",
")",
";",
"const",
"translateY",
"=",
"position",
".",
"interpolate",
"(",
"{",
"inputRange",
",",
"outputRange",
":",
"[",
"50",
",",
"0",
",",
"0",
",",
"0",
"]",
",",
"}",
")",
";",
"const",
"translateX",
"=",
"0",
";",
"return",
"{",
"opacity",
",",
"transform",
":",
"[",
"{",
"translateX",
"}",
",",
"{",
"translateY",
"}",
"]",
",",
"}",
";",
"}"
] |
Standard Android-style fade in from the bottom.
|
[
"Standard",
"Android",
"-",
"style",
"fade",
"in",
"from",
"the",
"bottom",
"."
] |
37bf130e0a459ed8f8671ebf87efcb425aaeb775
|
https://github.com/gegeyang0124/react-native-navigation-cus/blob/37bf130e0a459ed8f8671ebf87efcb425aaeb775/src/views/CardStack/CardStackStyleInterpolator.js#L106-L135
|
38,107 |
gegeyang0124/react-native-navigation-cus
|
src/views/CardStack/CardStackStyleInterpolator.js
|
forFade
|
function forFade(props) {
const { layout, position, scene } = props;
if (!layout.isMeasured) {
return forInitial(props);
}
const interpolate = getSceneIndicesForInterpolationInputRange(props);
if (!interpolate) return { opacity: 0 };
const { first, last } = interpolate;
const index = scene.index;
const opacity = position.interpolate({
inputRange: [first, index, last],
outputRange: [0, 1, 1],
});
return {
opacity,
};
}
|
javascript
|
function forFade(props) {
const { layout, position, scene } = props;
if (!layout.isMeasured) {
return forInitial(props);
}
const interpolate = getSceneIndicesForInterpolationInputRange(props);
if (!interpolate) return { opacity: 0 };
const { first, last } = interpolate;
const index = scene.index;
const opacity = position.interpolate({
inputRange: [first, index, last],
outputRange: [0, 1, 1],
});
return {
opacity,
};
}
|
[
"function",
"forFade",
"(",
"props",
")",
"{",
"const",
"{",
"layout",
",",
"position",
",",
"scene",
"}",
"=",
"props",
";",
"if",
"(",
"!",
"layout",
".",
"isMeasured",
")",
"{",
"return",
"forInitial",
"(",
"props",
")",
";",
"}",
"const",
"interpolate",
"=",
"getSceneIndicesForInterpolationInputRange",
"(",
"props",
")",
";",
"if",
"(",
"!",
"interpolate",
")",
"return",
"{",
"opacity",
":",
"0",
"}",
";",
"const",
"{",
"first",
",",
"last",
"}",
"=",
"interpolate",
";",
"const",
"index",
"=",
"scene",
".",
"index",
";",
"const",
"opacity",
"=",
"position",
".",
"interpolate",
"(",
"{",
"inputRange",
":",
"[",
"first",
",",
"index",
",",
"last",
"]",
",",
"outputRange",
":",
"[",
"0",
",",
"1",
",",
"1",
"]",
",",
"}",
")",
";",
"return",
"{",
"opacity",
",",
"}",
";",
"}"
] |
fadeIn and fadeOut
|
[
"fadeIn",
"and",
"fadeOut"
] |
37bf130e0a459ed8f8671ebf87efcb425aaeb775
|
https://github.com/gegeyang0124/react-native-navigation-cus/blob/37bf130e0a459ed8f8671ebf87efcb425aaeb775/src/views/CardStack/CardStackStyleInterpolator.js#L140-L160
|
38,108 |
devfacet/iptocountry
|
app/index.js
|
loadAndServe
|
function loadAndServe() {
ip2co.dbLoad();
ip2co.listenHTTP({hostname: appConfig.listenOpt.http.hostname, port: appConfig.listenOpt.http.port});
}
|
javascript
|
function loadAndServe() {
ip2co.dbLoad();
ip2co.listenHTTP({hostname: appConfig.listenOpt.http.hostname, port: appConfig.listenOpt.http.port});
}
|
[
"function",
"loadAndServe",
"(",
")",
"{",
"ip2co",
".",
"dbLoad",
"(",
")",
";",
"ip2co",
".",
"listenHTTP",
"(",
"{",
"hostname",
":",
"appConfig",
".",
"listenOpt",
".",
"http",
".",
"hostname",
",",
"port",
":",
"appConfig",
".",
"listenOpt",
".",
"http",
".",
"port",
"}",
")",
";",
"}"
] |
Loads the database and listen http requests.
|
[
"Loads",
"the",
"database",
"and",
"listen",
"http",
"requests",
"."
] |
e22081019cb579ddf1d200d857149374acabd01b
|
https://github.com/devfacet/iptocountry/blob/e22081019cb579ddf1d200d857149374acabd01b/app/index.js#L30-L33
|
38,109 |
amida-tech/blue-button-cms
|
lib/sections/claims.js
|
extrapolateDatesFromLines
|
function extrapolateDatesFromLines(claimLines, returnChildObj) {
var lowTime;
var highTime;
var pointTime;
if (returnChildObj.date_time) {
if (returnChildObj.date_time.low) {
lowTime = returnChildObj.date_time.low;
}
if (returnChildObj.date_time.high) {
highTime = returnChildObj.date_time.high;
}
if (returnChildObj.date_time.point) {
pointTime = returnChildObj.date_time.point;
}
}
for (var x in claimLines) {
if (typeof (claimLines[x]) === "function") {
continue;
}
var claimLineObj = claimLines[x];
if (claimLineObj.date_time) {
/*if the main claim body has undefined dates, populate it with
claim lines date */
if (claimLineObj.date_time.low && lowTime === undefined) {
lowTime = claimLineObj.date_time.low;
}
if (claimLineObj.date_time.high && highTime === undefined) {
highTime = claimLineObj.date_time.high;
}
if (claimLineObj.date_time.point && pointTime === undefined) {
pointTime = claimLineObj.date_time.point;
}
//if the claim lines are defined, then update them with better/more accurate information
if (lowTime !== undefined && claimLineObj.date_time.low) {
var lowDateTime = new Date(lowTime.date);
var lineLowDateTime = new Date(claimLineObj.date_time.low.date);
if (lineLowDateTime < lowDateTime) {
lowTime = claimLineObj.date_time.low;
}
}
if (highTime !== undefined && claimLineObj.date_time.high) {
var highDateTime = new Date(highTime.date);
var lineHighDateTime = new Date(claimLineObj.date_time.high.date);
if (lineHighDateTime > highDateTime) {
highTime = claimLineObj.date_time.high;
}
}
//on the assumption that the most recent service date is most relevant
if (pointTime !== undefined && claimLineObj.date_time.point) {
var pointDateTime = new Date(pointTime.date);
var linePointDateTime = new Date(claimLineObj.date_time.point.date);
if (pointDateTime > pointDateTime) {
pointTime = claimLineObj.date_time.point;
}
}
}
}
//assign the newly discovered times to the main claims body object
if (returnChildObj.date_time === undefined) {
returnChildObj.date_time = {};
}
if (lowTime) {
returnChildObj.date_time.low = lowTime;
}
if (highTime) {
returnChildObj.date_time.high = highTime;
}
if (pointTime) {
returnChildObj.date_time.point = pointTime;
}
}
|
javascript
|
function extrapolateDatesFromLines(claimLines, returnChildObj) {
var lowTime;
var highTime;
var pointTime;
if (returnChildObj.date_time) {
if (returnChildObj.date_time.low) {
lowTime = returnChildObj.date_time.low;
}
if (returnChildObj.date_time.high) {
highTime = returnChildObj.date_time.high;
}
if (returnChildObj.date_time.point) {
pointTime = returnChildObj.date_time.point;
}
}
for (var x in claimLines) {
if (typeof (claimLines[x]) === "function") {
continue;
}
var claimLineObj = claimLines[x];
if (claimLineObj.date_time) {
/*if the main claim body has undefined dates, populate it with
claim lines date */
if (claimLineObj.date_time.low && lowTime === undefined) {
lowTime = claimLineObj.date_time.low;
}
if (claimLineObj.date_time.high && highTime === undefined) {
highTime = claimLineObj.date_time.high;
}
if (claimLineObj.date_time.point && pointTime === undefined) {
pointTime = claimLineObj.date_time.point;
}
//if the claim lines are defined, then update them with better/more accurate information
if (lowTime !== undefined && claimLineObj.date_time.low) {
var lowDateTime = new Date(lowTime.date);
var lineLowDateTime = new Date(claimLineObj.date_time.low.date);
if (lineLowDateTime < lowDateTime) {
lowTime = claimLineObj.date_time.low;
}
}
if (highTime !== undefined && claimLineObj.date_time.high) {
var highDateTime = new Date(highTime.date);
var lineHighDateTime = new Date(claimLineObj.date_time.high.date);
if (lineHighDateTime > highDateTime) {
highTime = claimLineObj.date_time.high;
}
}
//on the assumption that the most recent service date is most relevant
if (pointTime !== undefined && claimLineObj.date_time.point) {
var pointDateTime = new Date(pointTime.date);
var linePointDateTime = new Date(claimLineObj.date_time.point.date);
if (pointDateTime > pointDateTime) {
pointTime = claimLineObj.date_time.point;
}
}
}
}
//assign the newly discovered times to the main claims body object
if (returnChildObj.date_time === undefined) {
returnChildObj.date_time = {};
}
if (lowTime) {
returnChildObj.date_time.low = lowTime;
}
if (highTime) {
returnChildObj.date_time.high = highTime;
}
if (pointTime) {
returnChildObj.date_time.point = pointTime;
}
}
|
[
"function",
"extrapolateDatesFromLines",
"(",
"claimLines",
",",
"returnChildObj",
")",
"{",
"var",
"lowTime",
";",
"var",
"highTime",
";",
"var",
"pointTime",
";",
"if",
"(",
"returnChildObj",
".",
"date_time",
")",
"{",
"if",
"(",
"returnChildObj",
".",
"date_time",
".",
"low",
")",
"{",
"lowTime",
"=",
"returnChildObj",
".",
"date_time",
".",
"low",
";",
"}",
"if",
"(",
"returnChildObj",
".",
"date_time",
".",
"high",
")",
"{",
"highTime",
"=",
"returnChildObj",
".",
"date_time",
".",
"high",
";",
"}",
"if",
"(",
"returnChildObj",
".",
"date_time",
".",
"point",
")",
"{",
"pointTime",
"=",
"returnChildObj",
".",
"date_time",
".",
"point",
";",
"}",
"}",
"for",
"(",
"var",
"x",
"in",
"claimLines",
")",
"{",
"if",
"(",
"typeof",
"(",
"claimLines",
"[",
"x",
"]",
")",
"===",
"\"function\"",
")",
"{",
"continue",
";",
"}",
"var",
"claimLineObj",
"=",
"claimLines",
"[",
"x",
"]",
";",
"if",
"(",
"claimLineObj",
".",
"date_time",
")",
"{",
"/*if the main claim body has undefined dates, populate it with\n claim lines date */",
"if",
"(",
"claimLineObj",
".",
"date_time",
".",
"low",
"&&",
"lowTime",
"===",
"undefined",
")",
"{",
"lowTime",
"=",
"claimLineObj",
".",
"date_time",
".",
"low",
";",
"}",
"if",
"(",
"claimLineObj",
".",
"date_time",
".",
"high",
"&&",
"highTime",
"===",
"undefined",
")",
"{",
"highTime",
"=",
"claimLineObj",
".",
"date_time",
".",
"high",
";",
"}",
"if",
"(",
"claimLineObj",
".",
"date_time",
".",
"point",
"&&",
"pointTime",
"===",
"undefined",
")",
"{",
"pointTime",
"=",
"claimLineObj",
".",
"date_time",
".",
"point",
";",
"}",
"//if the claim lines are defined, then update them with better/more accurate information",
"if",
"(",
"lowTime",
"!==",
"undefined",
"&&",
"claimLineObj",
".",
"date_time",
".",
"low",
")",
"{",
"var",
"lowDateTime",
"=",
"new",
"Date",
"(",
"lowTime",
".",
"date",
")",
";",
"var",
"lineLowDateTime",
"=",
"new",
"Date",
"(",
"claimLineObj",
".",
"date_time",
".",
"low",
".",
"date",
")",
";",
"if",
"(",
"lineLowDateTime",
"<",
"lowDateTime",
")",
"{",
"lowTime",
"=",
"claimLineObj",
".",
"date_time",
".",
"low",
";",
"}",
"}",
"if",
"(",
"highTime",
"!==",
"undefined",
"&&",
"claimLineObj",
".",
"date_time",
".",
"high",
")",
"{",
"var",
"highDateTime",
"=",
"new",
"Date",
"(",
"highTime",
".",
"date",
")",
";",
"var",
"lineHighDateTime",
"=",
"new",
"Date",
"(",
"claimLineObj",
".",
"date_time",
".",
"high",
".",
"date",
")",
";",
"if",
"(",
"lineHighDateTime",
">",
"highDateTime",
")",
"{",
"highTime",
"=",
"claimLineObj",
".",
"date_time",
".",
"high",
";",
"}",
"}",
"//on the assumption that the most recent service date is most relevant",
"if",
"(",
"pointTime",
"!==",
"undefined",
"&&",
"claimLineObj",
".",
"date_time",
".",
"point",
")",
"{",
"var",
"pointDateTime",
"=",
"new",
"Date",
"(",
"pointTime",
".",
"date",
")",
";",
"var",
"linePointDateTime",
"=",
"new",
"Date",
"(",
"claimLineObj",
".",
"date_time",
".",
"point",
".",
"date",
")",
";",
"if",
"(",
"pointDateTime",
">",
"pointDateTime",
")",
"{",
"pointTime",
"=",
"claimLineObj",
".",
"date_time",
".",
"point",
";",
"}",
"}",
"}",
"}",
"//assign the newly discovered times to the main claims body object",
"if",
"(",
"returnChildObj",
".",
"date_time",
"===",
"undefined",
")",
"{",
"returnChildObj",
".",
"date_time",
"=",
"{",
"}",
";",
"}",
"if",
"(",
"lowTime",
")",
"{",
"returnChildObj",
".",
"date_time",
".",
"low",
"=",
"lowTime",
";",
"}",
"if",
"(",
"highTime",
")",
"{",
"returnChildObj",
".",
"date_time",
".",
"high",
"=",
"highTime",
";",
"}",
"if",
"(",
"pointTime",
")",
"{",
"returnChildObj",
".",
"date_time",
".",
"point",
"=",
"pointTime",
";",
"}",
"}"
] |
extrapolates main claim body dates from claim lines
|
[
"extrapolates",
"main",
"claim",
"body",
"dates",
"from",
"claim",
"lines"
] |
749b8cf071910b22f8176a9ed8fc3b05062e1aad
|
https://github.com/amida-tech/blue-button-cms/blob/749b8cf071910b22f8176a9ed8fc3b05062e1aad/lib/sections/claims.js#L25-L99
|
38,110 |
seancheung/kuconfig
|
lib/core.js
|
$var
|
function $var(params, fn, envs) {
if (params == null) {
return params;
}
if (typeof params === 'string') {
if (envs && envs[params] !== undefined) {
return envs[params];
}
return;
}
if (Array.isArray(params) && params.length === 2) {
const key = params[0];
if (typeof key === 'string') {
const value = fn.$var(key, fn, envs);
return value === undefined ? params[1] : value;
}
}
throw new Error(
'$var expects a string or an array with two elements of which the first one must be a string'
);
}
|
javascript
|
function $var(params, fn, envs) {
if (params == null) {
return params;
}
if (typeof params === 'string') {
if (envs && envs[params] !== undefined) {
return envs[params];
}
return;
}
if (Array.isArray(params) && params.length === 2) {
const key = params[0];
if (typeof key === 'string') {
const value = fn.$var(key, fn, envs);
return value === undefined ? params[1] : value;
}
}
throw new Error(
'$var expects a string or an array with two elements of which the first one must be a string'
);
}
|
[
"function",
"$var",
"(",
"params",
",",
"fn",
",",
"envs",
")",
"{",
"if",
"(",
"params",
"==",
"null",
")",
"{",
"return",
"params",
";",
"}",
"if",
"(",
"typeof",
"params",
"===",
"'string'",
")",
"{",
"if",
"(",
"envs",
"&&",
"envs",
"[",
"params",
"]",
"!==",
"undefined",
")",
"{",
"return",
"envs",
"[",
"params",
"]",
";",
"}",
"return",
";",
"}",
"if",
"(",
"Array",
".",
"isArray",
"(",
"params",
")",
"&&",
"params",
".",
"length",
"===",
"2",
")",
"{",
"const",
"key",
"=",
"params",
"[",
"0",
"]",
";",
"if",
"(",
"typeof",
"key",
"===",
"'string'",
")",
"{",
"const",
"value",
"=",
"fn",
".",
"$var",
"(",
"key",
",",
"fn",
",",
"envs",
")",
";",
"return",
"value",
"===",
"undefined",
"?",
"params",
"[",
"1",
"]",
":",
"value",
";",
"}",
"}",
"throw",
"new",
"Error",
"(",
"'$var expects a string or an array with two elements of which the first one must be a string'",
")",
";",
"}"
] |
Get value from envs with an optional fallback value
@param {string|[string, any]} params
@returns {any}
|
[
"Get",
"value",
"from",
"envs",
"with",
"an",
"optional",
"fallback",
"value"
] |
eb0de1920c8fcc7b9a28dceceadc87ecaa5a2ead
|
https://github.com/seancheung/kuconfig/blob/eb0de1920c8fcc7b9a28dceceadc87ecaa5a2ead/lib/core.js#L40-L62
|
38,111 |
seancheung/kuconfig
|
lib/core.js
|
$path
|
function $path(params) {
if (params == null) {
return params;
}
if (typeof params === 'string') {
const path = require('path');
if (path.isAbsolute(params)) {
return params;
}
return path.resolve(process.cwd(), params);
}
throw new Error('$path expects a string');
}
|
javascript
|
function $path(params) {
if (params == null) {
return params;
}
if (typeof params === 'string') {
const path = require('path');
if (path.isAbsolute(params)) {
return params;
}
return path.resolve(process.cwd(), params);
}
throw new Error('$path expects a string');
}
|
[
"function",
"$path",
"(",
"params",
")",
"{",
"if",
"(",
"params",
"==",
"null",
")",
"{",
"return",
"params",
";",
"}",
"if",
"(",
"typeof",
"params",
"===",
"'string'",
")",
"{",
"const",
"path",
"=",
"require",
"(",
"'path'",
")",
";",
"if",
"(",
"path",
".",
"isAbsolute",
"(",
"params",
")",
")",
"{",
"return",
"params",
";",
"}",
"return",
"path",
".",
"resolve",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"params",
")",
";",
"}",
"throw",
"new",
"Error",
"(",
"'$path expects a string'",
")",
";",
"}"
] |
Resolve the path to absolute from current working directory
@param {string} params
@returns {string}
|
[
"Resolve",
"the",
"path",
"to",
"absolute",
"from",
"current",
"working",
"directory"
] |
eb0de1920c8fcc7b9a28dceceadc87ecaa5a2ead
|
https://github.com/seancheung/kuconfig/blob/eb0de1920c8fcc7b9a28dceceadc87ecaa5a2ead/lib/core.js#L70-L83
|
38,112 |
seancheung/kuconfig
|
lib/core.js
|
$file
|
function $file(params, fn) {
if (params == null) {
return params;
}
let file, encoding;
if (typeof params === 'string') {
file = params;
} else if (Array.isArray(params) && params.length === 2) {
file = params[0];
encoding = params[1];
}
if (
typeof file === 'string' &&
(encoding === undefined || typeof encoding === 'string')
) {
file = fn.$path(file);
const fs = require('fs');
if (fs.existsSync(file) && fs.lstatSync(file).isFile()) {
return fs.readFileSync(file, { encoding });
}
}
throw new Error(
'$file expects a string or an array with two string elements'
);
}
|
javascript
|
function $file(params, fn) {
if (params == null) {
return params;
}
let file, encoding;
if (typeof params === 'string') {
file = params;
} else if (Array.isArray(params) && params.length === 2) {
file = params[0];
encoding = params[1];
}
if (
typeof file === 'string' &&
(encoding === undefined || typeof encoding === 'string')
) {
file = fn.$path(file);
const fs = require('fs');
if (fs.existsSync(file) && fs.lstatSync(file).isFile()) {
return fs.readFileSync(file, { encoding });
}
}
throw new Error(
'$file expects a string or an array with two string elements'
);
}
|
[
"function",
"$file",
"(",
"params",
",",
"fn",
")",
"{",
"if",
"(",
"params",
"==",
"null",
")",
"{",
"return",
"params",
";",
"}",
"let",
"file",
",",
"encoding",
";",
"if",
"(",
"typeof",
"params",
"===",
"'string'",
")",
"{",
"file",
"=",
"params",
";",
"}",
"else",
"if",
"(",
"Array",
".",
"isArray",
"(",
"params",
")",
"&&",
"params",
".",
"length",
"===",
"2",
")",
"{",
"file",
"=",
"params",
"[",
"0",
"]",
";",
"encoding",
"=",
"params",
"[",
"1",
"]",
";",
"}",
"if",
"(",
"typeof",
"file",
"===",
"'string'",
"&&",
"(",
"encoding",
"===",
"undefined",
"||",
"typeof",
"encoding",
"===",
"'string'",
")",
")",
"{",
"file",
"=",
"fn",
".",
"$path",
"(",
"file",
")",
";",
"const",
"fs",
"=",
"require",
"(",
"'fs'",
")",
";",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"file",
")",
"&&",
"fs",
".",
"lstatSync",
"(",
"file",
")",
".",
"isFile",
"(",
")",
")",
"{",
"return",
"fs",
".",
"readFileSync",
"(",
"file",
",",
"{",
"encoding",
"}",
")",
";",
"}",
"}",
"throw",
"new",
"Error",
"(",
"'$file expects a string or an array with two string elements'",
")",
";",
"}"
] |
Resolve the path and read the file with an optional encoding
@param {string|[string, string]} params
@returns {string|Buffer}
|
[
"Resolve",
"the",
"path",
"and",
"read",
"the",
"file",
"with",
"an",
"optional",
"encoding"
] |
eb0de1920c8fcc7b9a28dceceadc87ecaa5a2ead
|
https://github.com/seancheung/kuconfig/blob/eb0de1920c8fcc7b9a28dceceadc87ecaa5a2ead/lib/core.js#L91-L115
|
38,113 |
seancheung/kuconfig
|
lib/core.js
|
$number
|
function $number(params) {
if (params == null) {
return params;
}
if (typeof params === 'number') {
return params;
}
if (typeof params === 'string') {
return Number(params);
}
throw new Error('$number expects a number or string');
}
|
javascript
|
function $number(params) {
if (params == null) {
return params;
}
if (typeof params === 'number') {
return params;
}
if (typeof params === 'string') {
return Number(params);
}
throw new Error('$number expects a number or string');
}
|
[
"function",
"$number",
"(",
"params",
")",
"{",
"if",
"(",
"params",
"==",
"null",
")",
"{",
"return",
"params",
";",
"}",
"if",
"(",
"typeof",
"params",
"===",
"'number'",
")",
"{",
"return",
"params",
";",
"}",
"if",
"(",
"typeof",
"params",
"===",
"'string'",
")",
"{",
"return",
"Number",
"(",
"params",
")",
";",
"}",
"throw",
"new",
"Error",
"(",
"'$number expects a number or string'",
")",
";",
"}"
] |
Parse the given string into a number
@param {string} params
@returns {number}
|
[
"Parse",
"the",
"given",
"string",
"into",
"a",
"number"
] |
eb0de1920c8fcc7b9a28dceceadc87ecaa5a2ead
|
https://github.com/seancheung/kuconfig/blob/eb0de1920c8fcc7b9a28dceceadc87ecaa5a2ead/lib/core.js#L139-L150
|
38,114 |
mongodb-js/index-model
|
lib/collection.js
|
function(db, namespace) {
var collection = this;
collection.trigger('request', collection);
fetch(db, namespace, function(err, res) {
if (err) {
throw err;
}
collection.reset(res, {parse: true});
collection.trigger('sync', collection);
});
return collection;
}
|
javascript
|
function(db, namespace) {
var collection = this;
collection.trigger('request', collection);
fetch(db, namespace, function(err, res) {
if (err) {
throw err;
}
collection.reset(res, {parse: true});
collection.trigger('sync', collection);
});
return collection;
}
|
[
"function",
"(",
"db",
",",
"namespace",
")",
"{",
"var",
"collection",
"=",
"this",
";",
"collection",
".",
"trigger",
"(",
"'request'",
",",
"collection",
")",
";",
"fetch",
"(",
"db",
",",
"namespace",
",",
"function",
"(",
"err",
",",
"res",
")",
"{",
"if",
"(",
"err",
")",
"{",
"throw",
"err",
";",
"}",
"collection",
".",
"reset",
"(",
"res",
",",
"{",
"parse",
":",
"true",
"}",
")",
";",
"collection",
".",
"trigger",
"(",
"'sync'",
",",
"collection",
")",
";",
"}",
")",
";",
"return",
"collection",
";",
"}"
] |
queries a MongoDB instance for index details and populates
IndexCollection with the indexes in `namespace`.
@param {MongoClient} db MongoDB driver db handle
@param {String} namespace namespace to get indexes from, e.g. `test.foo`
@return {IndexCollection} collection of indexes on `namespace`
|
[
"queries",
"a",
"MongoDB",
"instance",
"for",
"index",
"details",
"and",
"populates",
"IndexCollection",
"with",
"the",
"indexes",
"in",
"namespace",
"."
] |
43c878440e79299ee104b36d55c06aff63d8cf63
|
https://github.com/mongodb-js/index-model/blob/43c878440e79299ee104b36d55c06aff63d8cf63/lib/collection.js#L17-L28
|
|
38,115 |
warehouseai/bffs
|
index.js
|
BFFS
|
function BFFS(options) {
if (!this) return new BFFS(options);
options = this.init(options);
var store = options.store;
var prefix = options.prefix;
var env = options.env;
var cdn = options.cdn;
//
// We keep the running status of builds in redis.
//
this.store = store;
//
// Everything else we store in Cassandra.
//
this.datastar = options.datastar;
this.models = options.models;
this.log = options.log;
this.prefix = prefix;
this.envs = env;
this.cdns = this.cdnify(cdn);
this.limit = options.limit;
//
// Always fetch by locale so we default our locale property if it does not
// exist.
//
this.defaultLocale = 'en-US';
}
|
javascript
|
function BFFS(options) {
if (!this) return new BFFS(options);
options = this.init(options);
var store = options.store;
var prefix = options.prefix;
var env = options.env;
var cdn = options.cdn;
//
// We keep the running status of builds in redis.
//
this.store = store;
//
// Everything else we store in Cassandra.
//
this.datastar = options.datastar;
this.models = options.models;
this.log = options.log;
this.prefix = prefix;
this.envs = env;
this.cdns = this.cdnify(cdn);
this.limit = options.limit;
//
// Always fetch by locale so we default our locale property if it does not
// exist.
//
this.defaultLocale = 'en-US';
}
|
[
"function",
"BFFS",
"(",
"options",
")",
"{",
"if",
"(",
"!",
"this",
")",
"return",
"new",
"BFFS",
"(",
"options",
")",
";",
"options",
"=",
"this",
".",
"init",
"(",
"options",
")",
";",
"var",
"store",
"=",
"options",
".",
"store",
";",
"var",
"prefix",
"=",
"options",
".",
"prefix",
";",
"var",
"env",
"=",
"options",
".",
"env",
";",
"var",
"cdn",
"=",
"options",
".",
"cdn",
";",
"//",
"// We keep the running status of builds in redis.",
"//",
"this",
".",
"store",
"=",
"store",
";",
"//",
"// Everything else we store in Cassandra.",
"//",
"this",
".",
"datastar",
"=",
"options",
".",
"datastar",
";",
"this",
".",
"models",
"=",
"options",
".",
"models",
";",
"this",
".",
"log",
"=",
"options",
".",
"log",
";",
"this",
".",
"prefix",
"=",
"prefix",
";",
"this",
".",
"envs",
"=",
"env",
";",
"this",
".",
"cdns",
"=",
"this",
".",
"cdnify",
"(",
"cdn",
")",
";",
"this",
".",
"limit",
"=",
"options",
".",
"limit",
";",
"//",
"// Always fetch by locale so we default our locale property if it does not",
"// exist.",
"//",
"this",
".",
"defaultLocale",
"=",
"'en-US'",
";",
"}"
] |
Build Files Finder, BFFS <3
Options:
- store: Dynamis configuration.
- env: Allowed environment variables.
- cdn: Configuration for the CDN.
@constructor
@param {Object} options Configuration.
@api private
|
[
"Build",
"Files",
"Finder",
"BFFS",
"<3"
] |
ca66a82dbac05ba51338987cc90aa5b0bb49d188
|
https://github.com/warehouseai/bffs/blob/ca66a82dbac05ba51338987cc90aa5b0bb49d188/index.js#L31-L63
|
38,116 |
warehouseai/bffs
|
index.js
|
compileEntity
|
function compileEntity() {
var entity = extend({
buildId: bff.key(payload),
extension: file.extension,
filename: file.filename,
fingerprint: print,
url: file.url
}, payload);
return entity;
}
|
javascript
|
function compileEntity() {
var entity = extend({
buildId: bff.key(payload),
extension: file.extension,
filename: file.filename,
fingerprint: print,
url: file.url
}, payload);
return entity;
}
|
[
"function",
"compileEntity",
"(",
")",
"{",
"var",
"entity",
"=",
"extend",
"(",
"{",
"buildId",
":",
"bff",
".",
"key",
"(",
"payload",
")",
",",
"extension",
":",
"file",
".",
"extension",
",",
"filename",
":",
"file",
".",
"filename",
",",
"fingerprint",
":",
"print",
",",
"url",
":",
"file",
".",
"url",
"}",
",",
"payload",
")",
";",
"return",
"entity",
";",
"}"
] |
Compile the entity based on parameters
|
[
"Compile",
"the",
"entity",
"based",
"on",
"parameters"
] |
ca66a82dbac05ba51338987cc90aa5b0bb49d188
|
https://github.com/warehouseai/bffs/blob/ca66a82dbac05ba51338987cc90aa5b0bb49d188/index.js#L402-L412
|
38,117 |
JamesEggers1/node-ABAValidator
|
bin/client-install.js
|
function(){
_prompt.question("You entered '" + _destination + "'. Is this correct? (Y/N)\n", function(input){
var response = input.trim().toLowerCase();
evaluateConfirmation(response);
});
}
|
javascript
|
function(){
_prompt.question("You entered '" + _destination + "'. Is this correct? (Y/N)\n", function(input){
var response = input.trim().toLowerCase();
evaluateConfirmation(response);
});
}
|
[
"function",
"(",
")",
"{",
"_prompt",
".",
"question",
"(",
"\"You entered '\"",
"+",
"_destination",
"+",
"\"'. Is this correct? (Y/N)\\n\"",
",",
"function",
"(",
"input",
")",
"{",
"var",
"response",
"=",
"input",
".",
"trim",
"(",
")",
".",
"toLowerCase",
"(",
")",
";",
"evaluateConfirmation",
"(",
"response",
")",
";",
"}",
")",
";",
"}"
] |
Prompts the user to confirm in a destination directory previously typed in.
@private
|
[
"Prompts",
"the",
"user",
"to",
"confirm",
"in",
"a",
"destination",
"directory",
"previously",
"typed",
"in",
"."
] |
13cfc08c7160b809799a187f3909768816b9c16c
|
https://github.com/JamesEggers1/node-ABAValidator/blob/13cfc08c7160b809799a187f3909768816b9c16c/bin/client-install.js#L28-L33
|
|
38,118 |
JamesEggers1/node-ABAValidator
|
bin/client-install.js
|
function(){
console.log("Unknown Response");
if (_pathConfirmationCounter < 3){
console.log("Please enter a 'Y' or an 'N' when answering.\n");
_pathConfirmationCounter++;
confirmDestination();
} else {
console.log("Unable to install at this time due to too many unknown responses.\n");
_prompt.close();
}
}
|
javascript
|
function(){
console.log("Unknown Response");
if (_pathConfirmationCounter < 3){
console.log("Please enter a 'Y' or an 'N' when answering.\n");
_pathConfirmationCounter++;
confirmDestination();
} else {
console.log("Unable to install at this time due to too many unknown responses.\n");
_prompt.close();
}
}
|
[
"function",
"(",
")",
"{",
"console",
".",
"log",
"(",
"\"Unknown Response\"",
")",
";",
"if",
"(",
"_pathConfirmationCounter",
"<",
"3",
")",
"{",
"console",
".",
"log",
"(",
"\"Please enter a 'Y' or an 'N' when answering.\\n\"",
")",
";",
"_pathConfirmationCounter",
"++",
";",
"confirmDestination",
"(",
")",
";",
"}",
"else",
"{",
"console",
".",
"log",
"(",
"\"Unable to install at this time due to too many unknown responses.\\n\"",
")",
";",
"_prompt",
".",
"close",
"(",
")",
";",
"}",
"}"
] |
Informs the user that their response was unknown and will reprompt if not encountered more than 3 times.
@private
|
[
"Informs",
"the",
"user",
"that",
"their",
"response",
"was",
"unknown",
"and",
"will",
"reprompt",
"if",
"not",
"encountered",
"more",
"than",
"3",
"times",
"."
] |
13cfc08c7160b809799a187f3909768816b9c16c
|
https://github.com/JamesEggers1/node-ABAValidator/blob/13cfc08c7160b809799a187f3909768816b9c16c/bin/client-install.js#L39-L50
|
|
38,119 |
JamesEggers1/node-ABAValidator
|
bin/client-install.js
|
function(){
if (destinationIsRelative){
_destination = _path.join(process.cwd(), "../..", _destination);
}
if(!_fs.existsSync(_destination)){
_fs.mkdirSync(_destination);
}
var destinationPath = _path.join(_destination, "/" + SCRIPT_NAME);
var sourcePath = _path.resolve(_path.dirname(module.filename), "../src/" + SCRIPT_NAME);
var source = _fs.createReadStream(sourcePath);
var dest = _fs.createWriteStream(destinationPath);
dest.pipe(source);
console.log("Client Installation Complete!\n");
console.log(SCRIPT_NAME + " has been installed at: " + destinationPath);
_prompt.close();
}
|
javascript
|
function(){
if (destinationIsRelative){
_destination = _path.join(process.cwd(), "../..", _destination);
}
if(!_fs.existsSync(_destination)){
_fs.mkdirSync(_destination);
}
var destinationPath = _path.join(_destination, "/" + SCRIPT_NAME);
var sourcePath = _path.resolve(_path.dirname(module.filename), "../src/" + SCRIPT_NAME);
var source = _fs.createReadStream(sourcePath);
var dest = _fs.createWriteStream(destinationPath);
dest.pipe(source);
console.log("Client Installation Complete!\n");
console.log(SCRIPT_NAME + " has been installed at: " + destinationPath);
_prompt.close();
}
|
[
"function",
"(",
")",
"{",
"if",
"(",
"destinationIsRelative",
")",
"{",
"_destination",
"=",
"_path",
".",
"join",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"\"../..\"",
",",
"_destination",
")",
";",
"}",
"if",
"(",
"!",
"_fs",
".",
"existsSync",
"(",
"_destination",
")",
")",
"{",
"_fs",
".",
"mkdirSync",
"(",
"_destination",
")",
";",
"}",
"var",
"destinationPath",
"=",
"_path",
".",
"join",
"(",
"_destination",
",",
"\"/\"",
"+",
"SCRIPT_NAME",
")",
";",
"var",
"sourcePath",
"=",
"_path",
".",
"resolve",
"(",
"_path",
".",
"dirname",
"(",
"module",
".",
"filename",
")",
",",
"\"../src/\"",
"+",
"SCRIPT_NAME",
")",
";",
"var",
"source",
"=",
"_fs",
".",
"createReadStream",
"(",
"sourcePath",
")",
";",
"var",
"dest",
"=",
"_fs",
".",
"createWriteStream",
"(",
"destinationPath",
")",
";",
"dest",
".",
"pipe",
"(",
"source",
")",
";",
"console",
".",
"log",
"(",
"\"Client Installation Complete!\\n\"",
")",
";",
"console",
".",
"log",
"(",
"SCRIPT_NAME",
"+",
"\" has been installed at: \"",
"+",
"destinationPath",
")",
";",
"_prompt",
".",
"close",
"(",
")",
";",
"}"
] |
Copies the client-side script to the provided destination directory
@private
|
[
"Copies",
"the",
"client",
"-",
"side",
"script",
"to",
"the",
"provided",
"destination",
"directory"
] |
13cfc08c7160b809799a187f3909768816b9c16c
|
https://github.com/JamesEggers1/node-ABAValidator/blob/13cfc08c7160b809799a187f3909768816b9c16c/bin/client-install.js#L82-L100
|
|
38,120 |
ibm-watson-data-lab/--deprecated--pipes-sdk
|
lib/run/pipeRunStep.js
|
pipeRunStep
|
function pipeRunStep(){
//Public APIs
/**
* run: run this step
* Should be implemented by subclasses
*/
this.run = function( callback ){
throw new Error("Called run method from abstract pipeRunStep class");
}
this.getLabel = function(){
return this.label || "Unknown label";
}
this.getPipe = function(){
return (this.pipeRunStats && this.pipeRunStats.getPipe()) || null;
}
this.getPipeRunner = function(){
return this.pipeRunner || null;
}
this.setStepMessage = function(message){
this.stats.message = message;
this.pipeRunStats.broadcastRunEvent();
}
this.setPercentCompletion = function( percent ){
this.stats.percent = percent;
}
this.beginStep = function( pipeRunner, pipeRunStats ){
pipeRunStats.logger.info( "Step %s started", this.getLabel() );
//Reference to the main stats object
this.pipeRunStats = pipeRunStats;
this.pipeRunner = pipeRunner;
pipeRunStats.setMessage( this.label );
//Record the start time
this.stats.startTime = moment();
this.stats.status = "RUNNING";
this.setPercentCompletion(0);
this.pipeRunStats.save();
}
this.endStep = function(callback, err){
//Set the end time and elapsed time
this.stats.endTime = moment();
this.stats.elapsedTime = moment.duration( this.stats.endTime.diff( this.stats.startTime ) ).humanize();
this.stats.status = err ? "ERROR" : "FINISHED";
if ( err ){
this.setStepMessage( err );
}
this.setPercentCompletion(100);
this.pipeRunStats.save( callback, err );
this.pipeRunStats.logger.info({
message: require('util').format("Step %s completed", this.getLabel() ),
stats: this.stats
});
}
/**
* toJSON serialization function
*/
this.toJSON = function(){
return {
label: this.getLabel()
}
}
}
|
javascript
|
function pipeRunStep(){
//Public APIs
/**
* run: run this step
* Should be implemented by subclasses
*/
this.run = function( callback ){
throw new Error("Called run method from abstract pipeRunStep class");
}
this.getLabel = function(){
return this.label || "Unknown label";
}
this.getPipe = function(){
return (this.pipeRunStats && this.pipeRunStats.getPipe()) || null;
}
this.getPipeRunner = function(){
return this.pipeRunner || null;
}
this.setStepMessage = function(message){
this.stats.message = message;
this.pipeRunStats.broadcastRunEvent();
}
this.setPercentCompletion = function( percent ){
this.stats.percent = percent;
}
this.beginStep = function( pipeRunner, pipeRunStats ){
pipeRunStats.logger.info( "Step %s started", this.getLabel() );
//Reference to the main stats object
this.pipeRunStats = pipeRunStats;
this.pipeRunner = pipeRunner;
pipeRunStats.setMessage( this.label );
//Record the start time
this.stats.startTime = moment();
this.stats.status = "RUNNING";
this.setPercentCompletion(0);
this.pipeRunStats.save();
}
this.endStep = function(callback, err){
//Set the end time and elapsed time
this.stats.endTime = moment();
this.stats.elapsedTime = moment.duration( this.stats.endTime.diff( this.stats.startTime ) ).humanize();
this.stats.status = err ? "ERROR" : "FINISHED";
if ( err ){
this.setStepMessage( err );
}
this.setPercentCompletion(100);
this.pipeRunStats.save( callback, err );
this.pipeRunStats.logger.info({
message: require('util').format("Step %s completed", this.getLabel() ),
stats: this.stats
});
}
/**
* toJSON serialization function
*/
this.toJSON = function(){
return {
label: this.getLabel()
}
}
}
|
[
"function",
"pipeRunStep",
"(",
")",
"{",
"//Public APIs",
"/**\n\t * run: run this step\n\t * Should be implemented by subclasses\n\t */",
"this",
".",
"run",
"=",
"function",
"(",
"callback",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Called run method from abstract pipeRunStep class\"",
")",
";",
"}",
"this",
".",
"getLabel",
"=",
"function",
"(",
")",
"{",
"return",
"this",
".",
"label",
"||",
"\"Unknown label\"",
";",
"}",
"this",
".",
"getPipe",
"=",
"function",
"(",
")",
"{",
"return",
"(",
"this",
".",
"pipeRunStats",
"&&",
"this",
".",
"pipeRunStats",
".",
"getPipe",
"(",
")",
")",
"||",
"null",
";",
"}",
"this",
".",
"getPipeRunner",
"=",
"function",
"(",
")",
"{",
"return",
"this",
".",
"pipeRunner",
"||",
"null",
";",
"}",
"this",
".",
"setStepMessage",
"=",
"function",
"(",
"message",
")",
"{",
"this",
".",
"stats",
".",
"message",
"=",
"message",
";",
"this",
".",
"pipeRunStats",
".",
"broadcastRunEvent",
"(",
")",
";",
"}",
"this",
".",
"setPercentCompletion",
"=",
"function",
"(",
"percent",
")",
"{",
"this",
".",
"stats",
".",
"percent",
"=",
"percent",
";",
"}",
"this",
".",
"beginStep",
"=",
"function",
"(",
"pipeRunner",
",",
"pipeRunStats",
")",
"{",
"pipeRunStats",
".",
"logger",
".",
"info",
"(",
"\"Step %s started\"",
",",
"this",
".",
"getLabel",
"(",
")",
")",
";",
"//Reference to the main stats object",
"this",
".",
"pipeRunStats",
"=",
"pipeRunStats",
";",
"this",
".",
"pipeRunner",
"=",
"pipeRunner",
";",
"pipeRunStats",
".",
"setMessage",
"(",
"this",
".",
"label",
")",
";",
"//Record the start time",
"this",
".",
"stats",
".",
"startTime",
"=",
"moment",
"(",
")",
";",
"this",
".",
"stats",
".",
"status",
"=",
"\"RUNNING\"",
";",
"this",
".",
"setPercentCompletion",
"(",
"0",
")",
";",
"this",
".",
"pipeRunStats",
".",
"save",
"(",
")",
";",
"}",
"this",
".",
"endStep",
"=",
"function",
"(",
"callback",
",",
"err",
")",
"{",
"//Set the end time and elapsed time",
"this",
".",
"stats",
".",
"endTime",
"=",
"moment",
"(",
")",
";",
"this",
".",
"stats",
".",
"elapsedTime",
"=",
"moment",
".",
"duration",
"(",
"this",
".",
"stats",
".",
"endTime",
".",
"diff",
"(",
"this",
".",
"stats",
".",
"startTime",
")",
")",
".",
"humanize",
"(",
")",
";",
"this",
".",
"stats",
".",
"status",
"=",
"err",
"?",
"\"ERROR\"",
":",
"\"FINISHED\"",
";",
"if",
"(",
"err",
")",
"{",
"this",
".",
"setStepMessage",
"(",
"err",
")",
";",
"}",
"this",
".",
"setPercentCompletion",
"(",
"100",
")",
";",
"this",
".",
"pipeRunStats",
".",
"save",
"(",
"callback",
",",
"err",
")",
";",
"this",
".",
"pipeRunStats",
".",
"logger",
".",
"info",
"(",
"{",
"message",
":",
"require",
"(",
"'util'",
")",
".",
"format",
"(",
"\"Step %s completed\"",
",",
"this",
".",
"getLabel",
"(",
")",
")",
",",
"stats",
":",
"this",
".",
"stats",
"}",
")",
";",
"}",
"/**\n\t * toJSON serialization function\n\t */",
"this",
".",
"toJSON",
"=",
"function",
"(",
")",
"{",
"return",
"{",
"label",
":",
"this",
".",
"getLabel",
"(",
")",
"}",
"}",
"}"
] |
PipeRunStep class
Abstract Base class for all run steps
|
[
"PipeRunStep",
"class",
"Abstract",
"Base",
"class",
"for",
"all",
"run",
"steps"
] |
b5cbf238d8d2c6a852f1712eed7dcfabeebfdb25
|
https://github.com/ibm-watson-data-lab/--deprecated--pipes-sdk/blob/b5cbf238d8d2c6a852f1712eed7dcfabeebfdb25/lib/run/pipeRunStep.js#L14-L88
|
38,121 |
node-modules/antpb
|
lib/converter.js
|
genValuePartial_fromObject
|
function genValuePartial_fromObject(gen, field, fieldIndex, prop) {
if (field.resolvedType) {
if (field.resolvedType instanceof Enum) {
gen('switch(d%s){', prop);
for (let values = field.resolvedType.values, keys = Object.keys(values), i = 0; i < keys.length; ++i) {
if (field.repeated && values[keys[i]] === field.typeDefault) gen('default:');
gen('case%j:', keys[i])('case %i:', values[keys[i]])('m%s=%j', prop, values[keys[i]])('break');
}
gen('}');
} else {
gen('if(typeof d%s!=="object")', prop)('throw TypeError(%j)', field.fullName + ': object expected')('m%s=types[%i].fromObject(d%s)', prop, fieldIndex, prop);
}
} else {
let isUnsigned = false;
switch (field.type) {
case 'double':
case 'float':
gen('m%s=Number(d%s)', prop, prop); // also catches "NaN", "Infinity"
break;
case 'uint32':
case 'fixed32':
gen('m%s=d%s>>>0', prop, prop);
break;
case 'int32':
case 'sint32':
case 'sfixed32':
gen('m%s=d%s|0', prop, prop);
break;
case 'uint64':
isUnsigned = true;
// eslint-disable-line no-fallthrough
case 'int64':
case 'sint64':
case 'fixed64':
case 'sfixed64':
gen('if(util.Long)')('(m%s=util.Long.fromValue(d%s)).unsigned=%j', prop, prop, isUnsigned)('else if(typeof d%s==="string")', prop)('m%s=parseInt(d%s,10)', prop, prop)('else if(typeof d%s==="number")', prop)('m%s=d%s', prop, prop)('else if(typeof d%s==="object")', prop)('m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)', prop, prop, prop, isUnsigned ? 'true' : '');
break;
case 'bytes':
gen('if(typeof d%s==="string")', prop)('util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)', prop, prop, prop)('else if(d%s.length)', prop)('m%s=d%s', prop, prop);
break;
case 'string':
gen('m%s=String(d%s)', prop, prop);
break;
case 'bool':
gen('m%s=Boolean(d%s)', prop, prop);
break;
default:
break;
/* default: gen
("m%s=d%s", prop, prop);
break; */
}
}
return gen;
}
|
javascript
|
function genValuePartial_fromObject(gen, field, fieldIndex, prop) {
if (field.resolvedType) {
if (field.resolvedType instanceof Enum) {
gen('switch(d%s){', prop);
for (let values = field.resolvedType.values, keys = Object.keys(values), i = 0; i < keys.length; ++i) {
if (field.repeated && values[keys[i]] === field.typeDefault) gen('default:');
gen('case%j:', keys[i])('case %i:', values[keys[i]])('m%s=%j', prop, values[keys[i]])('break');
}
gen('}');
} else {
gen('if(typeof d%s!=="object")', prop)('throw TypeError(%j)', field.fullName + ': object expected')('m%s=types[%i].fromObject(d%s)', prop, fieldIndex, prop);
}
} else {
let isUnsigned = false;
switch (field.type) {
case 'double':
case 'float':
gen('m%s=Number(d%s)', prop, prop); // also catches "NaN", "Infinity"
break;
case 'uint32':
case 'fixed32':
gen('m%s=d%s>>>0', prop, prop);
break;
case 'int32':
case 'sint32':
case 'sfixed32':
gen('m%s=d%s|0', prop, prop);
break;
case 'uint64':
isUnsigned = true;
// eslint-disable-line no-fallthrough
case 'int64':
case 'sint64':
case 'fixed64':
case 'sfixed64':
gen('if(util.Long)')('(m%s=util.Long.fromValue(d%s)).unsigned=%j', prop, prop, isUnsigned)('else if(typeof d%s==="string")', prop)('m%s=parseInt(d%s,10)', prop, prop)('else if(typeof d%s==="number")', prop)('m%s=d%s', prop, prop)('else if(typeof d%s==="object")', prop)('m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)', prop, prop, prop, isUnsigned ? 'true' : '');
break;
case 'bytes':
gen('if(typeof d%s==="string")', prop)('util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)', prop, prop, prop)('else if(d%s.length)', prop)('m%s=d%s', prop, prop);
break;
case 'string':
gen('m%s=String(d%s)', prop, prop);
break;
case 'bool':
gen('m%s=Boolean(d%s)', prop, prop);
break;
default:
break;
/* default: gen
("m%s=d%s", prop, prop);
break; */
}
}
return gen;
}
|
[
"function",
"genValuePartial_fromObject",
"(",
"gen",
",",
"field",
",",
"fieldIndex",
",",
"prop",
")",
"{",
"if",
"(",
"field",
".",
"resolvedType",
")",
"{",
"if",
"(",
"field",
".",
"resolvedType",
"instanceof",
"Enum",
")",
"{",
"gen",
"(",
"'switch(d%s){'",
",",
"prop",
")",
";",
"for",
"(",
"let",
"values",
"=",
"field",
".",
"resolvedType",
".",
"values",
",",
"keys",
"=",
"Object",
".",
"keys",
"(",
"values",
")",
",",
"i",
"=",
"0",
";",
"i",
"<",
"keys",
".",
"length",
";",
"++",
"i",
")",
"{",
"if",
"(",
"field",
".",
"repeated",
"&&",
"values",
"[",
"keys",
"[",
"i",
"]",
"]",
"===",
"field",
".",
"typeDefault",
")",
"gen",
"(",
"'default:'",
")",
";",
"gen",
"(",
"'case%j:'",
",",
"keys",
"[",
"i",
"]",
")",
"(",
"'case %i:'",
",",
"values",
"[",
"keys",
"[",
"i",
"]",
"]",
")",
"(",
"'m%s=%j'",
",",
"prop",
",",
"values",
"[",
"keys",
"[",
"i",
"]",
"]",
")",
"(",
"'break'",
")",
";",
"}",
"gen",
"(",
"'}'",
")",
";",
"}",
"else",
"{",
"gen",
"(",
"'if(typeof d%s!==\"object\")'",
",",
"prop",
")",
"(",
"'throw TypeError(%j)'",
",",
"field",
".",
"fullName",
"+",
"': object expected'",
")",
"(",
"'m%s=types[%i].fromObject(d%s)'",
",",
"prop",
",",
"fieldIndex",
",",
"prop",
")",
";",
"}",
"}",
"else",
"{",
"let",
"isUnsigned",
"=",
"false",
";",
"switch",
"(",
"field",
".",
"type",
")",
"{",
"case",
"'double'",
":",
"case",
"'float'",
":",
"gen",
"(",
"'m%s=Number(d%s)'",
",",
"prop",
",",
"prop",
")",
";",
"// also catches \"NaN\", \"Infinity\"",
"break",
";",
"case",
"'uint32'",
":",
"case",
"'fixed32'",
":",
"gen",
"(",
"'m%s=d%s>>>0'",
",",
"prop",
",",
"prop",
")",
";",
"break",
";",
"case",
"'int32'",
":",
"case",
"'sint32'",
":",
"case",
"'sfixed32'",
":",
"gen",
"(",
"'m%s=d%s|0'",
",",
"prop",
",",
"prop",
")",
";",
"break",
";",
"case",
"'uint64'",
":",
"isUnsigned",
"=",
"true",
";",
"// eslint-disable-line no-fallthrough",
"case",
"'int64'",
":",
"case",
"'sint64'",
":",
"case",
"'fixed64'",
":",
"case",
"'sfixed64'",
":",
"gen",
"(",
"'if(util.Long)'",
")",
"(",
"'(m%s=util.Long.fromValue(d%s)).unsigned=%j'",
",",
"prop",
",",
"prop",
",",
"isUnsigned",
")",
"(",
"'else if(typeof d%s===\"string\")'",
",",
"prop",
")",
"(",
"'m%s=parseInt(d%s,10)'",
",",
"prop",
",",
"prop",
")",
"(",
"'else if(typeof d%s===\"number\")'",
",",
"prop",
")",
"(",
"'m%s=d%s'",
",",
"prop",
",",
"prop",
")",
"(",
"'else if(typeof d%s===\"object\")'",
",",
"prop",
")",
"(",
"'m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)'",
",",
"prop",
",",
"prop",
",",
"prop",
",",
"isUnsigned",
"?",
"'true'",
":",
"''",
")",
";",
"break",
";",
"case",
"'bytes'",
":",
"gen",
"(",
"'if(typeof d%s===\"string\")'",
",",
"prop",
")",
"(",
"'util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)'",
",",
"prop",
",",
"prop",
",",
"prop",
")",
"(",
"'else if(d%s.length)'",
",",
"prop",
")",
"(",
"'m%s=d%s'",
",",
"prop",
",",
"prop",
")",
";",
"break",
";",
"case",
"'string'",
":",
"gen",
"(",
"'m%s=String(d%s)'",
",",
"prop",
",",
"prop",
")",
";",
"break",
";",
"case",
"'bool'",
":",
"gen",
"(",
"'m%s=Boolean(d%s)'",
",",
"prop",
",",
"prop",
")",
";",
"break",
";",
"default",
":",
"break",
";",
"/* default: gen\n (\"m%s=d%s\", prop, prop);\n break; */",
"}",
"}",
"return",
"gen",
";",
"}"
] |
Generates a partial value fromObject conveter.
@param {Codegen} gen Codegen instance
@param {Field} field Reflected field
@param {number} fieldIndex Field index
@param {string} prop Property reference
@return {Codegen} Codegen instance
@ignore
|
[
"Generates",
"a",
"partial",
"value",
"fromObject",
"conveter",
"."
] |
e6d74d4c372151fcb3880eb44a4e85907d99405c
|
https://github.com/node-modules/antpb/blob/e6d74d4c372151fcb3880eb44a4e85907d99405c/lib/converter.js#L17-L71
|
38,122 |
node-modules/antpb
|
lib/converter.js
|
genValuePartial_toObject
|
function genValuePartial_toObject(gen, field, fieldIndex, prop, map) {
if (field.resolvedType) {
if (field.resolvedType instanceof Enum) {
if (map) {
gen('d%s.set(k, o.enums===String?types[%i].values[m%s.get(k)]:m%s.get(k));', prop, fieldIndex, prop, prop);
} else {
gen('d%s=o.enums===String?types[%i].values[m%s]:m%s', prop, fieldIndex, prop, prop);
}
} else {
if (map) {
gen('d%s.set(k, types[%i].toObject(m%s.get(k),o));', prop, fieldIndex, prop);
} else {
gen('d%s=types[%i].toObject(m%s,o)', prop, fieldIndex, prop);
}
}
} else {
let isUnsigned = false;
switch (field.type) {
case 'double':
case 'float':
if (map) {
gen('d%s.set(k, o.json&&!isFinite(m%s.get(k))?String(m%s.get(k)):m%s.get(k));', prop, prop, prop, prop);
} else {
gen('d%s=o.json&&!isFinite(m%s)?String(m%s):m%s;', prop, prop, prop, prop);
}
break;
case 'uint64':
isUnsigned = true;
// eslint-disable-line no-fallthrough
case 'int64':
case 'sint64':
case 'fixed64':
case 'sfixed64':
if (map) {
gen('if(typeof m%s==="number"){', prop)('d%s.set(k, o.longs===String?String(m%s.get(k)):m%s.get(k));', prop, prop, prop)('} else {')('d%s.set(k, o.longs===String?util.Long.prototype.toString.call(m%s.get(k)):o.longs===Number?new util.LongBits(m%s.get(k).low>>>0,m%s.get(k).high>>>0).toNumber(%s):m%s.get(k));', prop, prop, prop, prop, isUnsigned ? 'true' : '', prop)('}');
} else {
gen('if(typeof m%s==="number"){', prop)('d%s=o.longs===String?String(m%s):m%s;', prop, prop, prop)('} else {')('d%s=o.longs===String?util.Long.prototype.toString.call(m%s):o.longs===Number?new util.LongBits(m%s.low>>>0,m%s.high>>>0).toNumber(%s):m%s', prop, prop, prop, prop, isUnsigned ? 'true' : '', prop)('}');
}
break;
case 'bytes':
if (map) {
gen('d%s.set(k, o.bytes===String?util.base64.encode(m%s.get(k),0,m%s.get(k).length):o.bytes===Array?Array.prototype.slice.call(m%s.get(k)):m%s.get(k));', prop, prop, prop, prop, prop);
} else {
gen('d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s', prop, prop, prop, prop, prop);
}
break;
default:
if (map) {
gen('d%s.set(k, m%s.get(k));', prop, prop);
} else {
gen('d%s=m%s', prop, prop);
}
break;
}
}
return gen;
}
|
javascript
|
function genValuePartial_toObject(gen, field, fieldIndex, prop, map) {
if (field.resolvedType) {
if (field.resolvedType instanceof Enum) {
if (map) {
gen('d%s.set(k, o.enums===String?types[%i].values[m%s.get(k)]:m%s.get(k));', prop, fieldIndex, prop, prop);
} else {
gen('d%s=o.enums===String?types[%i].values[m%s]:m%s', prop, fieldIndex, prop, prop);
}
} else {
if (map) {
gen('d%s.set(k, types[%i].toObject(m%s.get(k),o));', prop, fieldIndex, prop);
} else {
gen('d%s=types[%i].toObject(m%s,o)', prop, fieldIndex, prop);
}
}
} else {
let isUnsigned = false;
switch (field.type) {
case 'double':
case 'float':
if (map) {
gen('d%s.set(k, o.json&&!isFinite(m%s.get(k))?String(m%s.get(k)):m%s.get(k));', prop, prop, prop, prop);
} else {
gen('d%s=o.json&&!isFinite(m%s)?String(m%s):m%s;', prop, prop, prop, prop);
}
break;
case 'uint64':
isUnsigned = true;
// eslint-disable-line no-fallthrough
case 'int64':
case 'sint64':
case 'fixed64':
case 'sfixed64':
if (map) {
gen('if(typeof m%s==="number"){', prop)('d%s.set(k, o.longs===String?String(m%s.get(k)):m%s.get(k));', prop, prop, prop)('} else {')('d%s.set(k, o.longs===String?util.Long.prototype.toString.call(m%s.get(k)):o.longs===Number?new util.LongBits(m%s.get(k).low>>>0,m%s.get(k).high>>>0).toNumber(%s):m%s.get(k));', prop, prop, prop, prop, isUnsigned ? 'true' : '', prop)('}');
} else {
gen('if(typeof m%s==="number"){', prop)('d%s=o.longs===String?String(m%s):m%s;', prop, prop, prop)('} else {')('d%s=o.longs===String?util.Long.prototype.toString.call(m%s):o.longs===Number?new util.LongBits(m%s.low>>>0,m%s.high>>>0).toNumber(%s):m%s', prop, prop, prop, prop, isUnsigned ? 'true' : '', prop)('}');
}
break;
case 'bytes':
if (map) {
gen('d%s.set(k, o.bytes===String?util.base64.encode(m%s.get(k),0,m%s.get(k).length):o.bytes===Array?Array.prototype.slice.call(m%s.get(k)):m%s.get(k));', prop, prop, prop, prop, prop);
} else {
gen('d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s', prop, prop, prop, prop, prop);
}
break;
default:
if (map) {
gen('d%s.set(k, m%s.get(k));', prop, prop);
} else {
gen('d%s=m%s', prop, prop);
}
break;
}
}
return gen;
}
|
[
"function",
"genValuePartial_toObject",
"(",
"gen",
",",
"field",
",",
"fieldIndex",
",",
"prop",
",",
"map",
")",
"{",
"if",
"(",
"field",
".",
"resolvedType",
")",
"{",
"if",
"(",
"field",
".",
"resolvedType",
"instanceof",
"Enum",
")",
"{",
"if",
"(",
"map",
")",
"{",
"gen",
"(",
"'d%s.set(k, o.enums===String?types[%i].values[m%s.get(k)]:m%s.get(k));'",
",",
"prop",
",",
"fieldIndex",
",",
"prop",
",",
"prop",
")",
";",
"}",
"else",
"{",
"gen",
"(",
"'d%s=o.enums===String?types[%i].values[m%s]:m%s'",
",",
"prop",
",",
"fieldIndex",
",",
"prop",
",",
"prop",
")",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"map",
")",
"{",
"gen",
"(",
"'d%s.set(k, types[%i].toObject(m%s.get(k),o));'",
",",
"prop",
",",
"fieldIndex",
",",
"prop",
")",
";",
"}",
"else",
"{",
"gen",
"(",
"'d%s=types[%i].toObject(m%s,o)'",
",",
"prop",
",",
"fieldIndex",
",",
"prop",
")",
";",
"}",
"}",
"}",
"else",
"{",
"let",
"isUnsigned",
"=",
"false",
";",
"switch",
"(",
"field",
".",
"type",
")",
"{",
"case",
"'double'",
":",
"case",
"'float'",
":",
"if",
"(",
"map",
")",
"{",
"gen",
"(",
"'d%s.set(k, o.json&&!isFinite(m%s.get(k))?String(m%s.get(k)):m%s.get(k));'",
",",
"prop",
",",
"prop",
",",
"prop",
",",
"prop",
")",
";",
"}",
"else",
"{",
"gen",
"(",
"'d%s=o.json&&!isFinite(m%s)?String(m%s):m%s;'",
",",
"prop",
",",
"prop",
",",
"prop",
",",
"prop",
")",
";",
"}",
"break",
";",
"case",
"'uint64'",
":",
"isUnsigned",
"=",
"true",
";",
"// eslint-disable-line no-fallthrough",
"case",
"'int64'",
":",
"case",
"'sint64'",
":",
"case",
"'fixed64'",
":",
"case",
"'sfixed64'",
":",
"if",
"(",
"map",
")",
"{",
"gen",
"(",
"'if(typeof m%s===\"number\"){'",
",",
"prop",
")",
"(",
"'d%s.set(k, o.longs===String?String(m%s.get(k)):m%s.get(k));'",
",",
"prop",
",",
"prop",
",",
"prop",
")",
"(",
"'} else {'",
")",
"(",
"'d%s.set(k, o.longs===String?util.Long.prototype.toString.call(m%s.get(k)):o.longs===Number?new util.LongBits(m%s.get(k).low>>>0,m%s.get(k).high>>>0).toNumber(%s):m%s.get(k));'",
",",
"prop",
",",
"prop",
",",
"prop",
",",
"prop",
",",
"isUnsigned",
"?",
"'true'",
":",
"''",
",",
"prop",
")",
"(",
"'}'",
")",
";",
"}",
"else",
"{",
"gen",
"(",
"'if(typeof m%s===\"number\"){'",
",",
"prop",
")",
"(",
"'d%s=o.longs===String?String(m%s):m%s;'",
",",
"prop",
",",
"prop",
",",
"prop",
")",
"(",
"'} else {'",
")",
"(",
"'d%s=o.longs===String?util.Long.prototype.toString.call(m%s):o.longs===Number?new util.LongBits(m%s.low>>>0,m%s.high>>>0).toNumber(%s):m%s'",
",",
"prop",
",",
"prop",
",",
"prop",
",",
"prop",
",",
"isUnsigned",
"?",
"'true'",
":",
"''",
",",
"prop",
")",
"(",
"'}'",
")",
";",
"}",
"break",
";",
"case",
"'bytes'",
":",
"if",
"(",
"map",
")",
"{",
"gen",
"(",
"'d%s.set(k, o.bytes===String?util.base64.encode(m%s.get(k),0,m%s.get(k).length):o.bytes===Array?Array.prototype.slice.call(m%s.get(k)):m%s.get(k));'",
",",
"prop",
",",
"prop",
",",
"prop",
",",
"prop",
",",
"prop",
")",
";",
"}",
"else",
"{",
"gen",
"(",
"'d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s'",
",",
"prop",
",",
"prop",
",",
"prop",
",",
"prop",
",",
"prop",
")",
";",
"}",
"break",
";",
"default",
":",
"if",
"(",
"map",
")",
"{",
"gen",
"(",
"'d%s.set(k, m%s.get(k));'",
",",
"prop",
",",
"prop",
")",
";",
"}",
"else",
"{",
"gen",
"(",
"'d%s=m%s'",
",",
"prop",
",",
"prop",
")",
";",
"}",
"break",
";",
"}",
"}",
"return",
"gen",
";",
"}"
] |
Generates a partial value toObject converter.
@param {Codegen} gen Codegen instance
@param {Field} field Reflected field
@param {number} fieldIndex Field index
@param {string} prop Property reference
@param {bool} map whether is a map
@return {Codegen} Codegen instance
@ignore
|
[
"Generates",
"a",
"partial",
"value",
"toObject",
"converter",
"."
] |
e6d74d4c372151fcb3880eb44a4e85907d99405c
|
https://github.com/node-modules/antpb/blob/e6d74d4c372151fcb3880eb44a4e85907d99405c/lib/converter.js#L175-L231
|
38,123 |
hachi-eiji/generate-serial-number
|
index.js
|
checkSum
|
function checkSum(num) {
if (num == null) {
return 0;
}
var doubled = _splitDigits(num).reverse().map(function(v, idx) {
return idx % 2 === 0 ? v * 2 : v;
});
var sum = doubled.reduce(function(tmp, v) {
return tmp + _sum(v);
}, 0);
var check = 10 - (sum % 10);
return check === 10 ? 0 : check;
}
|
javascript
|
function checkSum(num) {
if (num == null) {
return 0;
}
var doubled = _splitDigits(num).reverse().map(function(v, idx) {
return idx % 2 === 0 ? v * 2 : v;
});
var sum = doubled.reduce(function(tmp, v) {
return tmp + _sum(v);
}, 0);
var check = 10 - (sum % 10);
return check === 10 ? 0 : check;
}
|
[
"function",
"checkSum",
"(",
"num",
")",
"{",
"if",
"(",
"num",
"==",
"null",
")",
"{",
"return",
"0",
";",
"}",
"var",
"doubled",
"=",
"_splitDigits",
"(",
"num",
")",
".",
"reverse",
"(",
")",
".",
"map",
"(",
"function",
"(",
"v",
",",
"idx",
")",
"{",
"return",
"idx",
"%",
"2",
"===",
"0",
"?",
"v",
"*",
"2",
":",
"v",
";",
"}",
")",
";",
"var",
"sum",
"=",
"doubled",
".",
"reduce",
"(",
"function",
"(",
"tmp",
",",
"v",
")",
"{",
"return",
"tmp",
"+",
"_sum",
"(",
"v",
")",
";",
"}",
",",
"0",
")",
";",
"var",
"check",
"=",
"10",
"-",
"(",
"sum",
"%",
"10",
")",
";",
"return",
"check",
"===",
"10",
"?",
"0",
":",
"check",
";",
"}"
] |
create check sum.
@param {string|number} num
@return {number} check sum value
|
[
"create",
"check",
"sum",
"."
] |
17bf97c86aa183690e9456cb5bf3619c964542d4
|
https://github.com/hachi-eiji/generate-serial-number/blob/17bf97c86aa183690e9456cb5bf3619c964542d4/index.js#L22-L34
|
38,124 |
hachi-eiji/generate-serial-number
|
index.js
|
isValid
|
function isValid(checkNumber) {
if (checkNumber == null) {
return false;
}
var numbers = _splitDigits(checkNumber);
return numbers.pop() === checkSum(numbers.join(''));
}
|
javascript
|
function isValid(checkNumber) {
if (checkNumber == null) {
return false;
}
var numbers = _splitDigits(checkNumber);
return numbers.pop() === checkSum(numbers.join(''));
}
|
[
"function",
"isValid",
"(",
"checkNumber",
")",
"{",
"if",
"(",
"checkNumber",
"==",
"null",
")",
"{",
"return",
"false",
";",
"}",
"var",
"numbers",
"=",
"_splitDigits",
"(",
"checkNumber",
")",
";",
"return",
"numbers",
".",
"pop",
"(",
")",
"===",
"checkSum",
"(",
"numbers",
".",
"join",
"(",
"''",
")",
")",
";",
"}"
] |
validate num.
@param {string|number} checkNumber check number
@return {boolean} true: checkNumber is valid
|
[
"validate",
"num",
"."
] |
17bf97c86aa183690e9456cb5bf3619c964542d4
|
https://github.com/hachi-eiji/generate-serial-number/blob/17bf97c86aa183690e9456cb5bf3619c964542d4/index.js#L42-L48
|
38,125 |
hachi-eiji/generate-serial-number
|
index.js
|
generate
|
function generate(length) {
var len = length - 1;
var ary = new Array(len);
for (var i = 0; i < len; i++) {
ary.push(Math.floor(Math.random() * 10));
}
var num = ary.join('');
return num + '' + checkSum(num);
}
|
javascript
|
function generate(length) {
var len = length - 1;
var ary = new Array(len);
for (var i = 0; i < len; i++) {
ary.push(Math.floor(Math.random() * 10));
}
var num = ary.join('');
return num + '' + checkSum(num);
}
|
[
"function",
"generate",
"(",
"length",
")",
"{",
"var",
"len",
"=",
"length",
"-",
"1",
";",
"var",
"ary",
"=",
"new",
"Array",
"(",
"len",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"ary",
".",
"push",
"(",
"Math",
".",
"floor",
"(",
"Math",
".",
"random",
"(",
")",
"*",
"10",
")",
")",
";",
"}",
"var",
"num",
"=",
"ary",
".",
"join",
"(",
"''",
")",
";",
"return",
"num",
"+",
"''",
"+",
"checkSum",
"(",
"num",
")",
";",
"}"
] |
create generate code
@param {number} length generage
@return {string} generaged digits value
|
[
"create",
"generate",
"code"
] |
17bf97c86aa183690e9456cb5bf3619c964542d4
|
https://github.com/hachi-eiji/generate-serial-number/blob/17bf97c86aa183690e9456cb5bf3619c964542d4/index.js#L56-L64
|
38,126 |
tjmehta/buffer-splice
|
index.js
|
bufferSplice
|
function bufferSplice (buffer, start, count/*, [...items] */) {
var args = assertArgs(arguments, {
buffer: [Buffer, 'object'],
'[start]': 'integer',
'[count]': 'integer',
'[...items]': [Buffer, 'string', 'array', 'object', 'number']
})
defaults(args, {
start: buffer.length,
count: buffer.length,
items: []
})
buffer = args.buffer
start = args.start
count = args.count
var opts
if (!Buffer.isBuffer(buffer)) {
opts = buffer
buffer = opts.buffer
}
var items = args.items.map(castBuffer)
var end = start + count
var modified = Buffer.concat(
[ buffer.slice(0, start) ]
.concat(items)
.concat(buffer.slice(end, buffer.length))
)
if (opts) {
opts.buffer = modified // opts.buffer becomes modified buffer
return buffer.slice(start, end) // removed buffer
}
return modified // modified buffer
}
|
javascript
|
function bufferSplice (buffer, start, count/*, [...items] */) {
var args = assertArgs(arguments, {
buffer: [Buffer, 'object'],
'[start]': 'integer',
'[count]': 'integer',
'[...items]': [Buffer, 'string', 'array', 'object', 'number']
})
defaults(args, {
start: buffer.length,
count: buffer.length,
items: []
})
buffer = args.buffer
start = args.start
count = args.count
var opts
if (!Buffer.isBuffer(buffer)) {
opts = buffer
buffer = opts.buffer
}
var items = args.items.map(castBuffer)
var end = start + count
var modified = Buffer.concat(
[ buffer.slice(0, start) ]
.concat(items)
.concat(buffer.slice(end, buffer.length))
)
if (opts) {
opts.buffer = modified // opts.buffer becomes modified buffer
return buffer.slice(start, end) // removed buffer
}
return modified // modified buffer
}
|
[
"function",
"bufferSplice",
"(",
"buffer",
",",
"start",
",",
"count",
"/*, [...items] */",
")",
"{",
"var",
"args",
"=",
"assertArgs",
"(",
"arguments",
",",
"{",
"buffer",
":",
"[",
"Buffer",
",",
"'object'",
"]",
",",
"'[start]'",
":",
"'integer'",
",",
"'[count]'",
":",
"'integer'",
",",
"'[...items]'",
":",
"[",
"Buffer",
",",
"'string'",
",",
"'array'",
",",
"'object'",
",",
"'number'",
"]",
"}",
")",
"defaults",
"(",
"args",
",",
"{",
"start",
":",
"buffer",
".",
"length",
",",
"count",
":",
"buffer",
".",
"length",
",",
"items",
":",
"[",
"]",
"}",
")",
"buffer",
"=",
"args",
".",
"buffer",
"start",
"=",
"args",
".",
"start",
"count",
"=",
"args",
".",
"count",
"var",
"opts",
"if",
"(",
"!",
"Buffer",
".",
"isBuffer",
"(",
"buffer",
")",
")",
"{",
"opts",
"=",
"buffer",
"buffer",
"=",
"opts",
".",
"buffer",
"}",
"var",
"items",
"=",
"args",
".",
"items",
".",
"map",
"(",
"castBuffer",
")",
"var",
"end",
"=",
"start",
"+",
"count",
"var",
"modified",
"=",
"Buffer",
".",
"concat",
"(",
"[",
"buffer",
".",
"slice",
"(",
"0",
",",
"start",
")",
"]",
".",
"concat",
"(",
"items",
")",
".",
"concat",
"(",
"buffer",
".",
"slice",
"(",
"end",
",",
"buffer",
".",
"length",
")",
")",
")",
"if",
"(",
"opts",
")",
"{",
"opts",
".",
"buffer",
"=",
"modified",
"// opts.buffer becomes modified buffer",
"return",
"buffer",
".",
"slice",
"(",
"start",
",",
"end",
")",
"// removed buffer",
"}",
"return",
"modified",
"// modified buffer",
"}"
] |
Splice a buffer
@param {Buffer|Object} buffer input buffer or object w/ buffer { buffer: ... }
@param {Integer} [start] default: buffer.length
@param {Integer} [count] default: buffer.length
@param {Buffer,String,Number,Object,Array} [...items] items to insert into buffer (will be casted to buffer before insertion)
@return {Buffer} modified buffer
|
[
"Splice",
"a",
"buffer"
] |
dbcfaaf881516b6b9cf4a6b2e144d8a55a4f03f5
|
https://github.com/tjmehta/buffer-splice/blob/dbcfaaf881516b6b9cf4a6b2e144d8a55a4f03f5/index.js#L14-L49
|
38,127 |
bodyno/nunjucks-volt
|
src/transformer.js
|
mapCOW
|
function mapCOW(arr, func) {
var res = null;
for(var i=0; i<arr.length; i++) {
var item = func(arr[i]);
if(item !== arr[i]) {
if(!res) {
res = arr.slice();
}
res[i] = item;
}
}
return res || arr;
}
|
javascript
|
function mapCOW(arr, func) {
var res = null;
for(var i=0; i<arr.length; i++) {
var item = func(arr[i]);
if(item !== arr[i]) {
if(!res) {
res = arr.slice();
}
res[i] = item;
}
}
return res || arr;
}
|
[
"function",
"mapCOW",
"(",
"arr",
",",
"func",
")",
"{",
"var",
"res",
"=",
"null",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"arr",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"item",
"=",
"func",
"(",
"arr",
"[",
"i",
"]",
")",
";",
"if",
"(",
"item",
"!==",
"arr",
"[",
"i",
"]",
")",
"{",
"if",
"(",
"!",
"res",
")",
"{",
"res",
"=",
"arr",
".",
"slice",
"(",
")",
";",
"}",
"res",
"[",
"i",
"]",
"=",
"item",
";",
"}",
"}",
"return",
"res",
"||",
"arr",
";",
"}"
] |
copy-on-write version of map
|
[
"copy",
"-",
"on",
"-",
"write",
"version",
"of",
"map"
] |
a7c0908bf98acc2af497069d7d2701bb880d3323
|
https://github.com/bodyno/nunjucks-volt/blob/a7c0908bf98acc2af497069d7d2701bb880d3323/src/transformer.js#L12-L28
|
38,128 |
adrai/devicestack
|
lib/framehandler.js
|
FrameHandler
|
function FrameHandler(deviceOrFrameHandler) {
var self = this;
// call super class
EventEmitter2.call(this, {
wildcard: true,
delimiter: ':',
maxListeners: 1000 // default would be 10!
});
if (this.log) {
this.log = _.wrap(this.log, function(func, msg) {
func(self.constructor.name + ': ' + msg);
});
} else if (FrameHandler.prototype.log) {
FrameHandler.prototype.log = _.wrap(FrameHandler.prototype.log, function(func, msg) {
func(self.constructor.name + ': ' + msg);
});
this.log = FrameHandler.prototype.log;
} else {
var debug = require('debug')(this.constructor.name);
this.log = function(msg) {
debug(msg);
};
}
this.analyzeInterval = 20;
if (deviceOrFrameHandler) {
this.incomming = [];
deviceOrFrameHandler.on('receive', function (frame) {
var unwrappedFrame;
if (self.analyzeNextFrame) {
self.incomming = self.incomming.concat(Array.prototype.slice.call(frame, 0));
self.trigger();
} else {
if (self.unwrapFrame) {
unwrappedFrame = self.unwrapFrame(_.clone(frame));
if (self.log) self.log('receive unwrapped frame: ' + unwrappedFrame.toHexDebug());
self.emit('receive', unwrappedFrame);
} else {
if (self.log) self.log('receive frame: ' + frame.toHexDebug());
self.emit('receive', frame);
}
}
});
deviceOrFrameHandler.on('close', function() {
if (self.log) self.log('close');
self.emit('close');
self.removeAllListeners();
deviceOrFrameHandler.removeAllListeners();
deviceOrFrameHandler.removeAllListeners('receive');
self.incomming = [];
});
}
this.on('send', function(frame) {
if (self.wrapFrame) {
var wrappedFrame = self.wrapFrame(_.clone(frame));
if (self.log) self.log('send wrapped frame: ' + wrappedFrame.toHexDebug());
deviceOrFrameHandler.send(wrappedFrame);
} else {
if (self.log) self.log('send frame: ' + frame.toHexDebug());
deviceOrFrameHandler.send(frame);
}
});
}
|
javascript
|
function FrameHandler(deviceOrFrameHandler) {
var self = this;
// call super class
EventEmitter2.call(this, {
wildcard: true,
delimiter: ':',
maxListeners: 1000 // default would be 10!
});
if (this.log) {
this.log = _.wrap(this.log, function(func, msg) {
func(self.constructor.name + ': ' + msg);
});
} else if (FrameHandler.prototype.log) {
FrameHandler.prototype.log = _.wrap(FrameHandler.prototype.log, function(func, msg) {
func(self.constructor.name + ': ' + msg);
});
this.log = FrameHandler.prototype.log;
} else {
var debug = require('debug')(this.constructor.name);
this.log = function(msg) {
debug(msg);
};
}
this.analyzeInterval = 20;
if (deviceOrFrameHandler) {
this.incomming = [];
deviceOrFrameHandler.on('receive', function (frame) {
var unwrappedFrame;
if (self.analyzeNextFrame) {
self.incomming = self.incomming.concat(Array.prototype.slice.call(frame, 0));
self.trigger();
} else {
if (self.unwrapFrame) {
unwrappedFrame = self.unwrapFrame(_.clone(frame));
if (self.log) self.log('receive unwrapped frame: ' + unwrappedFrame.toHexDebug());
self.emit('receive', unwrappedFrame);
} else {
if (self.log) self.log('receive frame: ' + frame.toHexDebug());
self.emit('receive', frame);
}
}
});
deviceOrFrameHandler.on('close', function() {
if (self.log) self.log('close');
self.emit('close');
self.removeAllListeners();
deviceOrFrameHandler.removeAllListeners();
deviceOrFrameHandler.removeAllListeners('receive');
self.incomming = [];
});
}
this.on('send', function(frame) {
if (self.wrapFrame) {
var wrappedFrame = self.wrapFrame(_.clone(frame));
if (self.log) self.log('send wrapped frame: ' + wrappedFrame.toHexDebug());
deviceOrFrameHandler.send(wrappedFrame);
} else {
if (self.log) self.log('send frame: ' + frame.toHexDebug());
deviceOrFrameHandler.send(frame);
}
});
}
|
[
"function",
"FrameHandler",
"(",
"deviceOrFrameHandler",
")",
"{",
"var",
"self",
"=",
"this",
";",
"// call super class",
"EventEmitter2",
".",
"call",
"(",
"this",
",",
"{",
"wildcard",
":",
"true",
",",
"delimiter",
":",
"':'",
",",
"maxListeners",
":",
"1000",
"// default would be 10!",
"}",
")",
";",
"if",
"(",
"this",
".",
"log",
")",
"{",
"this",
".",
"log",
"=",
"_",
".",
"wrap",
"(",
"this",
".",
"log",
",",
"function",
"(",
"func",
",",
"msg",
")",
"{",
"func",
"(",
"self",
".",
"constructor",
".",
"name",
"+",
"': '",
"+",
"msg",
")",
";",
"}",
")",
";",
"}",
"else",
"if",
"(",
"FrameHandler",
".",
"prototype",
".",
"log",
")",
"{",
"FrameHandler",
".",
"prototype",
".",
"log",
"=",
"_",
".",
"wrap",
"(",
"FrameHandler",
".",
"prototype",
".",
"log",
",",
"function",
"(",
"func",
",",
"msg",
")",
"{",
"func",
"(",
"self",
".",
"constructor",
".",
"name",
"+",
"': '",
"+",
"msg",
")",
";",
"}",
")",
";",
"this",
".",
"log",
"=",
"FrameHandler",
".",
"prototype",
".",
"log",
";",
"}",
"else",
"{",
"var",
"debug",
"=",
"require",
"(",
"'debug'",
")",
"(",
"this",
".",
"constructor",
".",
"name",
")",
";",
"this",
".",
"log",
"=",
"function",
"(",
"msg",
")",
"{",
"debug",
"(",
"msg",
")",
";",
"}",
";",
"}",
"this",
".",
"analyzeInterval",
"=",
"20",
";",
"if",
"(",
"deviceOrFrameHandler",
")",
"{",
"this",
".",
"incomming",
"=",
"[",
"]",
";",
"deviceOrFrameHandler",
".",
"on",
"(",
"'receive'",
",",
"function",
"(",
"frame",
")",
"{",
"var",
"unwrappedFrame",
";",
"if",
"(",
"self",
".",
"analyzeNextFrame",
")",
"{",
"self",
".",
"incomming",
"=",
"self",
".",
"incomming",
".",
"concat",
"(",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"frame",
",",
"0",
")",
")",
";",
"self",
".",
"trigger",
"(",
")",
";",
"}",
"else",
"{",
"if",
"(",
"self",
".",
"unwrapFrame",
")",
"{",
"unwrappedFrame",
"=",
"self",
".",
"unwrapFrame",
"(",
"_",
".",
"clone",
"(",
"frame",
")",
")",
";",
"if",
"(",
"self",
".",
"log",
")",
"self",
".",
"log",
"(",
"'receive unwrapped frame: '",
"+",
"unwrappedFrame",
".",
"toHexDebug",
"(",
")",
")",
";",
"self",
".",
"emit",
"(",
"'receive'",
",",
"unwrappedFrame",
")",
";",
"}",
"else",
"{",
"if",
"(",
"self",
".",
"log",
")",
"self",
".",
"log",
"(",
"'receive frame: '",
"+",
"frame",
".",
"toHexDebug",
"(",
")",
")",
";",
"self",
".",
"emit",
"(",
"'receive'",
",",
"frame",
")",
";",
"}",
"}",
"}",
")",
";",
"deviceOrFrameHandler",
".",
"on",
"(",
"'close'",
",",
"function",
"(",
")",
"{",
"if",
"(",
"self",
".",
"log",
")",
"self",
".",
"log",
"(",
"'close'",
")",
";",
"self",
".",
"emit",
"(",
"'close'",
")",
";",
"self",
".",
"removeAllListeners",
"(",
")",
";",
"deviceOrFrameHandler",
".",
"removeAllListeners",
"(",
")",
";",
"deviceOrFrameHandler",
".",
"removeAllListeners",
"(",
"'receive'",
")",
";",
"self",
".",
"incomming",
"=",
"[",
"]",
";",
"}",
")",
";",
"}",
"this",
".",
"on",
"(",
"'send'",
",",
"function",
"(",
"frame",
")",
"{",
"if",
"(",
"self",
".",
"wrapFrame",
")",
"{",
"var",
"wrappedFrame",
"=",
"self",
".",
"wrapFrame",
"(",
"_",
".",
"clone",
"(",
"frame",
")",
")",
";",
"if",
"(",
"self",
".",
"log",
")",
"self",
".",
"log",
"(",
"'send wrapped frame: '",
"+",
"wrappedFrame",
".",
"toHexDebug",
"(",
")",
")",
";",
"deviceOrFrameHandler",
".",
"send",
"(",
"wrappedFrame",
")",
";",
"}",
"else",
"{",
"if",
"(",
"self",
".",
"log",
")",
"self",
".",
"log",
"(",
"'send frame: '",
"+",
"frame",
".",
"toHexDebug",
"(",
")",
")",
";",
"deviceOrFrameHandler",
".",
"send",
"(",
"frame",
")",
";",
"}",
"}",
")",
";",
"}"
] |
You can have one or multiple framehandlers.
A framhandler receives data from the upper layer and sends it to the lower layer by wrapping some header or footer information.
A framehandler receives data from lower layer and sends it to the upper layer by unwrapping some header or footer information.
The lowest layer for a framehandler is the device and the topmost ist the connection.
- reacts on send of upper layer, calls wrapFrame function if exists and calls send function on lower layer
- reacts on receive of lower layer, calls unwrapFrame function if exists and emits receive
- automatically calls start function
@param {Device || FrameHandler} deviceOrFrameHandler Device or framahandler object.
|
[
"You",
"can",
"have",
"one",
"or",
"multiple",
"framehandlers",
".",
"A",
"framhandler",
"receives",
"data",
"from",
"the",
"upper",
"layer",
"and",
"sends",
"it",
"to",
"the",
"lower",
"layer",
"by",
"wrapping",
"some",
"header",
"or",
"footer",
"information",
".",
"A",
"framehandler",
"receives",
"data",
"from",
"lower",
"layer",
"and",
"sends",
"it",
"to",
"the",
"upper",
"layer",
"by",
"unwrapping",
"some",
"header",
"or",
"footer",
"information",
".",
"The",
"lowest",
"layer",
"for",
"a",
"framehandler",
"is",
"the",
"device",
"and",
"the",
"topmost",
"ist",
"the",
"connection",
".",
"-",
"reacts",
"on",
"send",
"of",
"upper",
"layer",
"calls",
"wrapFrame",
"function",
"if",
"exists",
"and",
"calls",
"send",
"function",
"on",
"lower",
"layer",
"-",
"reacts",
"on",
"receive",
"of",
"lower",
"layer",
"calls",
"unwrapFrame",
"function",
"if",
"exists",
"and",
"emits",
"receive",
"-",
"automatically",
"calls",
"start",
"function"
] |
c0e20b799b5d3d7b5fbd8f0a3b8ab21c13fcad76
|
https://github.com/adrai/devicestack/blob/c0e20b799b5d3d7b5fbd8f0a3b8ab21c13fcad76/lib/framehandler.js#L16-L83
|
38,129 |
edjafarov/PromisePipe
|
src/linkProcessors/nextEnvProcessor.js
|
isValidTransition
|
function isValidTransition (link, context) {
var isValid = true;
if (!(PromisePipe.envTransitions[context._env] && PromisePipe.envTransitions[context._env][link._env])) {
if (!isSystemTransition(link._env)) {
isValid = false;
}
}
return isValid;
}
|
javascript
|
function isValidTransition (link, context) {
var isValid = true;
if (!(PromisePipe.envTransitions[context._env] && PromisePipe.envTransitions[context._env][link._env])) {
if (!isSystemTransition(link._env)) {
isValid = false;
}
}
return isValid;
}
|
[
"function",
"isValidTransition",
"(",
"link",
",",
"context",
")",
"{",
"var",
"isValid",
"=",
"true",
";",
"if",
"(",
"!",
"(",
"PromisePipe",
".",
"envTransitions",
"[",
"context",
".",
"_env",
"]",
"&&",
"PromisePipe",
".",
"envTransitions",
"[",
"context",
".",
"_env",
"]",
"[",
"link",
".",
"_env",
"]",
")",
")",
"{",
"if",
"(",
"!",
"isSystemTransition",
"(",
"link",
".",
"_env",
")",
")",
"{",
"isValid",
"=",
"false",
";",
"}",
"}",
"return",
"isValid",
";",
"}"
] |
Check valid is transition
|
[
"Check",
"valid",
"is",
"transition"
] |
ec37d5eaab57feadc2e1f5a9f9e7306e32565143
|
https://github.com/edjafarov/PromisePipe/blob/ec37d5eaab57feadc2e1f5a9f9e7306e32565143/src/linkProcessors/nextEnvProcessor.js#L51-L60
|
38,130 |
edjafarov/PromisePipe
|
src/linkProcessors/nextEnvProcessor.js
|
passChains
|
function passChains (first, last, sequence) {
return sequence.map(function (el) {
return el._id;
}).slice(first, last + 1);
}
|
javascript
|
function passChains (first, last, sequence) {
return sequence.map(function (el) {
return el._id;
}).slice(first, last + 1);
}
|
[
"function",
"passChains",
"(",
"first",
",",
"last",
",",
"sequence",
")",
"{",
"return",
"sequence",
".",
"map",
"(",
"function",
"(",
"el",
")",
"{",
"return",
"el",
".",
"_id",
";",
"}",
")",
".",
"slice",
"(",
"first",
",",
"last",
"+",
"1",
")",
";",
"}"
] |
Return filtered list for passing functions
@param {Number} first
@param {Number} last
@return {Array}
|
[
"Return",
"filtered",
"list",
"for",
"passing",
"functions"
] |
ec37d5eaab57feadc2e1f5a9f9e7306e32565143
|
https://github.com/edjafarov/PromisePipe/blob/ec37d5eaab57feadc2e1f5a9f9e7306e32565143/src/linkProcessors/nextEnvProcessor.js#L68-L72
|
38,131 |
edjafarov/PromisePipe
|
src/linkProcessors/nextEnvProcessor.js
|
lastChain
|
function lastChain (first, sequence) {
var index = getIndexOfNextEnvAppearance(first, PromisePipe.env, sequence);
return index === -1 ? (sequence.length - 1) : (index - 1);
}
|
javascript
|
function lastChain (first, sequence) {
var index = getIndexOfNextEnvAppearance(first, PromisePipe.env, sequence);
return index === -1 ? (sequence.length - 1) : (index - 1);
}
|
[
"function",
"lastChain",
"(",
"first",
",",
"sequence",
")",
"{",
"var",
"index",
"=",
"getIndexOfNextEnvAppearance",
"(",
"first",
",",
"PromisePipe",
".",
"env",
",",
"sequence",
")",
";",
"return",
"index",
"===",
"-",
"1",
"?",
"(",
"sequence",
".",
"length",
"-",
"1",
")",
":",
"(",
"index",
"-",
"1",
")",
";",
"}"
] |
Return lastChain index
@param {Number} first
@return {Number}
|
[
"Return",
"lastChain",
"index"
] |
ec37d5eaab57feadc2e1f5a9f9e7306e32565143
|
https://github.com/edjafarov/PromisePipe/blob/ec37d5eaab57feadc2e1f5a9f9e7306e32565143/src/linkProcessors/nextEnvProcessor.js#L79-L82
|
38,132 |
edjafarov/PromisePipe
|
src/linkProcessors/nextEnvProcessor.js
|
getChainIndexById
|
function getChainIndexById(id, sequence){
return sequence.map(function(el){
return el._id;
}).indexOf(id);
}
|
javascript
|
function getChainIndexById(id, sequence){
return sequence.map(function(el){
return el._id;
}).indexOf(id);
}
|
[
"function",
"getChainIndexById",
"(",
"id",
",",
"sequence",
")",
"{",
"return",
"sequence",
".",
"map",
"(",
"function",
"(",
"el",
")",
"{",
"return",
"el",
".",
"_id",
";",
"}",
")",
".",
"indexOf",
"(",
"id",
")",
";",
"}"
] |
Get chain by index
@param {String} id
@param {Array} sequence
|
[
"Get",
"chain",
"by",
"index"
] |
ec37d5eaab57feadc2e1f5a9f9e7306e32565143
|
https://github.com/edjafarov/PromisePipe/blob/ec37d5eaab57feadc2e1f5a9f9e7306e32565143/src/linkProcessors/nextEnvProcessor.js#L89-L93
|
38,133 |
edjafarov/PromisePipe
|
src/linkProcessors/nextEnvProcessor.js
|
getIndexOfNextEnvAppearance
|
function getIndexOfNextEnvAppearance(fromIndex, env, sequence){
return sequence.map(function(el){
return el._env;
}).indexOf(env, fromIndex);
}
|
javascript
|
function getIndexOfNextEnvAppearance(fromIndex, env, sequence){
return sequence.map(function(el){
return el._env;
}).indexOf(env, fromIndex);
}
|
[
"function",
"getIndexOfNextEnvAppearance",
"(",
"fromIndex",
",",
"env",
",",
"sequence",
")",
"{",
"return",
"sequence",
".",
"map",
"(",
"function",
"(",
"el",
")",
"{",
"return",
"el",
".",
"_env",
";",
"}",
")",
".",
"indexOf",
"(",
"env",
",",
"fromIndex",
")",
";",
"}"
] |
Get index of next env appearance
@param {Number} fromIndex
@param {String} env
@return {Number}
|
[
"Get",
"index",
"of",
"next",
"env",
"appearance"
] |
ec37d5eaab57feadc2e1f5a9f9e7306e32565143
|
https://github.com/edjafarov/PromisePipe/blob/ec37d5eaab57feadc2e1f5a9f9e7306e32565143/src/linkProcessors/nextEnvProcessor.js#L101-L105
|
38,134 |
edjafarov/PromisePipe
|
src/linkProcessors/nextEnvProcessor.js
|
rangeChain
|
function rangeChain (id, sequence) {
var first = getChainIndexById(id, sequence);
return [first, lastChain(first, sequence)];
}
|
javascript
|
function rangeChain (id, sequence) {
var first = getChainIndexById(id, sequence);
return [first, lastChain(first, sequence)];
}
|
[
"function",
"rangeChain",
"(",
"id",
",",
"sequence",
")",
"{",
"var",
"first",
"=",
"getChainIndexById",
"(",
"id",
",",
"sequence",
")",
";",
"return",
"[",
"first",
",",
"lastChain",
"(",
"first",
",",
"sequence",
")",
"]",
";",
"}"
] |
Return tuple of chained indexes
@param {Number} id
@return {Tuple}
|
[
"Return",
"tuple",
"of",
"chained",
"indexes"
] |
ec37d5eaab57feadc2e1f5a9f9e7306e32565143
|
https://github.com/edjafarov/PromisePipe/blob/ec37d5eaab57feadc2e1f5a9f9e7306e32565143/src/linkProcessors/nextEnvProcessor.js#L112-L115
|
38,135 |
sirap-group/connect-sequence
|
lib/errors/CustomError.js
|
setMessage
|
function setMessage (msg) {
if (msg && typeof msg === 'string') {
this.message = msg
} else if (this.constructor.name !== 'CustomError') {
this.message = this.constructor.DEFAULT_ERROR_MESSAGE
} else {
this.message = undefined
}
}
|
javascript
|
function setMessage (msg) {
if (msg && typeof msg === 'string') {
this.message = msg
} else if (this.constructor.name !== 'CustomError') {
this.message = this.constructor.DEFAULT_ERROR_MESSAGE
} else {
this.message = undefined
}
}
|
[
"function",
"setMessage",
"(",
"msg",
")",
"{",
"if",
"(",
"msg",
"&&",
"typeof",
"msg",
"===",
"'string'",
")",
"{",
"this",
".",
"message",
"=",
"msg",
"}",
"else",
"if",
"(",
"this",
".",
"constructor",
".",
"name",
"!==",
"'CustomError'",
")",
"{",
"this",
".",
"message",
"=",
"this",
".",
"constructor",
".",
"DEFAULT_ERROR_MESSAGE",
"}",
"else",
"{",
"this",
".",
"message",
"=",
"undefined",
"}",
"}"
] |
Set the error message from the given argument or from the class property DEFAULT_ERROR_MESSAGE
@method
|
[
"Set",
"the",
"error",
"message",
"from",
"the",
"given",
"argument",
"or",
"from",
"the",
"class",
"property",
"DEFAULT_ERROR_MESSAGE"
] |
8b0490d75596107b7c37e2c2cfa4d0486f3eda1a
|
https://github.com/sirap-group/connect-sequence/blob/8b0490d75596107b7c37e2c2cfa4d0486f3eda1a/lib/errors/CustomError.js#L33-L41
|
38,136 |
sirap-group/connect-sequence
|
lib/errors/CustomError.js
|
createStackTrace
|
function createStackTrace () {
var stack = new Error().stack
var splited = stack.split('\n')
var modifiedStack = splited[0].concat('\n', splited.splice(3).join('\n'))
this.stack = modifiedStack
}
|
javascript
|
function createStackTrace () {
var stack = new Error().stack
var splited = stack.split('\n')
var modifiedStack = splited[0].concat('\n', splited.splice(3).join('\n'))
this.stack = modifiedStack
}
|
[
"function",
"createStackTrace",
"(",
")",
"{",
"var",
"stack",
"=",
"new",
"Error",
"(",
")",
".",
"stack",
"var",
"splited",
"=",
"stack",
".",
"split",
"(",
"'\\n'",
")",
"var",
"modifiedStack",
"=",
"splited",
"[",
"0",
"]",
".",
"concat",
"(",
"'\\n'",
",",
"splited",
".",
"splice",
"(",
"3",
")",
".",
"join",
"(",
"'\\n'",
")",
")",
"this",
".",
"stack",
"=",
"modifiedStack",
"}"
] |
Set the the correct stack trace for this error
@method
@returns {undefined}
@throws {PrivateMethodError}
|
[
"Set",
"the",
"the",
"correct",
"stack",
"trace",
"for",
"this",
"error"
] |
8b0490d75596107b7c37e2c2cfa4d0486f3eda1a
|
https://github.com/sirap-group/connect-sequence/blob/8b0490d75596107b7c37e2c2cfa4d0486f3eda1a/lib/errors/CustomError.js#L49-L54
|
38,137 |
adrai/devicestack
|
lib/serial/eventeddeviceloader.js
|
EventedSerialDeviceLoader
|
function EventedSerialDeviceLoader(Device, vendorId, productId) {
// call super class
SerialDeviceLoader.call(this, Device, false);
this.vidPidPairs = [];
if (!productId && _.isArray(vendorId)) {
this.vidPidPairs = vendorId;
} else {
this.vidPidPairs = [{vendorId: vendorId, productId: productId}];
}
}
|
javascript
|
function EventedSerialDeviceLoader(Device, vendorId, productId) {
// call super class
SerialDeviceLoader.call(this, Device, false);
this.vidPidPairs = [];
if (!productId && _.isArray(vendorId)) {
this.vidPidPairs = vendorId;
} else {
this.vidPidPairs = [{vendorId: vendorId, productId: productId}];
}
}
|
[
"function",
"EventedSerialDeviceLoader",
"(",
"Device",
",",
"vendorId",
",",
"productId",
")",
"{",
"// call super class",
"SerialDeviceLoader",
".",
"call",
"(",
"this",
",",
"Device",
",",
"false",
")",
";",
"this",
".",
"vidPidPairs",
"=",
"[",
"]",
";",
"if",
"(",
"!",
"productId",
"&&",
"_",
".",
"isArray",
"(",
"vendorId",
")",
")",
"{",
"this",
".",
"vidPidPairs",
"=",
"vendorId",
";",
"}",
"else",
"{",
"this",
".",
"vidPidPairs",
"=",
"[",
"{",
"vendorId",
":",
"vendorId",
",",
"productId",
":",
"productId",
"}",
"]",
";",
"}",
"}"
] |
An EventedSerialDeviceLoader can check if there are available some serial devices.
@param {Object} Device Device The constructor function of the device.
@param {Number || Array} vendorId The vendor id or an array of vid/pid pairs.
@param {Number} productId The product id or optional.
|
[
"An",
"EventedSerialDeviceLoader",
"can",
"check",
"if",
"there",
"are",
"available",
"some",
"serial",
"devices",
"."
] |
c0e20b799b5d3d7b5fbd8f0a3b8ab21c13fcad76
|
https://github.com/adrai/devicestack/blob/c0e20b799b5d3d7b5fbd8f0a3b8ab21c13fcad76/lib/serial/eventeddeviceloader.js#L12-L24
|
38,138 |
vygis/ng-clamp
|
ng-clamp.js
|
getMaxLines
|
function getMaxLines(height) {
var availHeight = height || element.clientHeight,
lineHeight = getLineHeight(element);
return Math.max(Math.floor(availHeight / lineHeight), 0);
}
|
javascript
|
function getMaxLines(height) {
var availHeight = height || element.clientHeight,
lineHeight = getLineHeight(element);
return Math.max(Math.floor(availHeight / lineHeight), 0);
}
|
[
"function",
"getMaxLines",
"(",
"height",
")",
"{",
"var",
"availHeight",
"=",
"height",
"||",
"element",
".",
"clientHeight",
",",
"lineHeight",
"=",
"getLineHeight",
"(",
"element",
")",
";",
"return",
"Math",
".",
"max",
"(",
"Math",
".",
"floor",
"(",
"availHeight",
"/",
"lineHeight",
")",
",",
"0",
")",
";",
"}"
] |
Returns the maximum number of lines of text that should be rendered based
on the current height of the element and the line-height of the text.
|
[
"Returns",
"the",
"maximum",
"number",
"of",
"lines",
"of",
"text",
"that",
"should",
"be",
"rendered",
"based",
"on",
"the",
"current",
"height",
"of",
"the",
"element",
"and",
"the",
"line",
"-",
"height",
"of",
"the",
"text",
"."
] |
9684b4422d07484a0dcecc0d7aec7ad5ba0ee0fb
|
https://github.com/vygis/ng-clamp/blob/9684b4422d07484a0dcecc0d7aec7ad5ba0ee0fb/ng-clamp.js#L70-L75
|
38,139 |
vygis/ng-clamp
|
ng-clamp.js
|
getLineHeight
|
function getLineHeight(elem) {
var lh = computeStyle(elem, 'line-height');
if (lh == 'normal') {
// Normal line heights vary from browser to browser. The spec recommends
// a value between 1.0 and 1.2 of the font size. Using 1.1 to split the diff.
lh = parseInt(computeStyle(elem, 'font-size')) * 1.2;
}
return parseInt(lh);
}
|
javascript
|
function getLineHeight(elem) {
var lh = computeStyle(elem, 'line-height');
if (lh == 'normal') {
// Normal line heights vary from browser to browser. The spec recommends
// a value between 1.0 and 1.2 of the font size. Using 1.1 to split the diff.
lh = parseInt(computeStyle(elem, 'font-size')) * 1.2;
}
return parseInt(lh);
}
|
[
"function",
"getLineHeight",
"(",
"elem",
")",
"{",
"var",
"lh",
"=",
"computeStyle",
"(",
"elem",
",",
"'line-height'",
")",
";",
"if",
"(",
"lh",
"==",
"'normal'",
")",
"{",
"// Normal line heights vary from browser to browser. The spec recommends",
"// a value between 1.0 and 1.2 of the font size. Using 1.1 to split the diff.",
"lh",
"=",
"parseInt",
"(",
"computeStyle",
"(",
"elem",
",",
"'font-size'",
")",
")",
"*",
"1.2",
";",
"}",
"return",
"parseInt",
"(",
"lh",
")",
";",
"}"
] |
Returns the line-height of an element as an integer.
|
[
"Returns",
"the",
"line",
"-",
"height",
"of",
"an",
"element",
"as",
"an",
"integer",
"."
] |
9684b4422d07484a0dcecc0d7aec7ad5ba0ee0fb
|
https://github.com/vygis/ng-clamp/blob/9684b4422d07484a0dcecc0d7aec7ad5ba0ee0fb/ng-clamp.js#L89-L97
|
38,140 |
vygis/ng-clamp
|
ng-clamp.js
|
getLastChild
|
function getLastChild(elem) {
//Current element has children, need to go deeper and get last child as a text node
if (elem.lastChild.children && elem.lastChild.children.length > 0) {
return getLastChild(Array.prototype.slice.call(elem.children).pop());
}
//This is the absolute last child, a text node, but something's wrong with it. Remove it and keep trying
else if (!elem.lastChild || !elem.lastChild.nodeValue || elem.lastChild.nodeValue === '' || elem.lastChild.nodeValue == opt.truncationChar) {
elem.lastChild.parentNode.removeChild(elem.lastChild);
return getLastChild(element);
}
//This is the last child we want, return it
else {
return elem.lastChild;
}
}
|
javascript
|
function getLastChild(elem) {
//Current element has children, need to go deeper and get last child as a text node
if (elem.lastChild.children && elem.lastChild.children.length > 0) {
return getLastChild(Array.prototype.slice.call(elem.children).pop());
}
//This is the absolute last child, a text node, but something's wrong with it. Remove it and keep trying
else if (!elem.lastChild || !elem.lastChild.nodeValue || elem.lastChild.nodeValue === '' || elem.lastChild.nodeValue == opt.truncationChar) {
elem.lastChild.parentNode.removeChild(elem.lastChild);
return getLastChild(element);
}
//This is the last child we want, return it
else {
return elem.lastChild;
}
}
|
[
"function",
"getLastChild",
"(",
"elem",
")",
"{",
"//Current element has children, need to go deeper and get last child as a text node",
"if",
"(",
"elem",
".",
"lastChild",
".",
"children",
"&&",
"elem",
".",
"lastChild",
".",
"children",
".",
"length",
">",
"0",
")",
"{",
"return",
"getLastChild",
"(",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"elem",
".",
"children",
")",
".",
"pop",
"(",
")",
")",
";",
"}",
"//This is the absolute last child, a text node, but something's wrong with it. Remove it and keep trying",
"else",
"if",
"(",
"!",
"elem",
".",
"lastChild",
"||",
"!",
"elem",
".",
"lastChild",
".",
"nodeValue",
"||",
"elem",
".",
"lastChild",
".",
"nodeValue",
"===",
"''",
"||",
"elem",
".",
"lastChild",
".",
"nodeValue",
"==",
"opt",
".",
"truncationChar",
")",
"{",
"elem",
".",
"lastChild",
".",
"parentNode",
".",
"removeChild",
"(",
"elem",
".",
"lastChild",
")",
";",
"return",
"getLastChild",
"(",
"element",
")",
";",
"}",
"//This is the last child we want, return it",
"else",
"{",
"return",
"elem",
".",
"lastChild",
";",
"}",
"}"
] |
Gets an element's last child. That may be another node or a node's contents.
|
[
"Gets",
"an",
"element",
"s",
"last",
"child",
".",
"That",
"may",
"be",
"another",
"node",
"or",
"a",
"node",
"s",
"contents",
"."
] |
9684b4422d07484a0dcecc0d7aec7ad5ba0ee0fb
|
https://github.com/vygis/ng-clamp/blob/9684b4422d07484a0dcecc0d7aec7ad5ba0ee0fb/ng-clamp.js#L109-L123
|
38,141 |
vygis/ng-clamp
|
ng-clamp.js
|
truncate
|
function truncate(target, maxHeight) {
if (!maxHeight) {
return;
}
/**
* Resets global variables.
*/
function reset() {
splitOnChars = opt.splitOnChars.slice(0);
splitChar = splitOnChars[0];
chunks = null;
lastChunk = null;
}
var nodeValue = target.nodeValue.replace(opt.truncationChar, '');
//Grab the next chunks
if (!chunks) {
//If there are more characters to try, grab the next one
if (splitOnChars.length > 0) {
splitChar = splitOnChars.shift();
}
//No characters to chunk by. Go character-by-character
else {
splitChar = '';
}
chunks = nodeValue.split(splitChar);
}
//If there are chunks left to remove, remove the last one and see if
// the nodeValue fits.
if (chunks.length > 1) {
// console.log('chunks', chunks);
lastChunk = chunks.pop();
// console.log('lastChunk', lastChunk);
applyEllipsis(target, chunks.join(splitChar));
}
//No more chunks can be removed using this character
else {
chunks = null;
}
//Insert the custom HTML before the truncation character
if (truncationHTMLContainer) {
target.nodeValue = target.nodeValue.replace(opt.truncationChar, '');
element.innerHTML = target.nodeValue + ' ' + truncationHTMLContainer.innerHTML + opt.truncationChar;
}
//Search produced valid chunks
if (chunks) {
//It fits
if (element.clientHeight <= maxHeight) {
//There's still more characters to try splitting on, not quite done yet
if (splitOnChars.length >= 0 && splitChar !== '') {
applyEllipsis(target, chunks.join(splitChar) + splitChar + lastChunk);
chunks = null;
}
//Finished!
else {
return element.innerHTML;
}
}
}
//No valid chunks produced
else {
//No valid chunks even when splitting by letter, time to move
//on to the next node
if (splitChar === '') {
applyEllipsis(target, '');
target = getLastChild(element);
reset();
}
}
//If you get here it means still too big, let's keep truncating
if (opt.animate) {
setTimeout(function() {
truncate(target, maxHeight);
}, opt.animate === true ? 10 : opt.animate);
} else {
return truncate(target, maxHeight);
}
}
|
javascript
|
function truncate(target, maxHeight) {
if (!maxHeight) {
return;
}
/**
* Resets global variables.
*/
function reset() {
splitOnChars = opt.splitOnChars.slice(0);
splitChar = splitOnChars[0];
chunks = null;
lastChunk = null;
}
var nodeValue = target.nodeValue.replace(opt.truncationChar, '');
//Grab the next chunks
if (!chunks) {
//If there are more characters to try, grab the next one
if (splitOnChars.length > 0) {
splitChar = splitOnChars.shift();
}
//No characters to chunk by. Go character-by-character
else {
splitChar = '';
}
chunks = nodeValue.split(splitChar);
}
//If there are chunks left to remove, remove the last one and see if
// the nodeValue fits.
if (chunks.length > 1) {
// console.log('chunks', chunks);
lastChunk = chunks.pop();
// console.log('lastChunk', lastChunk);
applyEllipsis(target, chunks.join(splitChar));
}
//No more chunks can be removed using this character
else {
chunks = null;
}
//Insert the custom HTML before the truncation character
if (truncationHTMLContainer) {
target.nodeValue = target.nodeValue.replace(opt.truncationChar, '');
element.innerHTML = target.nodeValue + ' ' + truncationHTMLContainer.innerHTML + opt.truncationChar;
}
//Search produced valid chunks
if (chunks) {
//It fits
if (element.clientHeight <= maxHeight) {
//There's still more characters to try splitting on, not quite done yet
if (splitOnChars.length >= 0 && splitChar !== '') {
applyEllipsis(target, chunks.join(splitChar) + splitChar + lastChunk);
chunks = null;
}
//Finished!
else {
return element.innerHTML;
}
}
}
//No valid chunks produced
else {
//No valid chunks even when splitting by letter, time to move
//on to the next node
if (splitChar === '') {
applyEllipsis(target, '');
target = getLastChild(element);
reset();
}
}
//If you get here it means still too big, let's keep truncating
if (opt.animate) {
setTimeout(function() {
truncate(target, maxHeight);
}, opt.animate === true ? 10 : opt.animate);
} else {
return truncate(target, maxHeight);
}
}
|
[
"function",
"truncate",
"(",
"target",
",",
"maxHeight",
")",
"{",
"if",
"(",
"!",
"maxHeight",
")",
"{",
"return",
";",
"}",
"/**\n * Resets global variables.\n */",
"function",
"reset",
"(",
")",
"{",
"splitOnChars",
"=",
"opt",
".",
"splitOnChars",
".",
"slice",
"(",
"0",
")",
";",
"splitChar",
"=",
"splitOnChars",
"[",
"0",
"]",
";",
"chunks",
"=",
"null",
";",
"lastChunk",
"=",
"null",
";",
"}",
"var",
"nodeValue",
"=",
"target",
".",
"nodeValue",
".",
"replace",
"(",
"opt",
".",
"truncationChar",
",",
"''",
")",
";",
"//Grab the next chunks",
"if",
"(",
"!",
"chunks",
")",
"{",
"//If there are more characters to try, grab the next one",
"if",
"(",
"splitOnChars",
".",
"length",
">",
"0",
")",
"{",
"splitChar",
"=",
"splitOnChars",
".",
"shift",
"(",
")",
";",
"}",
"//No characters to chunk by. Go character-by-character",
"else",
"{",
"splitChar",
"=",
"''",
";",
"}",
"chunks",
"=",
"nodeValue",
".",
"split",
"(",
"splitChar",
")",
";",
"}",
"//If there are chunks left to remove, remove the last one and see if",
"// the nodeValue fits.",
"if",
"(",
"chunks",
".",
"length",
">",
"1",
")",
"{",
"// console.log('chunks', chunks);",
"lastChunk",
"=",
"chunks",
".",
"pop",
"(",
")",
";",
"// console.log('lastChunk', lastChunk);",
"applyEllipsis",
"(",
"target",
",",
"chunks",
".",
"join",
"(",
"splitChar",
")",
")",
";",
"}",
"//No more chunks can be removed using this character",
"else",
"{",
"chunks",
"=",
"null",
";",
"}",
"//Insert the custom HTML before the truncation character",
"if",
"(",
"truncationHTMLContainer",
")",
"{",
"target",
".",
"nodeValue",
"=",
"target",
".",
"nodeValue",
".",
"replace",
"(",
"opt",
".",
"truncationChar",
",",
"''",
")",
";",
"element",
".",
"innerHTML",
"=",
"target",
".",
"nodeValue",
"+",
"' '",
"+",
"truncationHTMLContainer",
".",
"innerHTML",
"+",
"opt",
".",
"truncationChar",
";",
"}",
"//Search produced valid chunks",
"if",
"(",
"chunks",
")",
"{",
"//It fits",
"if",
"(",
"element",
".",
"clientHeight",
"<=",
"maxHeight",
")",
"{",
"//There's still more characters to try splitting on, not quite done yet",
"if",
"(",
"splitOnChars",
".",
"length",
">=",
"0",
"&&",
"splitChar",
"!==",
"''",
")",
"{",
"applyEllipsis",
"(",
"target",
",",
"chunks",
".",
"join",
"(",
"splitChar",
")",
"+",
"splitChar",
"+",
"lastChunk",
")",
";",
"chunks",
"=",
"null",
";",
"}",
"//Finished!",
"else",
"{",
"return",
"element",
".",
"innerHTML",
";",
"}",
"}",
"}",
"//No valid chunks produced",
"else",
"{",
"//No valid chunks even when splitting by letter, time to move",
"//on to the next node",
"if",
"(",
"splitChar",
"===",
"''",
")",
"{",
"applyEllipsis",
"(",
"target",
",",
"''",
")",
";",
"target",
"=",
"getLastChild",
"(",
"element",
")",
";",
"reset",
"(",
")",
";",
"}",
"}",
"//If you get here it means still too big, let's keep truncating",
"if",
"(",
"opt",
".",
"animate",
")",
"{",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"truncate",
"(",
"target",
",",
"maxHeight",
")",
";",
"}",
",",
"opt",
".",
"animate",
"===",
"true",
"?",
"10",
":",
"opt",
".",
"animate",
")",
";",
"}",
"else",
"{",
"return",
"truncate",
"(",
"target",
",",
"maxHeight",
")",
";",
"}",
"}"
] |
Removes one character at a time from the text until its width or
height is beneath the passed-in max param.
|
[
"Removes",
"one",
"character",
"at",
"a",
"time",
"from",
"the",
"text",
"until",
"its",
"width",
"or",
"height",
"is",
"beneath",
"the",
"passed",
"-",
"in",
"max",
"param",
"."
] |
9684b4422d07484a0dcecc0d7aec7ad5ba0ee0fb
|
https://github.com/vygis/ng-clamp/blob/9684b4422d07484a0dcecc0d7aec7ad5ba0ee0fb/ng-clamp.js#L129-L214
|
38,142 |
vygis/ng-clamp
|
ng-clamp.js
|
reset
|
function reset() {
splitOnChars = opt.splitOnChars.slice(0);
splitChar = splitOnChars[0];
chunks = null;
lastChunk = null;
}
|
javascript
|
function reset() {
splitOnChars = opt.splitOnChars.slice(0);
splitChar = splitOnChars[0];
chunks = null;
lastChunk = null;
}
|
[
"function",
"reset",
"(",
")",
"{",
"splitOnChars",
"=",
"opt",
".",
"splitOnChars",
".",
"slice",
"(",
"0",
")",
";",
"splitChar",
"=",
"splitOnChars",
"[",
"0",
"]",
";",
"chunks",
"=",
"null",
";",
"lastChunk",
"=",
"null",
";",
"}"
] |
Resets global variables.
|
[
"Resets",
"global",
"variables",
"."
] |
9684b4422d07484a0dcecc0d7aec7ad5ba0ee0fb
|
https://github.com/vygis/ng-clamp/blob/9684b4422d07484a0dcecc0d7aec7ad5ba0ee0fb/ng-clamp.js#L137-L142
|
38,143 |
iranreyes/gsap-promisify
|
index.js
|
_animateFunc
|
function _animateFunc(func, element, duration, opts) {
opts = Object.assign({}, opts);
var tween;
return new Promise(function(resolve, reject, onCancel) {
opts.onComplete = resolve;
tween = func(element, duration, opts);
onCancel &&
onCancel(function() {
tween.kill();
});
});
}
|
javascript
|
function _animateFunc(func, element, duration, opts) {
opts = Object.assign({}, opts);
var tween;
return new Promise(function(resolve, reject, onCancel) {
opts.onComplete = resolve;
tween = func(element, duration, opts);
onCancel &&
onCancel(function() {
tween.kill();
});
});
}
|
[
"function",
"_animateFunc",
"(",
"func",
",",
"element",
",",
"duration",
",",
"opts",
")",
"{",
"opts",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"opts",
")",
";",
"var",
"tween",
";",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
",",
"onCancel",
")",
"{",
"opts",
".",
"onComplete",
"=",
"resolve",
";",
"tween",
"=",
"func",
"(",
"element",
",",
"duration",
",",
"opts",
")",
";",
"onCancel",
"&&",
"onCancel",
"(",
"function",
"(",
")",
"{",
"tween",
".",
"kill",
"(",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Animate specific functions inside the TweenModules, like TweenLite.to
@param {Function} func - TweenModule.to
@param {DOMElement} element - DOM Element
@param {number} duration - Duration
@param {Object} opts - Paramaters
@returns
|
[
"Animate",
"specific",
"functions",
"inside",
"the",
"TweenModules",
"like",
"TweenLite",
".",
"to"
] |
8f52438793f37678d257f1b68495961fb7ea4d92
|
https://github.com/iranreyes/gsap-promisify/blob/8f52438793f37678d257f1b68495961fb7ea4d92/index.js#L10-L21
|
38,144 |
iranreyes/gsap-promisify
|
index.js
|
animate
|
function animate(Promise, TweenModule) {
var animateTo = _animateFunc.bind(null, TweenModule.to);
var util = animateTo;
util.to = animateTo;
util.from = _animateFunc.bind(null, TweenModule.from);
util.set = function animateSet(element, params) {
params = Object.assign({}, params);
return new Promise(function(resolve, reject) {
params.onComplete = resolve;
TweenModule.set(element, params);
});
};
util.fromTo = function animateFromTo(element, duration, from, to) {
to = Object.assign({}, to);
var tween;
return new Promise(function(resolve, reject, onCancel) {
to.onComplete = resolve;
tween = TweenModule.fromTo(element, duration, from, to);
onCancel &&
onCancel(function() {
tween.kill();
});
});
};
util.killTweensOf = TweenModule.killTweensOf.bind(TweenModule);
util.all = Promise.all;
return util;
}
|
javascript
|
function animate(Promise, TweenModule) {
var animateTo = _animateFunc.bind(null, TweenModule.to);
var util = animateTo;
util.to = animateTo;
util.from = _animateFunc.bind(null, TweenModule.from);
util.set = function animateSet(element, params) {
params = Object.assign({}, params);
return new Promise(function(resolve, reject) {
params.onComplete = resolve;
TweenModule.set(element, params);
});
};
util.fromTo = function animateFromTo(element, duration, from, to) {
to = Object.assign({}, to);
var tween;
return new Promise(function(resolve, reject, onCancel) {
to.onComplete = resolve;
tween = TweenModule.fromTo(element, duration, from, to);
onCancel &&
onCancel(function() {
tween.kill();
});
});
};
util.killTweensOf = TweenModule.killTweensOf.bind(TweenModule);
util.all = Promise.all;
return util;
}
|
[
"function",
"animate",
"(",
"Promise",
",",
"TweenModule",
")",
"{",
"var",
"animateTo",
"=",
"_animateFunc",
".",
"bind",
"(",
"null",
",",
"TweenModule",
".",
"to",
")",
";",
"var",
"util",
"=",
"animateTo",
";",
"util",
".",
"to",
"=",
"animateTo",
";",
"util",
".",
"from",
"=",
"_animateFunc",
".",
"bind",
"(",
"null",
",",
"TweenModule",
".",
"from",
")",
";",
"util",
".",
"set",
"=",
"function",
"animateSet",
"(",
"element",
",",
"params",
")",
"{",
"params",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"params",
")",
";",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"params",
".",
"onComplete",
"=",
"resolve",
";",
"TweenModule",
".",
"set",
"(",
"element",
",",
"params",
")",
";",
"}",
")",
";",
"}",
";",
"util",
".",
"fromTo",
"=",
"function",
"animateFromTo",
"(",
"element",
",",
"duration",
",",
"from",
",",
"to",
")",
"{",
"to",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"to",
")",
";",
"var",
"tween",
";",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
",",
"onCancel",
")",
"{",
"to",
".",
"onComplete",
"=",
"resolve",
";",
"tween",
"=",
"TweenModule",
".",
"fromTo",
"(",
"element",
",",
"duration",
",",
"from",
",",
"to",
")",
";",
"onCancel",
"&&",
"onCancel",
"(",
"function",
"(",
")",
"{",
"tween",
".",
"kill",
"(",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
";",
"util",
".",
"killTweensOf",
"=",
"TweenModule",
".",
"killTweensOf",
".",
"bind",
"(",
"TweenModule",
")",
";",
"util",
".",
"all",
"=",
"Promise",
".",
"all",
";",
"return",
"util",
";",
"}"
] |
Get a wrapper of GSAP Tween
@param {Promise} Promise - Promise framework
@param {TweenModule} TweenModule - TweenMax or TweenLite
@returns {Object} GSAP Promisified
|
[
"Get",
"a",
"wrapper",
"of",
"GSAP",
"Tween"
] |
8f52438793f37678d257f1b68495961fb7ea4d92
|
https://github.com/iranreyes/gsap-promisify/blob/8f52438793f37678d257f1b68495961fb7ea4d92/index.js#L30-L61
|
38,145 |
bodyno/nunjucks-volt
|
src/compiler.js
|
binOpEmitter
|
function binOpEmitter(str) {
return function(node, frame) {
this.compile(node.left, frame);
this.emit(str);
this.compile(node.right, frame);
};
}
|
javascript
|
function binOpEmitter(str) {
return function(node, frame) {
this.compile(node.left, frame);
this.emit(str);
this.compile(node.right, frame);
};
}
|
[
"function",
"binOpEmitter",
"(",
"str",
")",
"{",
"return",
"function",
"(",
"node",
",",
"frame",
")",
"{",
"this",
".",
"compile",
"(",
"node",
".",
"left",
",",
"frame",
")",
";",
"this",
".",
"emit",
"(",
"str",
")",
";",
"this",
".",
"compile",
"(",
"node",
".",
"right",
",",
"frame",
")",
";",
"}",
";",
"}"
] |
A common pattern is to emit binary operators
|
[
"A",
"common",
"pattern",
"is",
"to",
"emit",
"binary",
"operators"
] |
a7c0908bf98acc2af497069d7d2701bb880d3323
|
https://github.com/bodyno/nunjucks-volt/blob/a7c0908bf98acc2af497069d7d2701bb880d3323/src/compiler.js#L23-L29
|
38,146 |
mercmobily/simpleDeclare
|
declare.js
|
function( fn ){
// Get the object's base
var objectBase = getObjectBase( this, fn );
// If the function is not found anywhere in the prototype chain
// there is a pretty big problem
if( ! objectBase.base ) throw new Error( "inherited coun't find method in chain (getInherited)" );
// At this point, I know the key. To look for the super method, I
// only have to check if one of the parent __proto__ has a matching key `k`
var p = Object.getPrototypeOf( objectBase.base );
return p[ objectBase.key ];
}
|
javascript
|
function( fn ){
// Get the object's base
var objectBase = getObjectBase( this, fn );
// If the function is not found anywhere in the prototype chain
// there is a pretty big problem
if( ! objectBase.base ) throw new Error( "inherited coun't find method in chain (getInherited)" );
// At this point, I know the key. To look for the super method, I
// only have to check if one of the parent __proto__ has a matching key `k`
var p = Object.getPrototypeOf( objectBase.base );
return p[ objectBase.key ];
}
|
[
"function",
"(",
"fn",
")",
"{",
"// Get the object's base",
"var",
"objectBase",
"=",
"getObjectBase",
"(",
"this",
",",
"fn",
")",
";",
"// If the function is not found anywhere in the prototype chain",
"// there is a pretty big problem",
"if",
"(",
"!",
"objectBase",
".",
"base",
")",
"throw",
"new",
"Error",
"(",
"\"inherited coun't find method in chain (getInherited)\"",
")",
";",
"// At this point, I know the key. To look for the super method, I",
"// only have to check if one of the parent __proto__ has a matching key `k`",
"var",
"p",
"=",
"Object",
".",
"getPrototypeOf",
"(",
"objectBase",
".",
"base",
")",
";",
"return",
"p",
"[",
"objectBase",
".",
"key",
"]",
";",
"}"
] |
This will become a method call, so `this` is the object
|
[
"This",
"will",
"become",
"a",
"method",
"call",
"so",
"this",
"is",
"the",
"object"
] |
1a8ed54f0e7eca6133c95e293e8770ef26382187
|
https://github.com/mercmobily/simpleDeclare/blob/1a8ed54f0e7eca6133c95e293e8770ef26382187/declare.js#L45-L58
|
|
38,147 |
mercmobily/simpleDeclare
|
declare.js
|
function(){
// These will be worked out from `arguments`
var SuperCtorList, protoMixin;
var MixedClass, ResultClass;
var list = [];
var i, l, ii, ll;
var proto;
var r = workoutDeclareArguments( arguments );
SuperCtorList = r.SuperCtorList;
protoMixin = r.protoMixin;
// No parameters: inheriting from Object directly, no multiple inheritance
if( SuperCtorList.length === 0 ){
MixedClass = Object;
}
// Only one parameter: straght single inheritance.
else if( SuperCtorList.length === 1 ){
MixedClass = SuperCtorList[ 0 ];
// More than one parameter: multiple inheritance at work
// MixedClass will end up being an artificially made constructor
// where the prototype chain is the sum of _every_ prototype in
// every element of SuperCtorList (taking out duplicates)
} else {
MixedClass = Object;
// NOW:
// Go through every __proto__ of every derivative class, and augment
// MixedClass by inheriting from A COPY OF each one of them.
list = [];
for( i = 0, l = SuperCtorList.length; i < l; i ++ ){
// Get the prototype list, in the right order
// (the reversed discovery order)
// The result will be placed in `subList`
var subList = [];
if( typeof SuperCtorList[ i ] === 'undefined' || typeof SuperCtorList[ i ].prototype === 'undefined'){
throw new Error("Invalid constructor!")
}
proto = SuperCtorList[ i ].prototype;
while( proto ){
if( proto.constructor !== Object ) subList.push( proto );
proto = Object.getPrototypeOf( proto );
}
subList = subList.reverse();
// Add each element of sublist as long as it's not already in the main `list`
for( ii = 0, ll = subList.length; ii < ll; ii ++ ){
if( ! constructorAlreadyInList( subList[ ii ].constructor, list ) ) list.push( subList[ ii ] );
}
}
// For each element in the prototype list that isn't Object(),
// augment MixedClass with a copy of the new prototype
for( ii = 0, ll = list.length; ii < ll; ii ++ ){
proto = list[ ii ];
var M = MixedClass;
if( proto.constructor !== Object ){
MixedClass = makeConstructor( MixedClass, proto, proto.constructor );
copyClassMethods( M, MixedClass ); // Methods previously inherited
copyClassMethods( proto.constructor, MixedClass ); // Extra methods from the father constructor
}
}
}
// Finally, inherit from the MixedClass, and add
// class methods over
// MixedClass might be:
// * Object (coming from no inheritance),
// * SuperCtorList[0] (coming from single inheritance)
// * A constructor with the appropriate prototype chain (multiple inheritance)
ResultClass = makeConstructor( MixedClass, protoMixin );
copyClassMethods( MixedClass, ResultClass );
// Add getInherited, inherited() and inheritedAsync() to the prototype
// (only if they are not already there)
if( ! ResultClass.prototype.getInherited ) {
ResultClass.prototype.getInherited = getInherited;
}
if( ! ResultClass.prototype.inherited ) {
ResultClass.prototype.inherited = makeInheritedFunction( 'sync' );
}
if( ! ResultClass.prototype.inheritedAsync ) {
ResultClass.prototype.inheritedAsync = makeInheritedFunction( 'async' );
}
// Add instanceOf
if( ! ResultClass.prototype.instanceOf ) {
ResultClass.prototype.instanceOf = instanceOf;
}
// Add class-wide method `extend`
ResultClass.extend = function(){
return extend.apply( this, arguments );
};
// That's it!
return ResultClass;
}
|
javascript
|
function(){
// These will be worked out from `arguments`
var SuperCtorList, protoMixin;
var MixedClass, ResultClass;
var list = [];
var i, l, ii, ll;
var proto;
var r = workoutDeclareArguments( arguments );
SuperCtorList = r.SuperCtorList;
protoMixin = r.protoMixin;
// No parameters: inheriting from Object directly, no multiple inheritance
if( SuperCtorList.length === 0 ){
MixedClass = Object;
}
// Only one parameter: straght single inheritance.
else if( SuperCtorList.length === 1 ){
MixedClass = SuperCtorList[ 0 ];
// More than one parameter: multiple inheritance at work
// MixedClass will end up being an artificially made constructor
// where the prototype chain is the sum of _every_ prototype in
// every element of SuperCtorList (taking out duplicates)
} else {
MixedClass = Object;
// NOW:
// Go through every __proto__ of every derivative class, and augment
// MixedClass by inheriting from A COPY OF each one of them.
list = [];
for( i = 0, l = SuperCtorList.length; i < l; i ++ ){
// Get the prototype list, in the right order
// (the reversed discovery order)
// The result will be placed in `subList`
var subList = [];
if( typeof SuperCtorList[ i ] === 'undefined' || typeof SuperCtorList[ i ].prototype === 'undefined'){
throw new Error("Invalid constructor!")
}
proto = SuperCtorList[ i ].prototype;
while( proto ){
if( proto.constructor !== Object ) subList.push( proto );
proto = Object.getPrototypeOf( proto );
}
subList = subList.reverse();
// Add each element of sublist as long as it's not already in the main `list`
for( ii = 0, ll = subList.length; ii < ll; ii ++ ){
if( ! constructorAlreadyInList( subList[ ii ].constructor, list ) ) list.push( subList[ ii ] );
}
}
// For each element in the prototype list that isn't Object(),
// augment MixedClass with a copy of the new prototype
for( ii = 0, ll = list.length; ii < ll; ii ++ ){
proto = list[ ii ];
var M = MixedClass;
if( proto.constructor !== Object ){
MixedClass = makeConstructor( MixedClass, proto, proto.constructor );
copyClassMethods( M, MixedClass ); // Methods previously inherited
copyClassMethods( proto.constructor, MixedClass ); // Extra methods from the father constructor
}
}
}
// Finally, inherit from the MixedClass, and add
// class methods over
// MixedClass might be:
// * Object (coming from no inheritance),
// * SuperCtorList[0] (coming from single inheritance)
// * A constructor with the appropriate prototype chain (multiple inheritance)
ResultClass = makeConstructor( MixedClass, protoMixin );
copyClassMethods( MixedClass, ResultClass );
// Add getInherited, inherited() and inheritedAsync() to the prototype
// (only if they are not already there)
if( ! ResultClass.prototype.getInherited ) {
ResultClass.prototype.getInherited = getInherited;
}
if( ! ResultClass.prototype.inherited ) {
ResultClass.prototype.inherited = makeInheritedFunction( 'sync' );
}
if( ! ResultClass.prototype.inheritedAsync ) {
ResultClass.prototype.inheritedAsync = makeInheritedFunction( 'async' );
}
// Add instanceOf
if( ! ResultClass.prototype.instanceOf ) {
ResultClass.prototype.instanceOf = instanceOf;
}
// Add class-wide method `extend`
ResultClass.extend = function(){
return extend.apply( this, arguments );
};
// That's it!
return ResultClass;
}
|
[
"function",
"(",
")",
"{",
"// These will be worked out from `arguments`",
"var",
"SuperCtorList",
",",
"protoMixin",
";",
"var",
"MixedClass",
",",
"ResultClass",
";",
"var",
"list",
"=",
"[",
"]",
";",
"var",
"i",
",",
"l",
",",
"ii",
",",
"ll",
";",
"var",
"proto",
";",
"var",
"r",
"=",
"workoutDeclareArguments",
"(",
"arguments",
")",
";",
"SuperCtorList",
"=",
"r",
".",
"SuperCtorList",
";",
"protoMixin",
"=",
"r",
".",
"protoMixin",
";",
"// No parameters: inheriting from Object directly, no multiple inheritance",
"if",
"(",
"SuperCtorList",
".",
"length",
"===",
"0",
")",
"{",
"MixedClass",
"=",
"Object",
";",
"}",
"// Only one parameter: straght single inheritance.",
"else",
"if",
"(",
"SuperCtorList",
".",
"length",
"===",
"1",
")",
"{",
"MixedClass",
"=",
"SuperCtorList",
"[",
"0",
"]",
";",
"// More than one parameter: multiple inheritance at work",
"// MixedClass will end up being an artificially made constructor",
"// where the prototype chain is the sum of _every_ prototype in",
"// every element of SuperCtorList (taking out duplicates)",
"}",
"else",
"{",
"MixedClass",
"=",
"Object",
";",
"// NOW:",
"// Go through every __proto__ of every derivative class, and augment",
"// MixedClass by inheriting from A COPY OF each one of them.",
"list",
"=",
"[",
"]",
";",
"for",
"(",
"i",
"=",
"0",
",",
"l",
"=",
"SuperCtorList",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"// Get the prototype list, in the right order",
"// (the reversed discovery order)",
"// The result will be placed in `subList`",
"var",
"subList",
"=",
"[",
"]",
";",
"if",
"(",
"typeof",
"SuperCtorList",
"[",
"i",
"]",
"===",
"'undefined'",
"||",
"typeof",
"SuperCtorList",
"[",
"i",
"]",
".",
"prototype",
"===",
"'undefined'",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Invalid constructor!\"",
")",
"}",
"proto",
"=",
"SuperCtorList",
"[",
"i",
"]",
".",
"prototype",
";",
"while",
"(",
"proto",
")",
"{",
"if",
"(",
"proto",
".",
"constructor",
"!==",
"Object",
")",
"subList",
".",
"push",
"(",
"proto",
")",
";",
"proto",
"=",
"Object",
".",
"getPrototypeOf",
"(",
"proto",
")",
";",
"}",
"subList",
"=",
"subList",
".",
"reverse",
"(",
")",
";",
"// Add each element of sublist as long as it's not already in the main `list`",
"for",
"(",
"ii",
"=",
"0",
",",
"ll",
"=",
"subList",
".",
"length",
";",
"ii",
"<",
"ll",
";",
"ii",
"++",
")",
"{",
"if",
"(",
"!",
"constructorAlreadyInList",
"(",
"subList",
"[",
"ii",
"]",
".",
"constructor",
",",
"list",
")",
")",
"list",
".",
"push",
"(",
"subList",
"[",
"ii",
"]",
")",
";",
"}",
"}",
"// For each element in the prototype list that isn't Object(),",
"// augment MixedClass with a copy of the new prototype",
"for",
"(",
"ii",
"=",
"0",
",",
"ll",
"=",
"list",
".",
"length",
";",
"ii",
"<",
"ll",
";",
"ii",
"++",
")",
"{",
"proto",
"=",
"list",
"[",
"ii",
"]",
";",
"var",
"M",
"=",
"MixedClass",
";",
"if",
"(",
"proto",
".",
"constructor",
"!==",
"Object",
")",
"{",
"MixedClass",
"=",
"makeConstructor",
"(",
"MixedClass",
",",
"proto",
",",
"proto",
".",
"constructor",
")",
";",
"copyClassMethods",
"(",
"M",
",",
"MixedClass",
")",
";",
"// Methods previously inherited",
"copyClassMethods",
"(",
"proto",
".",
"constructor",
",",
"MixedClass",
")",
";",
"// Extra methods from the father constructor",
"}",
"}",
"}",
"// Finally, inherit from the MixedClass, and add",
"// class methods over",
"// MixedClass might be:",
"// * Object (coming from no inheritance),",
"// * SuperCtorList[0] (coming from single inheritance)",
"// * A constructor with the appropriate prototype chain (multiple inheritance)",
"ResultClass",
"=",
"makeConstructor",
"(",
"MixedClass",
",",
"protoMixin",
")",
";",
"copyClassMethods",
"(",
"MixedClass",
",",
"ResultClass",
")",
";",
"// Add getInherited, inherited() and inheritedAsync() to the prototype",
"// (only if they are not already there)",
"if",
"(",
"!",
"ResultClass",
".",
"prototype",
".",
"getInherited",
")",
"{",
"ResultClass",
".",
"prototype",
".",
"getInherited",
"=",
"getInherited",
";",
"}",
"if",
"(",
"!",
"ResultClass",
".",
"prototype",
".",
"inherited",
")",
"{",
"ResultClass",
".",
"prototype",
".",
"inherited",
"=",
"makeInheritedFunction",
"(",
"'sync'",
")",
";",
"}",
"if",
"(",
"!",
"ResultClass",
".",
"prototype",
".",
"inheritedAsync",
")",
"{",
"ResultClass",
".",
"prototype",
".",
"inheritedAsync",
"=",
"makeInheritedFunction",
"(",
"'async'",
")",
";",
"}",
"// Add instanceOf",
"if",
"(",
"!",
"ResultClass",
".",
"prototype",
".",
"instanceOf",
")",
"{",
"ResultClass",
".",
"prototype",
".",
"instanceOf",
"=",
"instanceOf",
";",
"}",
"// Add class-wide method `extend`",
"ResultClass",
".",
"extend",
"=",
"function",
"(",
")",
"{",
"return",
"extend",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"}",
";",
"// That's it!",
"return",
"ResultClass",
";",
"}"
] |
Parameters are very variable
|
[
"Parameters",
"are",
"very",
"variable"
] |
1a8ed54f0e7eca6133c95e293e8770ef26382187
|
https://github.com/mercmobily/simpleDeclare/blob/1a8ed54f0e7eca6133c95e293e8770ef26382187/declare.js#L328-L436
|
|
38,148 |
crysalead-js/dom-layer
|
examples/input/js/inputs.js
|
elementType
|
function elementType(element) {
var name = element.nodeName.toLowerCase();
if (name !== "input") {
if (name === "select" && element.multiple) {
return "select-multiple";
}
return name;
}
var type = element.getAttribute('type');
if (!type) {
return "text";
}
return type.toLowerCase();
}
|
javascript
|
function elementType(element) {
var name = element.nodeName.toLowerCase();
if (name !== "input") {
if (name === "select" && element.multiple) {
return "select-multiple";
}
return name;
}
var type = element.getAttribute('type');
if (!type) {
return "text";
}
return type.toLowerCase();
}
|
[
"function",
"elementType",
"(",
"element",
")",
"{",
"var",
"name",
"=",
"element",
".",
"nodeName",
".",
"toLowerCase",
"(",
")",
";",
"if",
"(",
"name",
"!==",
"\"input\"",
")",
"{",
"if",
"(",
"name",
"===",
"\"select\"",
"&&",
"element",
".",
"multiple",
")",
"{",
"return",
"\"select-multiple\"",
";",
"}",
"return",
"name",
";",
"}",
"var",
"type",
"=",
"element",
".",
"getAttribute",
"(",
"'type'",
")",
";",
"if",
"(",
"!",
"type",
")",
"{",
"return",
"\"text\"",
";",
"}",
"return",
"type",
".",
"toLowerCase",
"(",
")",
";",
"}"
] |
Returns the type of a DOM element.
@param Object element A DOM element.
@return String The DOM element type.
|
[
"Returns",
"the",
"type",
"of",
"a",
"DOM",
"element",
"."
] |
0c3509fe1b6c4cd2ce0c030b73791f951f5f97a2
|
https://github.com/crysalead-js/dom-layer/blob/0c3509fe1b6c4cd2ce0c030b73791f951f5f97a2/examples/input/js/inputs.js#L13-L26
|
38,149 |
crysalead-js/dom-layer
|
examples/input/js/inputs.js
|
getValue
|
function getValue(element) {
var name = elementType(element);
switch (name) {
case "checkbox":
case "radio":
if (!element.checked) {
return false;
}
var val = element.getAttribute('value');
return val == null ? true : val;
case "select":
case "select-multiple":
var options = element.options;
var values = [];
for (var i = 0, len = options.length; i < len; i++) {
if (options[i].selected) {
values.push(options[i].value);
}
}
return name === "select-multiple" ? values : values[0];
default:
return element.value;
}
}
|
javascript
|
function getValue(element) {
var name = elementType(element);
switch (name) {
case "checkbox":
case "radio":
if (!element.checked) {
return false;
}
var val = element.getAttribute('value');
return val == null ? true : val;
case "select":
case "select-multiple":
var options = element.options;
var values = [];
for (var i = 0, len = options.length; i < len; i++) {
if (options[i].selected) {
values.push(options[i].value);
}
}
return name === "select-multiple" ? values : values[0];
default:
return element.value;
}
}
|
[
"function",
"getValue",
"(",
"element",
")",
"{",
"var",
"name",
"=",
"elementType",
"(",
"element",
")",
";",
"switch",
"(",
"name",
")",
"{",
"case",
"\"checkbox\"",
":",
"case",
"\"radio\"",
":",
"if",
"(",
"!",
"element",
".",
"checked",
")",
"{",
"return",
"false",
";",
"}",
"var",
"val",
"=",
"element",
".",
"getAttribute",
"(",
"'value'",
")",
";",
"return",
"val",
"==",
"null",
"?",
"true",
":",
"val",
";",
"case",
"\"select\"",
":",
"case",
"\"select-multiple\"",
":",
"var",
"options",
"=",
"element",
".",
"options",
";",
"var",
"values",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"options",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"if",
"(",
"options",
"[",
"i",
"]",
".",
"selected",
")",
"{",
"values",
".",
"push",
"(",
"options",
"[",
"i",
"]",
".",
"value",
")",
";",
"}",
"}",
"return",
"name",
"===",
"\"select-multiple\"",
"?",
"values",
":",
"values",
"[",
"0",
"]",
";",
"default",
":",
"return",
"element",
".",
"value",
";",
"}",
"}"
] |
Gets DOM element value.
@param Object element A DOM element
@return mixed The DOM element value
|
[
"Gets",
"DOM",
"element",
"value",
"."
] |
0c3509fe1b6c4cd2ce0c030b73791f951f5f97a2
|
https://github.com/crysalead-js/dom-layer/blob/0c3509fe1b6c4cd2ce0c030b73791f951f5f97a2/examples/input/js/inputs.js#L34-L57
|
38,150 |
hswolff/activity-logger
|
index.js
|
getActivity
|
function getActivity(activityId) {
var activity = activities[activityId];
if (activity === undefined) {
throw new Error('activity with id "' + activityId + '" not found.');
}
return activity;
}
|
javascript
|
function getActivity(activityId) {
var activity = activities[activityId];
if (activity === undefined) {
throw new Error('activity with id "' + activityId + '" not found.');
}
return activity;
}
|
[
"function",
"getActivity",
"(",
"activityId",
")",
"{",
"var",
"activity",
"=",
"activities",
"[",
"activityId",
"]",
";",
"if",
"(",
"activity",
"===",
"undefined",
")",
"{",
"throw",
"new",
"Error",
"(",
"'activity with id \"'",
"+",
"activityId",
"+",
"'\" not found.'",
")",
";",
"}",
"return",
"activity",
";",
"}"
] |
The Activity object.
@typedef {{
id: number,
message: string,
timestamps: Array.<number>
}} Activity
Get an Activity object if it exists. Throws if it doesn't exist.
@param {number} activityId Activity id.
@return {Activity}
|
[
"The",
"Activity",
"object",
"."
] |
e3997da2f8705aff488ac1be0b26a7fee7d4661f
|
https://github.com/hswolff/activity-logger/blob/e3997da2f8705aff488ac1be0b26a7fee7d4661f/index.js#L56-L64
|
38,151 |
hswolff/activity-logger
|
index.js
|
writeActivity
|
function writeActivity(template, activity) {
if (!enabled) {
return;
}
var handlers = outputHandlers.get();
if (handlers.length === 0) {
throw new Error('No output handlers defined.');
}
handlers.forEach(function(handler) {
handler(template(activity));
});
}
|
javascript
|
function writeActivity(template, activity) {
if (!enabled) {
return;
}
var handlers = outputHandlers.get();
if (handlers.length === 0) {
throw new Error('No output handlers defined.');
}
handlers.forEach(function(handler) {
handler(template(activity));
});
}
|
[
"function",
"writeActivity",
"(",
"template",
",",
"activity",
")",
"{",
"if",
"(",
"!",
"enabled",
")",
"{",
"return",
";",
"}",
"var",
"handlers",
"=",
"outputHandlers",
".",
"get",
"(",
")",
";",
"if",
"(",
"handlers",
".",
"length",
"===",
"0",
")",
"{",
"throw",
"new",
"Error",
"(",
"'No output handlers defined.'",
")",
";",
"}",
"handlers",
".",
"forEach",
"(",
"function",
"(",
"handler",
")",
"{",
"handler",
"(",
"template",
"(",
"activity",
")",
")",
";",
"}",
")",
";",
"}"
] |
Outputs the activity message to all defined handlers.
@param {Function} template Template to use to format the message.
@param {Activity} activity Activity object.
|
[
"Outputs",
"the",
"activity",
"message",
"to",
"all",
"defined",
"handlers",
"."
] |
e3997da2f8705aff488ac1be0b26a7fee7d4661f
|
https://github.com/hswolff/activity-logger/blob/e3997da2f8705aff488ac1be0b26a7fee7d4661f/index.js#L71-L85
|
38,152 |
hswolff/activity-logger
|
index.js
|
createActivity
|
function createActivity(activityMessage) {
if (activityMessage === undefined ||
activityMessage === undefined ||
typeof activityMessage !== 'string') {
throw new Error('Creating a new activity requires an activity message.');
}
var activityId = uuid++;
var activity = {
id: activityId,
message: activityMessage,
timestamps: []
};
activities[activityId] = activity;
return activityId;
}
|
javascript
|
function createActivity(activityMessage) {
if (activityMessage === undefined ||
activityMessage === undefined ||
typeof activityMessage !== 'string') {
throw new Error('Creating a new activity requires an activity message.');
}
var activityId = uuid++;
var activity = {
id: activityId,
message: activityMessage,
timestamps: []
};
activities[activityId] = activity;
return activityId;
}
|
[
"function",
"createActivity",
"(",
"activityMessage",
")",
"{",
"if",
"(",
"activityMessage",
"===",
"undefined",
"||",
"activityMessage",
"===",
"undefined",
"||",
"typeof",
"activityMessage",
"!==",
"'string'",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Creating a new activity requires an activity message.'",
")",
";",
"}",
"var",
"activityId",
"=",
"uuid",
"++",
";",
"var",
"activity",
"=",
"{",
"id",
":",
"activityId",
",",
"message",
":",
"activityMessage",
",",
"timestamps",
":",
"[",
"]",
"}",
";",
"activities",
"[",
"activityId",
"]",
"=",
"activity",
";",
"return",
"activityId",
";",
"}"
] |
Create a new Activity object with its own unique ID. Does not start the
activity.
@param {string} activityMessage The activity message to use.
@return {number} Activity ID.
|
[
"Create",
"a",
"new",
"Activity",
"object",
"with",
"its",
"own",
"unique",
"ID",
".",
"Does",
"not",
"start",
"the",
"activity",
"."
] |
e3997da2f8705aff488ac1be0b26a7fee7d4661f
|
https://github.com/hswolff/activity-logger/blob/e3997da2f8705aff488ac1be0b26a7fee7d4661f/index.js#L93-L110
|
38,153 |
hswolff/activity-logger
|
index.js
|
markActivity
|
function markActivity(activityId) {
var activity = getActivity(activityId);
var timeNow = Date.now();
activity.timestamps.push(timeNow);
return timeNow;
}
|
javascript
|
function markActivity(activityId) {
var activity = getActivity(activityId);
var timeNow = Date.now();
activity.timestamps.push(timeNow);
return timeNow;
}
|
[
"function",
"markActivity",
"(",
"activityId",
")",
"{",
"var",
"activity",
"=",
"getActivity",
"(",
"activityId",
")",
";",
"var",
"timeNow",
"=",
"Date",
".",
"now",
"(",
")",
";",
"activity",
".",
"timestamps",
".",
"push",
"(",
"timeNow",
")",
";",
"return",
"timeNow",
";",
"}"
] |
Mark a timestamp in an activity. Adds it to the array of timestamps.
@param {number} activityId Activity ID.
@return {number} The timestamp value added.
|
[
"Mark",
"a",
"timestamp",
"in",
"an",
"activity",
".",
"Adds",
"it",
"to",
"the",
"array",
"of",
"timestamps",
"."
] |
e3997da2f8705aff488ac1be0b26a7fee7d4661f
|
https://github.com/hswolff/activity-logger/blob/e3997da2f8705aff488ac1be0b26a7fee7d4661f/index.js#L118-L123
|
38,154 |
hswolff/activity-logger
|
index.js
|
startActivity
|
function startActivity(activityMessage) {
var activityId = createActivity(activityMessage);
markActivity(activityId);
var activity = getActivity(activityId);
writeActivity(activityEvents.start, activity);
return activityId;
}
|
javascript
|
function startActivity(activityMessage) {
var activityId = createActivity(activityMessage);
markActivity(activityId);
var activity = getActivity(activityId);
writeActivity(activityEvents.start, activity);
return activityId;
}
|
[
"function",
"startActivity",
"(",
"activityMessage",
")",
"{",
"var",
"activityId",
"=",
"createActivity",
"(",
"activityMessage",
")",
";",
"markActivity",
"(",
"activityId",
")",
";",
"var",
"activity",
"=",
"getActivity",
"(",
"activityId",
")",
";",
"writeActivity",
"(",
"activityEvents",
".",
"start",
",",
"activity",
")",
";",
"return",
"activityId",
";",
"}"
] |
Create and start a new activity.
@param {string} activityMessage Message to use for activity.
@return {number} Activity id.
|
[
"Create",
"and",
"start",
"a",
"new",
"activity",
"."
] |
e3997da2f8705aff488ac1be0b26a7fee7d4661f
|
https://github.com/hswolff/activity-logger/blob/e3997da2f8705aff488ac1be0b26a7fee7d4661f/index.js#L143-L152
|
38,155 |
hswolff/activity-logger
|
index.js
|
endActivity
|
function endActivity(activityId) {
markActivity(activityId);
var activity = destroyActivity(activityId)
writeActivity(activityEvents.end, activity);
return activity;
}
|
javascript
|
function endActivity(activityId) {
markActivity(activityId);
var activity = destroyActivity(activityId)
writeActivity(activityEvents.end, activity);
return activity;
}
|
[
"function",
"endActivity",
"(",
"activityId",
")",
"{",
"markActivity",
"(",
"activityId",
")",
";",
"var",
"activity",
"=",
"destroyActivity",
"(",
"activityId",
")",
"writeActivity",
"(",
"activityEvents",
".",
"end",
",",
"activity",
")",
";",
"return",
"activity",
";",
"}"
] |
End an activity. Log the time, write output, and then delete activity.
@param {number} activityId Activity ID.
@return {Activity} Return the ended activity.
|
[
"End",
"an",
"activity",
".",
"Log",
"the",
"time",
"write",
"output",
"and",
"then",
"delete",
"activity",
"."
] |
e3997da2f8705aff488ac1be0b26a7fee7d4661f
|
https://github.com/hswolff/activity-logger/blob/e3997da2f8705aff488ac1be0b26a7fee7d4661f/index.js#L160-L168
|
38,156 |
kmi/node-red-contrib-jsonpath
|
jsonpath/node-red-contrib-jsonpath.js
|
JSONPathNode
|
function JSONPathNode(n) {
// Create a RED node
RED.nodes.createNode(this,n);
// Store local copies of the node configuration (as defined in the .html)
this.expression = n.expression;
this.split = n.split;
var node = this;
this.on("input", function(msg) {
if ( msg.hasOwnProperty("payload") ) {
var input = msg.payload;
if (typeof msg.payload === "string") {
// It's a string: parse it as JSON
try {
input = JSON.parse(msg.payload);
} catch (e) {
node.warn("The message received is not JSON. Ignoring it.");
return;
}
}
// Evalute the JSONPath expresssion
var evalResult = jsonPath.eval(input, node.expression);
if (!node.split) {
// Batch it in one message. Carry pre-existing properties
msg.payload = evalResult;
node.send(msg);
} else {
// Send one message per match result
var response = evalResult.map(function (value) {
return {"payload": value};
});
node.send([response]);
}
}
});
this.on("close", function() {
// Called when the node is shutdown - eg on redeploy.
// Allows ports to be closed, connections dropped etc.
// eg: this.client.disconnect();
});
}
|
javascript
|
function JSONPathNode(n) {
// Create a RED node
RED.nodes.createNode(this,n);
// Store local copies of the node configuration (as defined in the .html)
this.expression = n.expression;
this.split = n.split;
var node = this;
this.on("input", function(msg) {
if ( msg.hasOwnProperty("payload") ) {
var input = msg.payload;
if (typeof msg.payload === "string") {
// It's a string: parse it as JSON
try {
input = JSON.parse(msg.payload);
} catch (e) {
node.warn("The message received is not JSON. Ignoring it.");
return;
}
}
// Evalute the JSONPath expresssion
var evalResult = jsonPath.eval(input, node.expression);
if (!node.split) {
// Batch it in one message. Carry pre-existing properties
msg.payload = evalResult;
node.send(msg);
} else {
// Send one message per match result
var response = evalResult.map(function (value) {
return {"payload": value};
});
node.send([response]);
}
}
});
this.on("close", function() {
// Called when the node is shutdown - eg on redeploy.
// Allows ports to be closed, connections dropped etc.
// eg: this.client.disconnect();
});
}
|
[
"function",
"JSONPathNode",
"(",
"n",
")",
"{",
"// Create a RED node",
"RED",
".",
"nodes",
".",
"createNode",
"(",
"this",
",",
"n",
")",
";",
"// Store local copies of the node configuration (as defined in the .html)",
"this",
".",
"expression",
"=",
"n",
".",
"expression",
";",
"this",
".",
"split",
"=",
"n",
".",
"split",
";",
"var",
"node",
"=",
"this",
";",
"this",
".",
"on",
"(",
"\"input\"",
",",
"function",
"(",
"msg",
")",
"{",
"if",
"(",
"msg",
".",
"hasOwnProperty",
"(",
"\"payload\"",
")",
")",
"{",
"var",
"input",
"=",
"msg",
".",
"payload",
";",
"if",
"(",
"typeof",
"msg",
".",
"payload",
"===",
"\"string\"",
")",
"{",
"// It's a string: parse it as JSON",
"try",
"{",
"input",
"=",
"JSON",
".",
"parse",
"(",
"msg",
".",
"payload",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"node",
".",
"warn",
"(",
"\"The message received is not JSON. Ignoring it.\"",
")",
";",
"return",
";",
"}",
"}",
"// Evalute the JSONPath expresssion",
"var",
"evalResult",
"=",
"jsonPath",
".",
"eval",
"(",
"input",
",",
"node",
".",
"expression",
")",
";",
"if",
"(",
"!",
"node",
".",
"split",
")",
"{",
"// Batch it in one message. Carry pre-existing properties",
"msg",
".",
"payload",
"=",
"evalResult",
";",
"node",
".",
"send",
"(",
"msg",
")",
";",
"}",
"else",
"{",
"// Send one message per match result",
"var",
"response",
"=",
"evalResult",
".",
"map",
"(",
"function",
"(",
"value",
")",
"{",
"return",
"{",
"\"payload\"",
":",
"value",
"}",
";",
"}",
")",
";",
"node",
".",
"send",
"(",
"[",
"response",
"]",
")",
";",
"}",
"}",
"}",
")",
";",
"this",
".",
"on",
"(",
"\"close\"",
",",
"function",
"(",
")",
"{",
"// Called when the node is shutdown - eg on redeploy.",
"// Allows ports to be closed, connections dropped etc.",
"// eg: this.client.disconnect();",
"}",
")",
";",
"}"
] |
The main node definition - most things happen in here
|
[
"The",
"main",
"node",
"definition",
"-",
"most",
"things",
"happen",
"in",
"here"
] |
6db0d1ffaa069e31b37b52fe8a4b420b5bdfe257
|
https://github.com/kmi/node-red-contrib-jsonpath/blob/6db0d1ffaa069e31b37b52fe8a4b420b5bdfe257/jsonpath/node-red-contrib-jsonpath.js#L28-L73
|
38,157 |
shakefu/template-js
|
index.js
|
Template
|
function Template (filename, context) {
// Save the context for reuse in sub-templates
this.context = context || {}
this.context.include = this.render.bind(this)
this.context.forEach = forEach
// Save the filename for the initial render
this.filename = filename
// Create a cache so we only read files once
this.cache = {}
}
|
javascript
|
function Template (filename, context) {
// Save the context for reuse in sub-templates
this.context = context || {}
this.context.include = this.render.bind(this)
this.context.forEach = forEach
// Save the filename for the initial render
this.filename = filename
// Create a cache so we only read files once
this.cache = {}
}
|
[
"function",
"Template",
"(",
"filename",
",",
"context",
")",
"{",
"// Save the context for reuse in sub-templates",
"this",
".",
"context",
"=",
"context",
"||",
"{",
"}",
"this",
".",
"context",
".",
"include",
"=",
"this",
".",
"render",
".",
"bind",
"(",
"this",
")",
"this",
".",
"context",
".",
"forEach",
"=",
"forEach",
"// Save the filename for the initial render",
"this",
".",
"filename",
"=",
"filename",
"// Create a cache so we only read files once",
"this",
".",
"cache",
"=",
"{",
"}",
"}"
] |
Template class for reusable contexts and cached files.
|
[
"Template",
"class",
"for",
"reusable",
"contexts",
"and",
"cached",
"files",
"."
] |
9f336df6f88c5250bc5880d8dc45dac2f46fe2e0
|
https://github.com/shakefu/template-js/blob/9f336df6f88c5250bc5880d8dc45dac2f46fe2e0/index.js#L20-L31
|
38,158 |
adrai/devicestack
|
lib/serial/deviceguider.js
|
SerialDeviceGuider
|
function SerialDeviceGuider(deviceLoader) {
var self = this;
// call super class
DeviceGuider.call(this, deviceLoader);
this.currentState.getDeviceByPort = function(port) {
return _.find(self.currentState.plugged, function(d) {
return d.get('portName') && port && d.get('portName').toLowerCase() === port.toLowerCase();
});
};
this.currentState.getConnectedDeviceByPort = function(port) {
return _.find(self.currentState.connected, function(d) {
return d.get('portName') && port && d.get('portName').toLowerCase() === port.toLowerCase();
});
};
}
|
javascript
|
function SerialDeviceGuider(deviceLoader) {
var self = this;
// call super class
DeviceGuider.call(this, deviceLoader);
this.currentState.getDeviceByPort = function(port) {
return _.find(self.currentState.plugged, function(d) {
return d.get('portName') && port && d.get('portName').toLowerCase() === port.toLowerCase();
});
};
this.currentState.getConnectedDeviceByPort = function(port) {
return _.find(self.currentState.connected, function(d) {
return d.get('portName') && port && d.get('portName').toLowerCase() === port.toLowerCase();
});
};
}
|
[
"function",
"SerialDeviceGuider",
"(",
"deviceLoader",
")",
"{",
"var",
"self",
"=",
"this",
";",
"// call super class",
"DeviceGuider",
".",
"call",
"(",
"this",
",",
"deviceLoader",
")",
";",
"this",
".",
"currentState",
".",
"getDeviceByPort",
"=",
"function",
"(",
"port",
")",
"{",
"return",
"_",
".",
"find",
"(",
"self",
".",
"currentState",
".",
"plugged",
",",
"function",
"(",
"d",
")",
"{",
"return",
"d",
".",
"get",
"(",
"'portName'",
")",
"&&",
"port",
"&&",
"d",
".",
"get",
"(",
"'portName'",
")",
".",
"toLowerCase",
"(",
")",
"===",
"port",
".",
"toLowerCase",
"(",
")",
";",
"}",
")",
";",
"}",
";",
"this",
".",
"currentState",
".",
"getConnectedDeviceByPort",
"=",
"function",
"(",
"port",
")",
"{",
"return",
"_",
".",
"find",
"(",
"self",
".",
"currentState",
".",
"connected",
",",
"function",
"(",
"d",
")",
"{",
"return",
"d",
".",
"get",
"(",
"'portName'",
")",
"&&",
"port",
"&&",
"d",
".",
"get",
"(",
"'portName'",
")",
".",
"toLowerCase",
"(",
")",
"===",
"port",
".",
"toLowerCase",
"(",
")",
";",
"}",
")",
";",
"}",
";",
"}"
] |
A serialdeviceguider emits 'plug' for new attached serial devices,
'unplug' for removed serial devices, emits 'connect' for connected serial devices
and emits 'disconnect' for disconnected serial devices.
@param {SerialDeviceLoader} deviceLoader The deviceloader object.
|
[
"A",
"serialdeviceguider",
"emits",
"plug",
"for",
"new",
"attached",
"serial",
"devices",
"unplug",
"for",
"removed",
"serial",
"devices",
"emits",
"connect",
"for",
"connected",
"serial",
"devices",
"and",
"emits",
"disconnect",
"for",
"disconnected",
"serial",
"devices",
"."
] |
c0e20b799b5d3d7b5fbd8f0a3b8ab21c13fcad76
|
https://github.com/adrai/devicestack/blob/c0e20b799b5d3d7b5fbd8f0a3b8ab21c13fcad76/lib/serial/deviceguider.js#L12-L29
|
38,159 |
NotNinja/nevis
|
src/hash-code/context.js
|
HashCodeContext
|
function HashCodeContext(value, hashCode, options) {
if (options == null) {
options = {};
}
/**
* A reference to {@link Nevis.hashCode} which can be called within a {@link HashCodeGenerator}.
*
* @private
* @type {Function}
*/
this._hashCode = hashCode;
/**
* The options to be used to generate the hash code for the value.
*
* @public
* @type {Nevis~HashCodeOptions}
*/
this.options = {
allowCache: options.allowCache !== false,
filterProperty: options.filterProperty != null ? options.filterProperty : function() {
return true;
},
ignoreHashCode: Boolean(options.ignoreHashCode),
ignoreInherited: Boolean(options.ignoreInherited),
ignoreMethods: Boolean(options.ignoreMethods)
};
/**
* The string representation of the value whose hash code is to be generated.
*
* This is generated using <code>Object.prototype.toString</code> and is intended to be primarily used for more
* specific type-checking.
*
* @public
* @type {string}
*/
this.string = Object.prototype.toString.call(value);
/**
* The type of the value whose hash code is to be generated.
*
* This is generated using <code>typeof</code> and is intended to be primarily used for simple type-checking.
*
* @public
* @type {string}
*/
this.type = typeof value;
/**
* The value whose hash code is to be generated.
*
* @public
* @type {*}
*/
this.value = value;
}
|
javascript
|
function HashCodeContext(value, hashCode, options) {
if (options == null) {
options = {};
}
/**
* A reference to {@link Nevis.hashCode} which can be called within a {@link HashCodeGenerator}.
*
* @private
* @type {Function}
*/
this._hashCode = hashCode;
/**
* The options to be used to generate the hash code for the value.
*
* @public
* @type {Nevis~HashCodeOptions}
*/
this.options = {
allowCache: options.allowCache !== false,
filterProperty: options.filterProperty != null ? options.filterProperty : function() {
return true;
},
ignoreHashCode: Boolean(options.ignoreHashCode),
ignoreInherited: Boolean(options.ignoreInherited),
ignoreMethods: Boolean(options.ignoreMethods)
};
/**
* The string representation of the value whose hash code is to be generated.
*
* This is generated using <code>Object.prototype.toString</code> and is intended to be primarily used for more
* specific type-checking.
*
* @public
* @type {string}
*/
this.string = Object.prototype.toString.call(value);
/**
* The type of the value whose hash code is to be generated.
*
* This is generated using <code>typeof</code> and is intended to be primarily used for simple type-checking.
*
* @public
* @type {string}
*/
this.type = typeof value;
/**
* The value whose hash code is to be generated.
*
* @public
* @type {*}
*/
this.value = value;
}
|
[
"function",
"HashCodeContext",
"(",
"value",
",",
"hashCode",
",",
"options",
")",
"{",
"if",
"(",
"options",
"==",
"null",
")",
"{",
"options",
"=",
"{",
"}",
";",
"}",
"/**\n * A reference to {@link Nevis.hashCode} which can be called within a {@link HashCodeGenerator}.\n *\n * @private\n * @type {Function}\n */",
"this",
".",
"_hashCode",
"=",
"hashCode",
";",
"/**\n * The options to be used to generate the hash code for the value.\n *\n * @public\n * @type {Nevis~HashCodeOptions}\n */",
"this",
".",
"options",
"=",
"{",
"allowCache",
":",
"options",
".",
"allowCache",
"!==",
"false",
",",
"filterProperty",
":",
"options",
".",
"filterProperty",
"!=",
"null",
"?",
"options",
".",
"filterProperty",
":",
"function",
"(",
")",
"{",
"return",
"true",
";",
"}",
",",
"ignoreHashCode",
":",
"Boolean",
"(",
"options",
".",
"ignoreHashCode",
")",
",",
"ignoreInherited",
":",
"Boolean",
"(",
"options",
".",
"ignoreInherited",
")",
",",
"ignoreMethods",
":",
"Boolean",
"(",
"options",
".",
"ignoreMethods",
")",
"}",
";",
"/**\n * The string representation of the value whose hash code is to be generated.\n *\n * This is generated using <code>Object.prototype.toString</code> and is intended to be primarily used for more\n * specific type-checking.\n *\n * @public\n * @type {string}\n */",
"this",
".",
"string",
"=",
"Object",
".",
"prototype",
".",
"toString",
".",
"call",
"(",
"value",
")",
";",
"/**\n * The type of the value whose hash code is to be generated.\n *\n * This is generated using <code>typeof</code> and is intended to be primarily used for simple type-checking.\n *\n * @public\n * @type {string}\n */",
"this",
".",
"type",
"=",
"typeof",
"value",
";",
"/**\n * The value whose hash code is to be generated.\n *\n * @public\n * @type {*}\n */",
"this",
".",
"value",
"=",
"value",
";",
"}"
] |
Contains the value for which a hash code is to be generated as well string representation and type of the value which
can be checked elsewhere for type-checking etc.
@param {*} value - the value whose hash code is to be generated
@param {Function} hashCode - a reference to {@link Nevis.hashCode} which can be called within a
{@link HashCodeGenerator}
@param {?Nevis~HashCodeOptions} options - the options to be used (may be <code>null</code>)
@protected
@constructor
|
[
"Contains",
"the",
"value",
"for",
"which",
"a",
"hash",
"code",
"is",
"to",
"be",
"generated",
"as",
"well",
"string",
"representation",
"and",
"type",
"of",
"the",
"value",
"which",
"can",
"be",
"checked",
"elsewhere",
"for",
"type",
"-",
"checking",
"etc",
"."
] |
1885e154e6e52d8d3eb307da9f27ed591bac455c
|
https://github.com/NotNinja/nevis/blob/1885e154e6e52d8d3eb307da9f27ed591bac455c/src/hash-code/context.js#L36-L93
|
38,160 |
nknapp/thought
|
lib/init.js
|
checkPackageJsonInGit
|
function checkPackageJsonInGit () {
return exec('git', ['status', '--porcelain', 'package.json'])
.then(function ([stdout, stderr]) {
debug('git status --porcelain package.json', 'stdout', stdout, 'stderr', stderr)
if (stdout.indexOf('package.json') >= 0) {
throw new Error('package.json has changes!\n' +
'I would like to add scripts to your package.json, but ' +
'there are changes that have not been commited yet.\n' +
'I don\'t want to damage anything, so I\'m not doing anyhting right now. ' +
'Please commit your package.json')
}
})
}
|
javascript
|
function checkPackageJsonInGit () {
return exec('git', ['status', '--porcelain', 'package.json'])
.then(function ([stdout, stderr]) {
debug('git status --porcelain package.json', 'stdout', stdout, 'stderr', stderr)
if (stdout.indexOf('package.json') >= 0) {
throw new Error('package.json has changes!\n' +
'I would like to add scripts to your package.json, but ' +
'there are changes that have not been commited yet.\n' +
'I don\'t want to damage anything, so I\'m not doing anyhting right now. ' +
'Please commit your package.json')
}
})
}
|
[
"function",
"checkPackageJsonInGit",
"(",
")",
"{",
"return",
"exec",
"(",
"'git'",
",",
"[",
"'status'",
",",
"'--porcelain'",
",",
"'package.json'",
"]",
")",
".",
"then",
"(",
"function",
"(",
"[",
"stdout",
",",
"stderr",
"]",
")",
"{",
"debug",
"(",
"'git status --porcelain package.json'",
",",
"'stdout'",
",",
"stdout",
",",
"'stderr'",
",",
"stderr",
")",
"if",
"(",
"stdout",
".",
"indexOf",
"(",
"'package.json'",
")",
">=",
"0",
")",
"{",
"throw",
"new",
"Error",
"(",
"'package.json has changes!\\n'",
"+",
"'I would like to add scripts to your package.json, but '",
"+",
"'there are changes that have not been commited yet.\\n'",
"+",
"'I don\\'t want to damage anything, so I\\'m not doing anyhting right now. '",
"+",
"'Please commit your package.json'",
")",
"}",
"}",
")",
"}"
] |
Ensure that package.json is checked in and unmodified
@return {Promise<boolean>} true, if everything is fine
|
[
"Ensure",
"that",
"package",
".",
"json",
"is",
"checked",
"in",
"and",
"unmodified"
] |
2ae991f2d3065ff4eae4df544d20787b07be5116
|
https://github.com/nknapp/thought/blob/2ae991f2d3065ff4eae4df544d20787b07be5116/lib/init.js#L49-L61
|
38,161 |
mongodb-js/index-model
|
lib/fetch.js
|
combineStatsAndIndexes
|
function combineStatsAndIndexes(done, results) {
var indexes = results.getIndexes;
var stats = results.getIndexStats;
var sizes = results.getIndexSizes;
_.each(indexes, function(idx, i) {
_.assign(indexes[i], stats[idx.name]);
_.assign(indexes[i], sizes[idx.name]);
});
done(null, indexes);
}
|
javascript
|
function combineStatsAndIndexes(done, results) {
var indexes = results.getIndexes;
var stats = results.getIndexStats;
var sizes = results.getIndexSizes;
_.each(indexes, function(idx, i) {
_.assign(indexes[i], stats[idx.name]);
_.assign(indexes[i], sizes[idx.name]);
});
done(null, indexes);
}
|
[
"function",
"combineStatsAndIndexes",
"(",
"done",
",",
"results",
")",
"{",
"var",
"indexes",
"=",
"results",
".",
"getIndexes",
";",
"var",
"stats",
"=",
"results",
".",
"getIndexStats",
";",
"var",
"sizes",
"=",
"results",
".",
"getIndexSizes",
";",
"_",
".",
"each",
"(",
"indexes",
",",
"function",
"(",
"idx",
",",
"i",
")",
"{",
"_",
".",
"assign",
"(",
"indexes",
"[",
"i",
"]",
",",
"stats",
"[",
"idx",
".",
"name",
"]",
")",
";",
"_",
".",
"assign",
"(",
"indexes",
"[",
"i",
"]",
",",
"sizes",
"[",
"idx",
".",
"name",
"]",
")",
";",
"}",
")",
";",
"done",
"(",
"null",
",",
"indexes",
")",
";",
"}"
] |
merge all information together for each index
@param {Function} done callback
@param {object} results results from async.auto
|
[
"merge",
"all",
"information",
"together",
"for",
"each",
"index"
] |
43c878440e79299ee104b36d55c06aff63d8cf63
|
https://github.com/mongodb-js/index-model/blob/43c878440e79299ee104b36d55c06aff63d8cf63/lib/fetch.js#L125-L134
|
38,162 |
mlaanderson/database-js-postgres
|
index.js
|
OpenConnection
|
function OpenConnection(connection) {
let base = new pg.Client({
host: connection.Hostname || 'localhost',
port: parseInt(connection.Port) || 5432,
user: connection.Username,
password: connection.Password,
database: connection.Database
});
base.connect();
return new PostgreSQL(base);
}
|
javascript
|
function OpenConnection(connection) {
let base = new pg.Client({
host: connection.Hostname || 'localhost',
port: parseInt(connection.Port) || 5432,
user: connection.Username,
password: connection.Password,
database: connection.Database
});
base.connect();
return new PostgreSQL(base);
}
|
[
"function",
"OpenConnection",
"(",
"connection",
")",
"{",
"let",
"base",
"=",
"new",
"pg",
".",
"Client",
"(",
"{",
"host",
":",
"connection",
".",
"Hostname",
"||",
"'localhost'",
",",
"port",
":",
"parseInt",
"(",
"connection",
".",
"Port",
")",
"||",
"5432",
",",
"user",
":",
"connection",
".",
"Username",
",",
"password",
":",
"connection",
".",
"Password",
",",
"database",
":",
"connection",
".",
"Database",
"}",
")",
";",
"base",
".",
"connect",
"(",
")",
";",
"return",
"new",
"PostgreSQL",
"(",
"base",
")",
";",
"}"
] |
Opens a connection
@param {{Hostname: string, Port: number, Username: string, Password: string, Database: string}} connection
@returns {PostgreSQL}
|
[
"Opens",
"a",
"connection"
] |
241d657f905f7f38113e230c84b4f7c14b234a65
|
https://github.com/mlaanderson/database-js-postgres/blob/241d657f905f7f38113e230c84b4f7c14b234a65/index.js#L123-L133
|
38,163 |
edjafarov/PromisePipe
|
example/PPRouter/adapters/ExpressAdapter.js
|
function(renderData){
var renderArr = Object.keys(renderData).map(function(mask){
return {
mask: mask,
context: renderData[mask].context,
component: renderData[mask].component,
params: renderData[mask].params,
data: renderData[mask].data
}
})
function renderComp(renderArr){
var partial = renderArr.shift();
if(renderArr.length > 0) partial.params.children = [renderComp(renderArr)];
partial.params.mask = partial.mask;
partial.params.data = partial.data;
partial.params.context = partial.context;
if(!partial.component) {
var result = partial.data || '';
if(partial.params.children && partial.params.children[0]) result +=partial.params.children[0];
return result;
}
return partial.component(partial.params)
}
return renderComp(renderArr);
}
|
javascript
|
function(renderData){
var renderArr = Object.keys(renderData).map(function(mask){
return {
mask: mask,
context: renderData[mask].context,
component: renderData[mask].component,
params: renderData[mask].params,
data: renderData[mask].data
}
})
function renderComp(renderArr){
var partial = renderArr.shift();
if(renderArr.length > 0) partial.params.children = [renderComp(renderArr)];
partial.params.mask = partial.mask;
partial.params.data = partial.data;
partial.params.context = partial.context;
if(!partial.component) {
var result = partial.data || '';
if(partial.params.children && partial.params.children[0]) result +=partial.params.children[0];
return result;
}
return partial.component(partial.params)
}
return renderComp(renderArr);
}
|
[
"function",
"(",
"renderData",
")",
"{",
"var",
"renderArr",
"=",
"Object",
".",
"keys",
"(",
"renderData",
")",
".",
"map",
"(",
"function",
"(",
"mask",
")",
"{",
"return",
"{",
"mask",
":",
"mask",
",",
"context",
":",
"renderData",
"[",
"mask",
"]",
".",
"context",
",",
"component",
":",
"renderData",
"[",
"mask",
"]",
".",
"component",
",",
"params",
":",
"renderData",
"[",
"mask",
"]",
".",
"params",
",",
"data",
":",
"renderData",
"[",
"mask",
"]",
".",
"data",
"}",
"}",
")",
"function",
"renderComp",
"(",
"renderArr",
")",
"{",
"var",
"partial",
"=",
"renderArr",
".",
"shift",
"(",
")",
";",
"if",
"(",
"renderArr",
".",
"length",
">",
"0",
")",
"partial",
".",
"params",
".",
"children",
"=",
"[",
"renderComp",
"(",
"renderArr",
")",
"]",
";",
"partial",
".",
"params",
".",
"mask",
"=",
"partial",
".",
"mask",
";",
"partial",
".",
"params",
".",
"data",
"=",
"partial",
".",
"data",
";",
"partial",
".",
"params",
".",
"context",
"=",
"partial",
".",
"context",
";",
"if",
"(",
"!",
"partial",
".",
"component",
")",
"{",
"var",
"result",
"=",
"partial",
".",
"data",
"||",
"''",
";",
"if",
"(",
"partial",
".",
"params",
".",
"children",
"&&",
"partial",
".",
"params",
".",
"children",
"[",
"0",
"]",
")",
"result",
"+=",
"partial",
".",
"params",
".",
"children",
"[",
"0",
"]",
";",
"return",
"result",
";",
"}",
"return",
"partial",
".",
"component",
"(",
"partial",
".",
"params",
")",
"}",
"return",
"renderComp",
"(",
"renderArr",
")",
";",
"}"
] |
renderData is a hash of data, params, and component per resolved part of url
|
[
"renderData",
"is",
"a",
"hash",
"of",
"data",
"params",
"and",
"component",
"per",
"resolved",
"part",
"of",
"url"
] |
ec37d5eaab57feadc2e1f5a9f9e7306e32565143
|
https://github.com/edjafarov/PromisePipe/blob/ec37d5eaab57feadc2e1f5a9f9e7306e32565143/example/PPRouter/adapters/ExpressAdapter.js#L6-L34
|
|
38,164 |
adrai/devicestack
|
lib/deviceloader.js
|
DeviceLoader
|
function DeviceLoader() {
var self = this;
// call super class
EventEmitter2.call(this, {
wildcard: true,
delimiter: ':',
maxListeners: 1000 // default would be 10!
});
if (this.log) {
this.log = _.wrap(this.log, function(func, msg) {
func(self.constructor.name + ': ' + msg);
});
} else if (DeviceLoader.prototype.log) {
DeviceLoader.prototype.log = _.wrap(DeviceLoader.prototype.log, function(func, msg) {
func(self.constructor.name + ': ' + msg);
});
this.log = DeviceLoader.prototype.log;
} else {
var debug = require('debug')(this.constructor.name);
this.log = function(msg) {
debug(msg);
};
}
this.lookupIntervalId = null;
this.oldDevices = [];
this.isRunning = false;
}
|
javascript
|
function DeviceLoader() {
var self = this;
// call super class
EventEmitter2.call(this, {
wildcard: true,
delimiter: ':',
maxListeners: 1000 // default would be 10!
});
if (this.log) {
this.log = _.wrap(this.log, function(func, msg) {
func(self.constructor.name + ': ' + msg);
});
} else if (DeviceLoader.prototype.log) {
DeviceLoader.prototype.log = _.wrap(DeviceLoader.prototype.log, function(func, msg) {
func(self.constructor.name + ': ' + msg);
});
this.log = DeviceLoader.prototype.log;
} else {
var debug = require('debug')(this.constructor.name);
this.log = function(msg) {
debug(msg);
};
}
this.lookupIntervalId = null;
this.oldDevices = [];
this.isRunning = false;
}
|
[
"function",
"DeviceLoader",
"(",
")",
"{",
"var",
"self",
"=",
"this",
";",
"// call super class",
"EventEmitter2",
".",
"call",
"(",
"this",
",",
"{",
"wildcard",
":",
"true",
",",
"delimiter",
":",
"':'",
",",
"maxListeners",
":",
"1000",
"// default would be 10!",
"}",
")",
";",
"if",
"(",
"this",
".",
"log",
")",
"{",
"this",
".",
"log",
"=",
"_",
".",
"wrap",
"(",
"this",
".",
"log",
",",
"function",
"(",
"func",
",",
"msg",
")",
"{",
"func",
"(",
"self",
".",
"constructor",
".",
"name",
"+",
"': '",
"+",
"msg",
")",
";",
"}",
")",
";",
"}",
"else",
"if",
"(",
"DeviceLoader",
".",
"prototype",
".",
"log",
")",
"{",
"DeviceLoader",
".",
"prototype",
".",
"log",
"=",
"_",
".",
"wrap",
"(",
"DeviceLoader",
".",
"prototype",
".",
"log",
",",
"function",
"(",
"func",
",",
"msg",
")",
"{",
"func",
"(",
"self",
".",
"constructor",
".",
"name",
"+",
"': '",
"+",
"msg",
")",
";",
"}",
")",
";",
"this",
".",
"log",
"=",
"DeviceLoader",
".",
"prototype",
".",
"log",
";",
"}",
"else",
"{",
"var",
"debug",
"=",
"require",
"(",
"'debug'",
")",
"(",
"this",
".",
"constructor",
".",
"name",
")",
";",
"this",
".",
"log",
"=",
"function",
"(",
"msg",
")",
"{",
"debug",
"(",
"msg",
")",
";",
"}",
";",
"}",
"this",
".",
"lookupIntervalId",
"=",
"null",
";",
"this",
".",
"oldDevices",
"=",
"[",
"]",
";",
"this",
".",
"isRunning",
"=",
"false",
";",
"}"
] |
A deviceloader can check if there are available some devices.
|
[
"A",
"deviceloader",
"can",
"check",
"if",
"there",
"are",
"available",
"some",
"devices",
"."
] |
c0e20b799b5d3d7b5fbd8f0a3b8ab21c13fcad76
|
https://github.com/adrai/devicestack/blob/c0e20b799b5d3d7b5fbd8f0a3b8ab21c13fcad76/lib/deviceloader.js#L8-L38
|
38,165 |
koopjs/koop-logger
|
index.js
|
createLogger
|
function createLogger (config) {
config = config || {}
let level
if (process.env.KOOP_LOG_LEVEL) {
level = process.env.KOOP_LOG_LEVEL
} else if (process.env.NODE_ENV === 'production') {
level = 'info'
} else {
level = 'debug'
}
if (!config.logfile) {
// no logfile defined, log to STDOUT an STDERRv
const debugConsole = new winston.transports.Console({
colorize: process.env.NODE_ENV === 'production',
level,
stringify: true,
json: true
})
return new winston.Logger({ transports: [debugConsole] })
}
// we need a dir to do log rotation so we get the dir from the file
const logpath = path.dirname(config.logfile)
const logAll = new winston.transports.File({
filename: config.logfile,
name: 'log.all',
dirname: logpath,
colorize: true,
json: false,
level,
formatter: formatter
})
const logError = new winston.transports.File({
filename: config.logfile.replace('.log', '.error.log'),
name: 'log.error',
dirname: logpath,
colorize: true,
json: false,
level: 'error',
formatter: formatter
})
// always log errors
const transports = [logError]
// only log everthing if debug mode is on
if (process.env['LOG_LEVEL'] === 'debug') {
transports.push(logAll)
}
return new winston.Logger({ transports })
}
|
javascript
|
function createLogger (config) {
config = config || {}
let level
if (process.env.KOOP_LOG_LEVEL) {
level = process.env.KOOP_LOG_LEVEL
} else if (process.env.NODE_ENV === 'production') {
level = 'info'
} else {
level = 'debug'
}
if (!config.logfile) {
// no logfile defined, log to STDOUT an STDERRv
const debugConsole = new winston.transports.Console({
colorize: process.env.NODE_ENV === 'production',
level,
stringify: true,
json: true
})
return new winston.Logger({ transports: [debugConsole] })
}
// we need a dir to do log rotation so we get the dir from the file
const logpath = path.dirname(config.logfile)
const logAll = new winston.transports.File({
filename: config.logfile,
name: 'log.all',
dirname: logpath,
colorize: true,
json: false,
level,
formatter: formatter
})
const logError = new winston.transports.File({
filename: config.logfile.replace('.log', '.error.log'),
name: 'log.error',
dirname: logpath,
colorize: true,
json: false,
level: 'error',
formatter: formatter
})
// always log errors
const transports = [logError]
// only log everthing if debug mode is on
if (process.env['LOG_LEVEL'] === 'debug') {
transports.push(logAll)
}
return new winston.Logger({ transports })
}
|
[
"function",
"createLogger",
"(",
"config",
")",
"{",
"config",
"=",
"config",
"||",
"{",
"}",
"let",
"level",
"if",
"(",
"process",
".",
"env",
".",
"KOOP_LOG_LEVEL",
")",
"{",
"level",
"=",
"process",
".",
"env",
".",
"KOOP_LOG_LEVEL",
"}",
"else",
"if",
"(",
"process",
".",
"env",
".",
"NODE_ENV",
"===",
"'production'",
")",
"{",
"level",
"=",
"'info'",
"}",
"else",
"{",
"level",
"=",
"'debug'",
"}",
"if",
"(",
"!",
"config",
".",
"logfile",
")",
"{",
"// no logfile defined, log to STDOUT an STDERRv",
"const",
"debugConsole",
"=",
"new",
"winston",
".",
"transports",
".",
"Console",
"(",
"{",
"colorize",
":",
"process",
".",
"env",
".",
"NODE_ENV",
"===",
"'production'",
",",
"level",
",",
"stringify",
":",
"true",
",",
"json",
":",
"true",
"}",
")",
"return",
"new",
"winston",
".",
"Logger",
"(",
"{",
"transports",
":",
"[",
"debugConsole",
"]",
"}",
")",
"}",
"// we need a dir to do log rotation so we get the dir from the file",
"const",
"logpath",
"=",
"path",
".",
"dirname",
"(",
"config",
".",
"logfile",
")",
"const",
"logAll",
"=",
"new",
"winston",
".",
"transports",
".",
"File",
"(",
"{",
"filename",
":",
"config",
".",
"logfile",
",",
"name",
":",
"'log.all'",
",",
"dirname",
":",
"logpath",
",",
"colorize",
":",
"true",
",",
"json",
":",
"false",
",",
"level",
",",
"formatter",
":",
"formatter",
"}",
")",
"const",
"logError",
"=",
"new",
"winston",
".",
"transports",
".",
"File",
"(",
"{",
"filename",
":",
"config",
".",
"logfile",
".",
"replace",
"(",
"'.log'",
",",
"'.error.log'",
")",
",",
"name",
":",
"'log.error'",
",",
"dirname",
":",
"logpath",
",",
"colorize",
":",
"true",
",",
"json",
":",
"false",
",",
"level",
":",
"'error'",
",",
"formatter",
":",
"formatter",
"}",
")",
"// always log errors",
"const",
"transports",
"=",
"[",
"logError",
"]",
"// only log everthing if debug mode is on",
"if",
"(",
"process",
".",
"env",
"[",
"'LOG_LEVEL'",
"]",
"===",
"'debug'",
")",
"{",
"transports",
".",
"push",
"(",
"logAll",
")",
"}",
"return",
"new",
"winston",
".",
"Logger",
"(",
"{",
"transports",
"}",
")",
"}"
] |
creates new custom winston logger
@param {object} config - koop configuration
@return {Logger} custom logger instance
|
[
"creates",
"new",
"custom",
"winston",
"logger"
] |
dce77f5ef23955b94514f97e9935f6011f035372
|
https://github.com/koopjs/koop-logger/blob/dce77f5ef23955b94514f97e9935f6011f035372/index.js#L11-L62
|
38,166 |
koopjs/koop-logger
|
index.js
|
formatter
|
function formatter (options) {
const line = [
new Date().toISOString(),
options.level
]
if (options.message !== undefined) line.push(options.message)
if (options.meta && Object.keys(options.meta).length) line.push(JSON.stringify(options.meta))
return line.join(' ')
}
|
javascript
|
function formatter (options) {
const line = [
new Date().toISOString(),
options.level
]
if (options.message !== undefined) line.push(options.message)
if (options.meta && Object.keys(options.meta).length) line.push(JSON.stringify(options.meta))
return line.join(' ')
}
|
[
"function",
"formatter",
"(",
"options",
")",
"{",
"const",
"line",
"=",
"[",
"new",
"Date",
"(",
")",
".",
"toISOString",
"(",
")",
",",
"options",
".",
"level",
"]",
"if",
"(",
"options",
".",
"message",
"!==",
"undefined",
")",
"line",
".",
"push",
"(",
"options",
".",
"message",
")",
"if",
"(",
"options",
".",
"meta",
"&&",
"Object",
".",
"keys",
"(",
"options",
".",
"meta",
")",
".",
"length",
")",
"line",
".",
"push",
"(",
"JSON",
".",
"stringify",
"(",
"options",
".",
"meta",
")",
")",
"return",
"line",
".",
"join",
"(",
"' '",
")",
"}"
] |
formats winston log lines
@param {object} options - log info from winston
@return {string} formatted log line
|
[
"formats",
"winston",
"log",
"lines"
] |
dce77f5ef23955b94514f97e9935f6011f035372
|
https://github.com/koopjs/koop-logger/blob/dce77f5ef23955b94514f97e9935f6011f035372/index.js#L69-L80
|
38,167 |
roboncode/tang
|
lib/helpers/difference.js
|
difference
|
function difference(object, base) {
return transform(object, (result, value, key) => {
if (!isEqual(value, base[key])) {
result[key] = isObject(value) && isObject(base[key]) ? difference(value, base[key]) : value;
}
});
}
|
javascript
|
function difference(object, base) {
return transform(object, (result, value, key) => {
if (!isEqual(value, base[key])) {
result[key] = isObject(value) && isObject(base[key]) ? difference(value, base[key]) : value;
}
});
}
|
[
"function",
"difference",
"(",
"object",
",",
"base",
")",
"{",
"return",
"transform",
"(",
"object",
",",
"(",
"result",
",",
"value",
",",
"key",
")",
"=>",
"{",
"if",
"(",
"!",
"isEqual",
"(",
"value",
",",
"base",
"[",
"key",
"]",
")",
")",
"{",
"result",
"[",
"key",
"]",
"=",
"isObject",
"(",
"value",
")",
"&&",
"isObject",
"(",
"base",
"[",
"key",
"]",
")",
"?",
"difference",
"(",
"value",
",",
"base",
"[",
"key",
"]",
")",
":",
"value",
";",
"}",
"}",
")",
";",
"}"
] |
Deep diff between two object, using lodash
@param {Object} object Object compared
@param {Object} base Object to compare with
@return {Object} Return a new object who represent the diff
|
[
"Deep",
"diff",
"between",
"two",
"object",
"using",
"lodash"
] |
3e3826be0e1a621faf3eeea8c769dd28343fb326
|
https://github.com/roboncode/tang/blob/3e3826be0e1a621faf3eeea8c769dd28343fb326/lib/helpers/difference.js#L16-L22
|
38,168 |
keyCat/node-steamspy
|
lib/steamspy.js
|
function ( method, params, cb ) {
if ( typeof params === 'function' ) {
cb = params;
params = {};
}
params = extend(params, {request: method});
this.__request({
method: 'get',
url: this.options.api_url,
qs: params
}, function ( err, response, data ) {
if ( err ) {
cb(err, response, data);
} else {
try {
data = JSON.parse(data);
} catch ( parseError ) {
cb(new Error('Status Code: ' + response.statusCode), response, data);
}
if ( response.statusCode === 200 ) {
cb(null, response, data);
} else {
cb(new Error('Status Code: ' + response.statusCode), response, data);
}
}
});
}
|
javascript
|
function ( method, params, cb ) {
if ( typeof params === 'function' ) {
cb = params;
params = {};
}
params = extend(params, {request: method});
this.__request({
method: 'get',
url: this.options.api_url,
qs: params
}, function ( err, response, data ) {
if ( err ) {
cb(err, response, data);
} else {
try {
data = JSON.parse(data);
} catch ( parseError ) {
cb(new Error('Status Code: ' + response.statusCode), response, data);
}
if ( response.statusCode === 200 ) {
cb(null, response, data);
} else {
cb(new Error('Status Code: ' + response.statusCode), response, data);
}
}
});
}
|
[
"function",
"(",
"method",
",",
"params",
",",
"cb",
")",
"{",
"if",
"(",
"typeof",
"params",
"===",
"'function'",
")",
"{",
"cb",
"=",
"params",
";",
"params",
"=",
"{",
"}",
";",
"}",
"params",
"=",
"extend",
"(",
"params",
",",
"{",
"request",
":",
"method",
"}",
")",
";",
"this",
".",
"__request",
"(",
"{",
"method",
":",
"'get'",
",",
"url",
":",
"this",
".",
"options",
".",
"api_url",
",",
"qs",
":",
"params",
"}",
",",
"function",
"(",
"err",
",",
"response",
",",
"data",
")",
"{",
"if",
"(",
"err",
")",
"{",
"cb",
"(",
"err",
",",
"response",
",",
"data",
")",
";",
"}",
"else",
"{",
"try",
"{",
"data",
"=",
"JSON",
".",
"parse",
"(",
"data",
")",
";",
"}",
"catch",
"(",
"parseError",
")",
"{",
"cb",
"(",
"new",
"Error",
"(",
"'Status Code: '",
"+",
"response",
".",
"statusCode",
")",
",",
"response",
",",
"data",
")",
";",
"}",
"if",
"(",
"response",
".",
"statusCode",
"===",
"200",
")",
"{",
"cb",
"(",
"null",
",",
"response",
",",
"data",
")",
";",
"}",
"else",
"{",
"cb",
"(",
"new",
"Error",
"(",
"'Status Code: '",
"+",
"response",
".",
"statusCode",
")",
",",
"response",
",",
"data",
")",
";",
"}",
"}",
"}",
")",
";",
"}"
] |
Makes a single request to SteamSpy API. Use this in case of absence of shorthands
@param {String} method API request method (e.g 'appdetails', 'top100in2weeks')
@param {Object} params API request parameters applied to URL querystring (e.g {appid: 730})
@param {SteamSpy~requestCallback} cb Callback executed after API response
|
[
"Makes",
"a",
"single",
"request",
"to",
"SteamSpy",
"API",
".",
"Use",
"this",
"in",
"case",
"of",
"absence",
"of",
"shorthands"
] |
ee93def99fbfa842d3eef9580d80ab2d703105b3
|
https://github.com/keyCat/node-steamspy/blob/ee93def99fbfa842d3eef9580d80ab2d703105b3/lib/steamspy.js#L48-L75
|
|
38,169 |
ben-eb/biquad
|
index.js
|
_createBiquadFilter
|
function _createBiquadFilter (defaults) {
return function (context, opts) {
if (audioContext) {
opts = context;
context = audioContext;
}
opts = assign(opts, defaults);
var filter = context.createBiquadFilter();
Object.keys(opts).forEach(function (option) {
if (option !== 'type') {
filter[option].value = opts[option];
} else {
filter.type = opts[option];
}
});
return filter;
};
}
|
javascript
|
function _createBiquadFilter (defaults) {
return function (context, opts) {
if (audioContext) {
opts = context;
context = audioContext;
}
opts = assign(opts, defaults);
var filter = context.createBiquadFilter();
Object.keys(opts).forEach(function (option) {
if (option !== 'type') {
filter[option].value = opts[option];
} else {
filter.type = opts[option];
}
});
return filter;
};
}
|
[
"function",
"_createBiquadFilter",
"(",
"defaults",
")",
"{",
"return",
"function",
"(",
"context",
",",
"opts",
")",
"{",
"if",
"(",
"audioContext",
")",
"{",
"opts",
"=",
"context",
";",
"context",
"=",
"audioContext",
";",
"}",
"opts",
"=",
"assign",
"(",
"opts",
",",
"defaults",
")",
";",
"var",
"filter",
"=",
"context",
".",
"createBiquadFilter",
"(",
")",
";",
"Object",
".",
"keys",
"(",
"opts",
")",
".",
"forEach",
"(",
"function",
"(",
"option",
")",
"{",
"if",
"(",
"option",
"!==",
"'type'",
")",
"{",
"filter",
"[",
"option",
"]",
".",
"value",
"=",
"opts",
"[",
"option",
"]",
";",
"}",
"else",
"{",
"filter",
".",
"type",
"=",
"opts",
"[",
"option",
"]",
";",
"}",
"}",
")",
";",
"return",
"filter",
";",
"}",
";",
"}"
] |
Thin biquad filter creation wrapper.
@param {Object} defaults Default options (usually just type)
@api private
|
[
"Thin",
"biquad",
"filter",
"creation",
"wrapper",
"."
] |
a681aa5d4724e9fa716d0600b06d11ab7a8e1882
|
https://github.com/ben-eb/biquad/blob/a681aa5d4724e9fa716d0600b06d11ab7a8e1882/index.js#L11-L31
|
38,170 |
Losant/bravado-core
|
lib/collection.js
|
function(options, ...rest) {
Entity.apply(this, [options, ...rest]);
this.itemType = options.itemType;
this.itemFactory = options.itemFactory;
this.body = defaults(options.body, {
count: 0,
items: []
});
if (options.items) {
this.body.items = options.items.map(function(item) {
return this.createItemEntity(item);
});
this.body.count = this.body.items.length;
}
}
|
javascript
|
function(options, ...rest) {
Entity.apply(this, [options, ...rest]);
this.itemType = options.itemType;
this.itemFactory = options.itemFactory;
this.body = defaults(options.body, {
count: 0,
items: []
});
if (options.items) {
this.body.items = options.items.map(function(item) {
return this.createItemEntity(item);
});
this.body.count = this.body.items.length;
}
}
|
[
"function",
"(",
"options",
",",
"...",
"rest",
")",
"{",
"Entity",
".",
"apply",
"(",
"this",
",",
"[",
"options",
",",
"...",
"rest",
"]",
")",
";",
"this",
".",
"itemType",
"=",
"options",
".",
"itemType",
";",
"this",
".",
"itemFactory",
"=",
"options",
".",
"itemFactory",
";",
"this",
".",
"body",
"=",
"defaults",
"(",
"options",
".",
"body",
",",
"{",
"count",
":",
"0",
",",
"items",
":",
"[",
"]",
"}",
")",
";",
"if",
"(",
"options",
".",
"items",
")",
"{",
"this",
".",
"body",
".",
"items",
"=",
"options",
".",
"items",
".",
"map",
"(",
"function",
"(",
"item",
")",
"{",
"return",
"this",
".",
"createItemEntity",
"(",
"item",
")",
";",
"}",
")",
";",
"this",
".",
"body",
".",
"count",
"=",
"this",
".",
"body",
".",
"items",
".",
"length",
";",
"}",
"}"
] |
Object that represents a collection of entities returned by a resource's action
|
[
"Object",
"that",
"represents",
"a",
"collection",
"of",
"entities",
"returned",
"by",
"a",
"resource",
"s",
"action"
] |
df152017e0aff9e575c1f7beaf4ddbb9cd346a7c
|
https://github.com/Losant/bravado-core/blob/df152017e0aff9e575c1f7beaf4ddbb9cd346a7c/lib/collection.js#L6-L20
|
|
38,171 |
curiousdannii/glkote-term
|
src/glkapi.js
|
set_references
|
function set_references( vm_options )
{
if ( vm_options.Dialog )
{
Dialog = vm_options.Dialog;
}
if ( !Dialog )
{
if ( typeof window !== 'undefined' && window.Dialog )
{
Dialog = window.Dialog;
}
else
{
throw new Error( 'No reference to Dialog' );
}
}
if ( vm_options.GiDispa )
{
GiDispa = vm_options.GiDispa;
}
else if ( !GiDispa && typeof window !== 'undefined' && window.GiDispa )
{
GiDispa = window.GiDispa;
}
if ( vm_options.GiLoad )
{
GiLoad = vm_options.GiLoad;
}
else if ( !GiLoad && typeof window !== 'undefined' && window.GiLoad )
{
GiLoad = window.GiLoad;
}
if ( vm_options.GlkOte )
{
GlkOte = vm_options.GlkOte;
}
if ( !GlkOte )
{
if ( typeof window !== 'undefined' && window.GlkOte )
{
GlkOte = window.GlkOte;
}
else
{
throw new Error('No reference to GlkOte');
}
}
}
|
javascript
|
function set_references( vm_options )
{
if ( vm_options.Dialog )
{
Dialog = vm_options.Dialog;
}
if ( !Dialog )
{
if ( typeof window !== 'undefined' && window.Dialog )
{
Dialog = window.Dialog;
}
else
{
throw new Error( 'No reference to Dialog' );
}
}
if ( vm_options.GiDispa )
{
GiDispa = vm_options.GiDispa;
}
else if ( !GiDispa && typeof window !== 'undefined' && window.GiDispa )
{
GiDispa = window.GiDispa;
}
if ( vm_options.GiLoad )
{
GiLoad = vm_options.GiLoad;
}
else if ( !GiLoad && typeof window !== 'undefined' && window.GiLoad )
{
GiLoad = window.GiLoad;
}
if ( vm_options.GlkOte )
{
GlkOte = vm_options.GlkOte;
}
if ( !GlkOte )
{
if ( typeof window !== 'undefined' && window.GlkOte )
{
GlkOte = window.GlkOte;
}
else
{
throw new Error('No reference to GlkOte');
}
}
}
|
[
"function",
"set_references",
"(",
"vm_options",
")",
"{",
"if",
"(",
"vm_options",
".",
"Dialog",
")",
"{",
"Dialog",
"=",
"vm_options",
".",
"Dialog",
";",
"}",
"if",
"(",
"!",
"Dialog",
")",
"{",
"if",
"(",
"typeof",
"window",
"!==",
"'undefined'",
"&&",
"window",
".",
"Dialog",
")",
"{",
"Dialog",
"=",
"window",
".",
"Dialog",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'No reference to Dialog'",
")",
";",
"}",
"}",
"if",
"(",
"vm_options",
".",
"GiDispa",
")",
"{",
"GiDispa",
"=",
"vm_options",
".",
"GiDispa",
";",
"}",
"else",
"if",
"(",
"!",
"GiDispa",
"&&",
"typeof",
"window",
"!==",
"'undefined'",
"&&",
"window",
".",
"GiDispa",
")",
"{",
"GiDispa",
"=",
"window",
".",
"GiDispa",
";",
"}",
"if",
"(",
"vm_options",
".",
"GiLoad",
")",
"{",
"GiLoad",
"=",
"vm_options",
".",
"GiLoad",
";",
"}",
"else",
"if",
"(",
"!",
"GiLoad",
"&&",
"typeof",
"window",
"!==",
"'undefined'",
"&&",
"window",
".",
"GiLoad",
")",
"{",
"GiLoad",
"=",
"window",
".",
"GiLoad",
";",
"}",
"if",
"(",
"vm_options",
".",
"GlkOte",
")",
"{",
"GlkOte",
"=",
"vm_options",
".",
"GlkOte",
";",
"}",
"if",
"(",
"!",
"GlkOte",
")",
"{",
"if",
"(",
"typeof",
"window",
"!==",
"'undefined'",
"&&",
"window",
".",
"GlkOte",
")",
"{",
"GlkOte",
"=",
"window",
".",
"GlkOte",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'No reference to GlkOte'",
")",
";",
"}",
"}",
"}"
] |
Set external variable references
|
[
"Set",
"external",
"variable",
"references"
] |
5eda3682a40609d624f4fd7405da58708a61d465
|
https://github.com/curiousdannii/glkote-term/blob/5eda3682a40609d624f4fd7405da58708a61d465/src/glkapi.js#L74-L125
|
38,172 |
crysalead-js/dom-layer
|
src/node/patcher/attrs-n-s.js
|
patch
|
function patch(element, previous, attrs) {
if (!previous && !attrs) {
return attrs;
}
var attrName, ns, name, value, split;
previous = previous || {};
attrs = attrs || {};
for (attrName in previous) {
if (previous[attrName] && !attrs[attrName]) {
split = splitAttrName(attrName);
ns = namespaces[split[0]];
name = split[1];
element.removeAttributeNS(ns, name);
}
}
for (attrName in attrs) {
value = attrs[attrName];
if (previous[attrName] === value) {
continue;
}
if (value) {
split = splitAttrName(attrName);
ns = namespaces[split[0]];
name = split[1];
element.setAttributeNS(ns, name, value);
}
}
return attrs;
}
|
javascript
|
function patch(element, previous, attrs) {
if (!previous && !attrs) {
return attrs;
}
var attrName, ns, name, value, split;
previous = previous || {};
attrs = attrs || {};
for (attrName in previous) {
if (previous[attrName] && !attrs[attrName]) {
split = splitAttrName(attrName);
ns = namespaces[split[0]];
name = split[1];
element.removeAttributeNS(ns, name);
}
}
for (attrName in attrs) {
value = attrs[attrName];
if (previous[attrName] === value) {
continue;
}
if (value) {
split = splitAttrName(attrName);
ns = namespaces[split[0]];
name = split[1];
element.setAttributeNS(ns, name, value);
}
}
return attrs;
}
|
[
"function",
"patch",
"(",
"element",
",",
"previous",
",",
"attrs",
")",
"{",
"if",
"(",
"!",
"previous",
"&&",
"!",
"attrs",
")",
"{",
"return",
"attrs",
";",
"}",
"var",
"attrName",
",",
"ns",
",",
"name",
",",
"value",
",",
"split",
";",
"previous",
"=",
"previous",
"||",
"{",
"}",
";",
"attrs",
"=",
"attrs",
"||",
"{",
"}",
";",
"for",
"(",
"attrName",
"in",
"previous",
")",
"{",
"if",
"(",
"previous",
"[",
"attrName",
"]",
"&&",
"!",
"attrs",
"[",
"attrName",
"]",
")",
"{",
"split",
"=",
"splitAttrName",
"(",
"attrName",
")",
";",
"ns",
"=",
"namespaces",
"[",
"split",
"[",
"0",
"]",
"]",
";",
"name",
"=",
"split",
"[",
"1",
"]",
";",
"element",
".",
"removeAttributeNS",
"(",
"ns",
",",
"name",
")",
";",
"}",
"}",
"for",
"(",
"attrName",
"in",
"attrs",
")",
"{",
"value",
"=",
"attrs",
"[",
"attrName",
"]",
";",
"if",
"(",
"previous",
"[",
"attrName",
"]",
"===",
"value",
")",
"{",
"continue",
";",
"}",
"if",
"(",
"value",
")",
"{",
"split",
"=",
"splitAttrName",
"(",
"attrName",
")",
";",
"ns",
"=",
"namespaces",
"[",
"split",
"[",
"0",
"]",
"]",
";",
"name",
"=",
"split",
"[",
"1",
"]",
";",
"element",
".",
"setAttributeNS",
"(",
"ns",
",",
"name",
",",
"value",
")",
";",
"}",
"}",
"return",
"attrs",
";",
"}"
] |
Maintains state of element namespaced attributes.
@param Object element A DOM element.
@param Object previous The previous state of attributes.
@param Object attrs The attributes to match on.
@return Object attrs The element attributes state.
|
[
"Maintains",
"state",
"of",
"element",
"namespaced",
"attributes",
"."
] |
0c3509fe1b6c4cd2ce0c030b73791f951f5f97a2
|
https://github.com/crysalead-js/dom-layer/blob/0c3509fe1b6c4cd2ce0c030b73791f951f5f97a2/src/node/patcher/attrs-n-s.js#L18-L47
|
38,173 |
etylsarin/gulp-ssi
|
lib/ssiparser.js
|
getFile
|
function getFile(filepath) {
var fileObj = {
path: filepath,
content: null
};
try {
fs.accessSync(filepath, fs.F_OK);
} catch(e) {
console.log(e.message);
return fileObj;
}
fileObj.content = fs.readFileSync(filepath, 'utf-8').trim();
return fileObj;
}
|
javascript
|
function getFile(filepath) {
var fileObj = {
path: filepath,
content: null
};
try {
fs.accessSync(filepath, fs.F_OK);
} catch(e) {
console.log(e.message);
return fileObj;
}
fileObj.content = fs.readFileSync(filepath, 'utf-8').trim();
return fileObj;
}
|
[
"function",
"getFile",
"(",
"filepath",
")",
"{",
"var",
"fileObj",
"=",
"{",
"path",
":",
"filepath",
",",
"content",
":",
"null",
"}",
";",
"try",
"{",
"fs",
".",
"accessSync",
"(",
"filepath",
",",
"fs",
".",
"F_OK",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"console",
".",
"log",
"(",
"e",
".",
"message",
")",
";",
"return",
"fileObj",
";",
"}",
"fileObj",
".",
"content",
"=",
"fs",
".",
"readFileSync",
"(",
"filepath",
",",
"'utf-8'",
")",
".",
"trim",
"(",
")",
";",
"return",
"fileObj",
";",
"}"
] |
Helper which gets a file content
|
[
"Helper",
"which",
"gets",
"a",
"file",
"content"
] |
d39e5caf21310d06c24302065520c9b52c3ebc56
|
https://github.com/etylsarin/gulp-ssi/blob/d39e5caf21310d06c24302065520c9b52c3ebc56/lib/ssiparser.js#L6-L19
|
38,174 |
bigpipe/floppy
|
index.js
|
Floppy
|
function Floppy(url, fn) {
if (!(this instanceof Floppy)) return new Floppy(url, fn);
this.readyState = Floppy.LOADING;
this.start = +new Date();
this.callbacks = [];
this.dependent = 0;
this.cleanup = [];
this.url = url;
if ('function' === typeof fn) {
this.add(fn);
}
}
|
javascript
|
function Floppy(url, fn) {
if (!(this instanceof Floppy)) return new Floppy(url, fn);
this.readyState = Floppy.LOADING;
this.start = +new Date();
this.callbacks = [];
this.dependent = 0;
this.cleanup = [];
this.url = url;
if ('function' === typeof fn) {
this.add(fn);
}
}
|
[
"function",
"Floppy",
"(",
"url",
",",
"fn",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Floppy",
")",
")",
"return",
"new",
"Floppy",
"(",
"url",
",",
"fn",
")",
";",
"this",
".",
"readyState",
"=",
"Floppy",
".",
"LOADING",
";",
"this",
".",
"start",
"=",
"+",
"new",
"Date",
"(",
")",
";",
"this",
".",
"callbacks",
"=",
"[",
"]",
";",
"this",
".",
"dependent",
"=",
"0",
";",
"this",
".",
"cleanup",
"=",
"[",
"]",
";",
"this",
".",
"url",
"=",
"url",
";",
"if",
"(",
"'function'",
"===",
"typeof",
"fn",
")",
"{",
"this",
".",
"add",
"(",
"fn",
")",
";",
"}",
"}"
] |
Representation of one single file that will be loaded.
@constructor
@param {String} url The file URL.
@param {Function} fn Optional callback.
@api private
|
[
"Representation",
"of",
"one",
"single",
"file",
"that",
"will",
"be",
"loaded",
"."
] |
907540a107c378ea14d9d40b05c625b43e151489
|
https://github.com/bigpipe/floppy/blob/907540a107c378ea14d9d40b05c625b43e151489/index.js#L11-L24
|
38,175 |
harmon25/msfrpc-client
|
lib/translate-response.js
|
translateResponse
|
function translateResponse(obj){
for(var k in obj){
if(obj[k] instanceof Array){
for(var i=0;i<obj[k].length;i++){
// just an array of strings
if(obj[k][i] instanceof Buffer){
obj[k][i] = obj[k][i].toString()
} else {
// and array of objects..
for(var k1 in obj[k][i]){
if(obj[k][i][k1] instanceof Buffer){
obj[k][i][k1] = obj[k][i][k1].toString()
}
}
}
}
} else if(obj[k] instanceof Buffer) {
obj[k] = obj[k].toString()
} else {
for(var rk in obj[k]){
if(obj[k][rk] instanceof Buffer){
obj[k][rk] = obj[k][rk].toString()
} else if(obj[k][rk] instanceof Array){
for(var i=0;i<obj[k][rk].length;i++){
if(obj[k][rk][i] instanceof Buffer){
obj[k][rk][i] = obj[k][rk][i].toString()
} else {
obj[k][rk][i] = obj[k][rk][i];
}
}
}
}
}
}
return obj
}
|
javascript
|
function translateResponse(obj){
for(var k in obj){
if(obj[k] instanceof Array){
for(var i=0;i<obj[k].length;i++){
// just an array of strings
if(obj[k][i] instanceof Buffer){
obj[k][i] = obj[k][i].toString()
} else {
// and array of objects..
for(var k1 in obj[k][i]){
if(obj[k][i][k1] instanceof Buffer){
obj[k][i][k1] = obj[k][i][k1].toString()
}
}
}
}
} else if(obj[k] instanceof Buffer) {
obj[k] = obj[k].toString()
} else {
for(var rk in obj[k]){
if(obj[k][rk] instanceof Buffer){
obj[k][rk] = obj[k][rk].toString()
} else if(obj[k][rk] instanceof Array){
for(var i=0;i<obj[k][rk].length;i++){
if(obj[k][rk][i] instanceof Buffer){
obj[k][rk][i] = obj[k][rk][i].toString()
} else {
obj[k][rk][i] = obj[k][rk][i];
}
}
}
}
}
}
return obj
}
|
[
"function",
"translateResponse",
"(",
"obj",
")",
"{",
"for",
"(",
"var",
"k",
"in",
"obj",
")",
"{",
"if",
"(",
"obj",
"[",
"k",
"]",
"instanceof",
"Array",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"obj",
"[",
"k",
"]",
".",
"length",
";",
"i",
"++",
")",
"{",
"// just an array of strings",
"if",
"(",
"obj",
"[",
"k",
"]",
"[",
"i",
"]",
"instanceof",
"Buffer",
")",
"{",
"obj",
"[",
"k",
"]",
"[",
"i",
"]",
"=",
"obj",
"[",
"k",
"]",
"[",
"i",
"]",
".",
"toString",
"(",
")",
"}",
"else",
"{",
"// and array of objects..",
"for",
"(",
"var",
"k1",
"in",
"obj",
"[",
"k",
"]",
"[",
"i",
"]",
")",
"{",
"if",
"(",
"obj",
"[",
"k",
"]",
"[",
"i",
"]",
"[",
"k1",
"]",
"instanceof",
"Buffer",
")",
"{",
"obj",
"[",
"k",
"]",
"[",
"i",
"]",
"[",
"k1",
"]",
"=",
"obj",
"[",
"k",
"]",
"[",
"i",
"]",
"[",
"k1",
"]",
".",
"toString",
"(",
")",
"}",
"}",
"}",
"}",
"}",
"else",
"if",
"(",
"obj",
"[",
"k",
"]",
"instanceof",
"Buffer",
")",
"{",
"obj",
"[",
"k",
"]",
"=",
"obj",
"[",
"k",
"]",
".",
"toString",
"(",
")",
"}",
"else",
"{",
"for",
"(",
"var",
"rk",
"in",
"obj",
"[",
"k",
"]",
")",
"{",
"if",
"(",
"obj",
"[",
"k",
"]",
"[",
"rk",
"]",
"instanceof",
"Buffer",
")",
"{",
"obj",
"[",
"k",
"]",
"[",
"rk",
"]",
"=",
"obj",
"[",
"k",
"]",
"[",
"rk",
"]",
".",
"toString",
"(",
")",
"}",
"else",
"if",
"(",
"obj",
"[",
"k",
"]",
"[",
"rk",
"]",
"instanceof",
"Array",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"obj",
"[",
"k",
"]",
"[",
"rk",
"]",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"obj",
"[",
"k",
"]",
"[",
"rk",
"]",
"[",
"i",
"]",
"instanceof",
"Buffer",
")",
"{",
"obj",
"[",
"k",
"]",
"[",
"rk",
"]",
"[",
"i",
"]",
"=",
"obj",
"[",
"k",
"]",
"[",
"rk",
"]",
"[",
"i",
"]",
".",
"toString",
"(",
")",
"}",
"else",
"{",
"obj",
"[",
"k",
"]",
"[",
"rk",
"]",
"[",
"i",
"]",
"=",
"obj",
"[",
"k",
"]",
"[",
"rk",
"]",
"[",
"i",
"]",
";",
"}",
"}",
"}",
"}",
"}",
"}",
"return",
"obj",
"}"
] |
could probably do this with some kinda recursion, but whatever..cleaner than before...
|
[
"could",
"probably",
"do",
"this",
"with",
"some",
"kinda",
"recursion",
"but",
"whatever",
"..",
"cleaner",
"than",
"before",
"..."
] |
9ea2385f73dd8d5225f553d0c27737b24a2ccec8
|
https://github.com/harmon25/msfrpc-client/blob/9ea2385f73dd8d5225f553d0c27737b24a2ccec8/lib/translate-response.js#L2-L37
|
38,176 |
henrytseng/hostr
|
lib/router.js
|
function(req) {
if(!req || !req.url) return false;
if(typeof(path) === 'string') {
return (req.url).match(path) && ((req.url).match(path).index === 0);
// RegExp
} else {
return (req.url).match(path) !== null;
}
}
|
javascript
|
function(req) {
if(!req || !req.url) return false;
if(typeof(path) === 'string') {
return (req.url).match(path) && ((req.url).match(path).index === 0);
// RegExp
} else {
return (req.url).match(path) !== null;
}
}
|
[
"function",
"(",
"req",
")",
"{",
"if",
"(",
"!",
"req",
"||",
"!",
"req",
".",
"url",
")",
"return",
"false",
";",
"if",
"(",
"typeof",
"(",
"path",
")",
"===",
"'string'",
")",
"{",
"return",
"(",
"req",
".",
"url",
")",
".",
"match",
"(",
"path",
")",
"&&",
"(",
"(",
"req",
".",
"url",
")",
".",
"match",
"(",
"path",
")",
".",
"index",
"===",
"0",
")",
";",
"// RegExp",
"}",
"else",
"{",
"return",
"(",
"req",
".",
"url",
")",
".",
"match",
"(",
"path",
")",
"!==",
"null",
";",
"}",
"}"
] |
Check if the route matches
@return {Boolean} True if the URL matches and false otherwise
|
[
"Check",
"if",
"the",
"route",
"matches"
] |
8ef1ec59d2acdd135eafb19d439519a8d87ff21a
|
https://github.com/henrytseng/hostr/blob/8ef1ec59d2acdd135eafb19d439519a8d87ff21a/lib/router.js#L24-L34
|
|
38,177 |
amida-tech/blue-button-cms
|
lib/sections/commonFunctions.js
|
ignoreValue
|
function ignoreValue(value) {
if (value === null || value === undefined || value.length === 0) {
return true;
}
if (value.length === 0) {
return true;
}
if (typeof (value) === 'object') {
return false;
}
value = value.toLowerCase();
var ignoreValues = ['not available', 'no information'];
for (var x = 0; x < ignoreValues.length; x++) {
if (value.indexOf(ignoreValues[x]) >= 0) {
return true;
}
}
return false;
}
|
javascript
|
function ignoreValue(value) {
if (value === null || value === undefined || value.length === 0) {
return true;
}
if (value.length === 0) {
return true;
}
if (typeof (value) === 'object') {
return false;
}
value = value.toLowerCase();
var ignoreValues = ['not available', 'no information'];
for (var x = 0; x < ignoreValues.length; x++) {
if (value.indexOf(ignoreValues[x]) >= 0) {
return true;
}
}
return false;
}
|
[
"function",
"ignoreValue",
"(",
"value",
")",
"{",
"if",
"(",
"value",
"===",
"null",
"||",
"value",
"===",
"undefined",
"||",
"value",
".",
"length",
"===",
"0",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"value",
".",
"length",
"===",
"0",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"typeof",
"(",
"value",
")",
"===",
"'object'",
")",
"{",
"return",
"false",
";",
"}",
"value",
"=",
"value",
".",
"toLowerCase",
"(",
")",
";",
"var",
"ignoreValues",
"=",
"[",
"'not available'",
",",
"'no information'",
"]",
";",
"for",
"(",
"var",
"x",
"=",
"0",
";",
"x",
"<",
"ignoreValues",
".",
"length",
";",
"x",
"++",
")",
"{",
"if",
"(",
"value",
".",
"indexOf",
"(",
"ignoreValues",
"[",
"x",
"]",
")",
">=",
"0",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] |
this function ignores all not avaliable value fields
|
[
"this",
"function",
"ignores",
"all",
"not",
"avaliable",
"value",
"fields"
] |
749b8cf071910b22f8176a9ed8fc3b05062e1aad
|
https://github.com/amida-tech/blue-button-cms/blob/749b8cf071910b22f8176a9ed8fc3b05062e1aad/lib/sections/commonFunctions.js#L418-L436
|
38,178 |
pwstegman/pw-lda
|
index.js
|
LDA
|
function LDA(...classes) {
// Compute pairwise LDA classes (needed for multiclass LDA)
if(classes.length < 2) {
throw new Error('Please pass at least 2 classes');
}
let numberOfPairs = classes.length * (classes.length - 1) / 2;
let pair1 = 0;
let pair2 = 1;
let pairs = new Array(numberOfPairs);
for(let i = 0; i < numberOfPairs; i++){
pairs[i] = computeLdaParams(classes[pair1], classes[pair2], pair1, pair2);
pair2++;
if(pair2 == classes.length) {
pair1++;
pair2 = pair1 + 1;
}
}
this.pairs = pairs;
this.numberOfClasses = classes.length;
}
|
javascript
|
function LDA(...classes) {
// Compute pairwise LDA classes (needed for multiclass LDA)
if(classes.length < 2) {
throw new Error('Please pass at least 2 classes');
}
let numberOfPairs = classes.length * (classes.length - 1) / 2;
let pair1 = 0;
let pair2 = 1;
let pairs = new Array(numberOfPairs);
for(let i = 0; i < numberOfPairs; i++){
pairs[i] = computeLdaParams(classes[pair1], classes[pair2], pair1, pair2);
pair2++;
if(pair2 == classes.length) {
pair1++;
pair2 = pair1 + 1;
}
}
this.pairs = pairs;
this.numberOfClasses = classes.length;
}
|
[
"function",
"LDA",
"(",
"...",
"classes",
")",
"{",
"// Compute pairwise LDA classes (needed for multiclass LDA)",
"if",
"(",
"classes",
".",
"length",
"<",
"2",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Please pass at least 2 classes'",
")",
";",
"}",
"let",
"numberOfPairs",
"=",
"classes",
".",
"length",
"*",
"(",
"classes",
".",
"length",
"-",
"1",
")",
"/",
"2",
";",
"let",
"pair1",
"=",
"0",
";",
"let",
"pair2",
"=",
"1",
";",
"let",
"pairs",
"=",
"new",
"Array",
"(",
"numberOfPairs",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"numberOfPairs",
";",
"i",
"++",
")",
"{",
"pairs",
"[",
"i",
"]",
"=",
"computeLdaParams",
"(",
"classes",
"[",
"pair1",
"]",
",",
"classes",
"[",
"pair2",
"]",
",",
"pair1",
",",
"pair2",
")",
";",
"pair2",
"++",
";",
"if",
"(",
"pair2",
"==",
"classes",
".",
"length",
")",
"{",
"pair1",
"++",
";",
"pair2",
"=",
"pair1",
"+",
"1",
";",
"}",
"}",
"this",
".",
"pairs",
"=",
"pairs",
";",
"this",
".",
"numberOfClasses",
"=",
"classes",
".",
"length",
";",
"}"
] |
An LDA object.
@constructor
@param {...number[][]} classes - Each parameter is a 2d class array. In each class array, rows are samples, columns are variables.
@example
let classifier = new LDA(class1, class2, class3);
|
[
"An",
"LDA",
"object",
"."
] |
4bd875cf746f98e2aa3f9c49cc426aad2980fb33
|
https://github.com/pwstegman/pw-lda/blob/4bd875cf746f98e2aa3f9c49cc426aad2980fb33/index.js#L15-L39
|
38,179 |
adrai/devicestack
|
lib/serial/globaldeviceloader.js
|
function(Device, filter) {
var sub = new EventEmitter2({
wildcard: true,
delimiter: ':',
maxListeners: 1000 // default would be 10!
});
sub.Device = Device;
sub.filter = filter;
sub.oldDevices = [];
sub.newDevices = [];
/**
* Calls the callback with an array of devices.
* @param {Array} ports When called within this file this are the listed system ports. [optional]
* @param {Function} callback The function, that will be called when finished lookup.
* `function(err, devices){}` devices is an array of Device objects.
*/
sub.lookup = function(ports, callback) {
if (!callback) {
callback = ports;
ports = null;
}
if (this.newDevices.length > 0) {
if (callback) { callback(null, this.newDevices); }
return;
} else {
var self = this;
globalSerialDeviceLoader.lookup(function(err) {
if (err && !err.name) {
err = new Error(err);
}
if (callback) { callback(err, self.newDevices); }
});
}
};
/**
* Calls lookup function with optional callback
* and emits 'plug' for new attached devices
* and 'unplug' for removed devices.
* @param {Function} callback The function, that will be called when finished triggering. [optional]
* `function(err, devices){}` devices is an array of Device objects.
*/
sub.trigger = function(callback) {
var self = this;
globalSerialDeviceLoader.trigger(function(err) {
if (err && !err.name) {
err = new Error(err);
}
if (callback) { callback(err, self.newDevices); }
});
};
/**
* Starts to lookup.
* @param {Number} interval The interval milliseconds. [optional]
* @param {Function} callback The function, that will be called when trigger has started. [optional]
* `function(err, devices){}` devices is an array of Device objects.
*/
sub.startLookup = function(interval, callback) {
if (!callback && _.isFunction(interval)) {
callback = interval;
interval = null;
}
subscribers.push(this);
var self = this;
if (isRunning) {
if (callback) { callback(null, self.newDevices); }
return;
} else {
globalSerialDeviceLoader.startLookup(interval, function(err) {
if (err && !err.name) {
err = new Error(err);
}
if (callback) { callback(err, self.newDevices); }
});
}
};
/**
* Removes itself as subscriber.
* If last stops the interval that calls trigger function.
*/
sub.stopLookup = function() {
var self = this;
if (!isRunning) {
return;
} else {
subscribers = _.reject(function(s) {
return s === self;
});
if (subscribers.length === 0) {
globalSerialDeviceLoader.stopLookup();
}
return;
}
};
return sub;
}
|
javascript
|
function(Device, filter) {
var sub = new EventEmitter2({
wildcard: true,
delimiter: ':',
maxListeners: 1000 // default would be 10!
});
sub.Device = Device;
sub.filter = filter;
sub.oldDevices = [];
sub.newDevices = [];
/**
* Calls the callback with an array of devices.
* @param {Array} ports When called within this file this are the listed system ports. [optional]
* @param {Function} callback The function, that will be called when finished lookup.
* `function(err, devices){}` devices is an array of Device objects.
*/
sub.lookup = function(ports, callback) {
if (!callback) {
callback = ports;
ports = null;
}
if (this.newDevices.length > 0) {
if (callback) { callback(null, this.newDevices); }
return;
} else {
var self = this;
globalSerialDeviceLoader.lookup(function(err) {
if (err && !err.name) {
err = new Error(err);
}
if (callback) { callback(err, self.newDevices); }
});
}
};
/**
* Calls lookup function with optional callback
* and emits 'plug' for new attached devices
* and 'unplug' for removed devices.
* @param {Function} callback The function, that will be called when finished triggering. [optional]
* `function(err, devices){}` devices is an array of Device objects.
*/
sub.trigger = function(callback) {
var self = this;
globalSerialDeviceLoader.trigger(function(err) {
if (err && !err.name) {
err = new Error(err);
}
if (callback) { callback(err, self.newDevices); }
});
};
/**
* Starts to lookup.
* @param {Number} interval The interval milliseconds. [optional]
* @param {Function} callback The function, that will be called when trigger has started. [optional]
* `function(err, devices){}` devices is an array of Device objects.
*/
sub.startLookup = function(interval, callback) {
if (!callback && _.isFunction(interval)) {
callback = interval;
interval = null;
}
subscribers.push(this);
var self = this;
if (isRunning) {
if (callback) { callback(null, self.newDevices); }
return;
} else {
globalSerialDeviceLoader.startLookup(interval, function(err) {
if (err && !err.name) {
err = new Error(err);
}
if (callback) { callback(err, self.newDevices); }
});
}
};
/**
* Removes itself as subscriber.
* If last stops the interval that calls trigger function.
*/
sub.stopLookup = function() {
var self = this;
if (!isRunning) {
return;
} else {
subscribers = _.reject(function(s) {
return s === self;
});
if (subscribers.length === 0) {
globalSerialDeviceLoader.stopLookup();
}
return;
}
};
return sub;
}
|
[
"function",
"(",
"Device",
",",
"filter",
")",
"{",
"var",
"sub",
"=",
"new",
"EventEmitter2",
"(",
"{",
"wildcard",
":",
"true",
",",
"delimiter",
":",
"':'",
",",
"maxListeners",
":",
"1000",
"// default would be 10!",
"}",
")",
";",
"sub",
".",
"Device",
"=",
"Device",
";",
"sub",
".",
"filter",
"=",
"filter",
";",
"sub",
".",
"oldDevices",
"=",
"[",
"]",
";",
"sub",
".",
"newDevices",
"=",
"[",
"]",
";",
"/**\n * Calls the callback with an array of devices.\n * @param {Array} ports When called within this file this are the listed system ports. [optional]\n * @param {Function} callback The function, that will be called when finished lookup.\n * `function(err, devices){}` devices is an array of Device objects.\n */",
"sub",
".",
"lookup",
"=",
"function",
"(",
"ports",
",",
"callback",
")",
"{",
"if",
"(",
"!",
"callback",
")",
"{",
"callback",
"=",
"ports",
";",
"ports",
"=",
"null",
";",
"}",
"if",
"(",
"this",
".",
"newDevices",
".",
"length",
">",
"0",
")",
"{",
"if",
"(",
"callback",
")",
"{",
"callback",
"(",
"null",
",",
"this",
".",
"newDevices",
")",
";",
"}",
"return",
";",
"}",
"else",
"{",
"var",
"self",
"=",
"this",
";",
"globalSerialDeviceLoader",
".",
"lookup",
"(",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
"&&",
"!",
"err",
".",
"name",
")",
"{",
"err",
"=",
"new",
"Error",
"(",
"err",
")",
";",
"}",
"if",
"(",
"callback",
")",
"{",
"callback",
"(",
"err",
",",
"self",
".",
"newDevices",
")",
";",
"}",
"}",
")",
";",
"}",
"}",
";",
"/**\n * Calls lookup function with optional callback\n * and emits 'plug' for new attached devices\n * and 'unplug' for removed devices.\n * @param {Function} callback The function, that will be called when finished triggering. [optional]\n * `function(err, devices){}` devices is an array of Device objects.\n */",
"sub",
".",
"trigger",
"=",
"function",
"(",
"callback",
")",
"{",
"var",
"self",
"=",
"this",
";",
"globalSerialDeviceLoader",
".",
"trigger",
"(",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
"&&",
"!",
"err",
".",
"name",
")",
"{",
"err",
"=",
"new",
"Error",
"(",
"err",
")",
";",
"}",
"if",
"(",
"callback",
")",
"{",
"callback",
"(",
"err",
",",
"self",
".",
"newDevices",
")",
";",
"}",
"}",
")",
";",
"}",
";",
"/**\n * Starts to lookup.\n * @param {Number} interval The interval milliseconds. [optional]\n * @param {Function} callback The function, that will be called when trigger has started. [optional]\n * `function(err, devices){}` devices is an array of Device objects.\n */",
"sub",
".",
"startLookup",
"=",
"function",
"(",
"interval",
",",
"callback",
")",
"{",
"if",
"(",
"!",
"callback",
"&&",
"_",
".",
"isFunction",
"(",
"interval",
")",
")",
"{",
"callback",
"=",
"interval",
";",
"interval",
"=",
"null",
";",
"}",
"subscribers",
".",
"push",
"(",
"this",
")",
";",
"var",
"self",
"=",
"this",
";",
"if",
"(",
"isRunning",
")",
"{",
"if",
"(",
"callback",
")",
"{",
"callback",
"(",
"null",
",",
"self",
".",
"newDevices",
")",
";",
"}",
"return",
";",
"}",
"else",
"{",
"globalSerialDeviceLoader",
".",
"startLookup",
"(",
"interval",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
"&&",
"!",
"err",
".",
"name",
")",
"{",
"err",
"=",
"new",
"Error",
"(",
"err",
")",
";",
"}",
"if",
"(",
"callback",
")",
"{",
"callback",
"(",
"err",
",",
"self",
".",
"newDevices",
")",
";",
"}",
"}",
")",
";",
"}",
"}",
";",
"/**\n * Removes itself as subscriber.\n * If last stops the interval that calls trigger function.\n */",
"sub",
".",
"stopLookup",
"=",
"function",
"(",
")",
"{",
"var",
"self",
"=",
"this",
";",
"if",
"(",
"!",
"isRunning",
")",
"{",
"return",
";",
"}",
"else",
"{",
"subscribers",
"=",
"_",
".",
"reject",
"(",
"function",
"(",
"s",
")",
"{",
"return",
"s",
"===",
"self",
";",
"}",
")",
";",
"if",
"(",
"subscribers",
".",
"length",
"===",
"0",
")",
"{",
"globalSerialDeviceLoader",
".",
"stopLookup",
"(",
")",
";",
"}",
"return",
";",
"}",
"}",
";",
"return",
"sub",
";",
"}"
] |
Creates a deviceloader.
@param {Object} Device The constructor function of the device.
@param {Function} filter The filter function that will filter the needed devices.
@return {Object} Represents a SerialDeviceLoader.
|
[
"Creates",
"a",
"deviceloader",
"."
] |
c0e20b799b5d3d7b5fbd8f0a3b8ab21c13fcad76
|
https://github.com/adrai/devicestack/blob/c0e20b799b5d3d7b5fbd8f0a3b8ab21c13fcad76/lib/serial/globaldeviceloader.js#L18-L120
|
|
38,180 |
adrai/devicestack
|
lib/serial/globaldeviceloader.js
|
function(callback) {
sp.list(function(err, ports) {
if (err && !err.name) {
err = new Error(err);
}
if (err && callback) { return callback(err); }
async.forEach(subscribers, function(s, callback) {
if (s) {
var resPorts = s.filter(ports);
var devices = _.map(resPorts, function(p) {
var found = _.find(s.oldDevices, function(dev) {
return dev.get('portName') && p.comName && dev.get('portName').toLowerCase() === p.comName.toLowerCase();
});
if (found) {
return found;
} else {
var newDev = new s.Device(p.comName);
newDev.set(p);
return newDev;
}
}) || [];
s.newDevices = devices;
}
callback(null);
}, function(err) {
if (err && !err.name) {
err = new Error(err);
}
if (callback) { return callback(err); }
});
});
}
|
javascript
|
function(callback) {
sp.list(function(err, ports) {
if (err && !err.name) {
err = new Error(err);
}
if (err && callback) { return callback(err); }
async.forEach(subscribers, function(s, callback) {
if (s) {
var resPorts = s.filter(ports);
var devices = _.map(resPorts, function(p) {
var found = _.find(s.oldDevices, function(dev) {
return dev.get('portName') && p.comName && dev.get('portName').toLowerCase() === p.comName.toLowerCase();
});
if (found) {
return found;
} else {
var newDev = new s.Device(p.comName);
newDev.set(p);
return newDev;
}
}) || [];
s.newDevices = devices;
}
callback(null);
}, function(err) {
if (err && !err.name) {
err = new Error(err);
}
if (callback) { return callback(err); }
});
});
}
|
[
"function",
"(",
"callback",
")",
"{",
"sp",
".",
"list",
"(",
"function",
"(",
"err",
",",
"ports",
")",
"{",
"if",
"(",
"err",
"&&",
"!",
"err",
".",
"name",
")",
"{",
"err",
"=",
"new",
"Error",
"(",
"err",
")",
";",
"}",
"if",
"(",
"err",
"&&",
"callback",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"async",
".",
"forEach",
"(",
"subscribers",
",",
"function",
"(",
"s",
",",
"callback",
")",
"{",
"if",
"(",
"s",
")",
"{",
"var",
"resPorts",
"=",
"s",
".",
"filter",
"(",
"ports",
")",
";",
"var",
"devices",
"=",
"_",
".",
"map",
"(",
"resPorts",
",",
"function",
"(",
"p",
")",
"{",
"var",
"found",
"=",
"_",
".",
"find",
"(",
"s",
".",
"oldDevices",
",",
"function",
"(",
"dev",
")",
"{",
"return",
"dev",
".",
"get",
"(",
"'portName'",
")",
"&&",
"p",
".",
"comName",
"&&",
"dev",
".",
"get",
"(",
"'portName'",
")",
".",
"toLowerCase",
"(",
")",
"===",
"p",
".",
"comName",
".",
"toLowerCase",
"(",
")",
";",
"}",
")",
";",
"if",
"(",
"found",
")",
"{",
"return",
"found",
";",
"}",
"else",
"{",
"var",
"newDev",
"=",
"new",
"s",
".",
"Device",
"(",
"p",
".",
"comName",
")",
";",
"newDev",
".",
"set",
"(",
"p",
")",
";",
"return",
"newDev",
";",
"}",
"}",
")",
"||",
"[",
"]",
";",
"s",
".",
"newDevices",
"=",
"devices",
";",
"}",
"callback",
"(",
"null",
")",
";",
"}",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
"&&",
"!",
"err",
".",
"name",
")",
"{",
"err",
"=",
"new",
"Error",
"(",
"err",
")",
";",
"}",
"if",
"(",
"callback",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Calls the callback when finished.
@param {Function} callback The function, that will be called when finished lookup.
`function(err){}`
|
[
"Calls",
"the",
"callback",
"when",
"finished",
"."
] |
c0e20b799b5d3d7b5fbd8f0a3b8ab21c13fcad76
|
https://github.com/adrai/devicestack/blob/c0e20b799b5d3d7b5fbd8f0a3b8ab21c13fcad76/lib/serial/globaldeviceloader.js#L127-L162
|
|
38,181 |
adrai/devicestack
|
lib/serial/globaldeviceloader.js
|
function(callback) {
globalSerialDeviceLoader.lookup(function(err) {
if (err && !err.name) {
err = new Error(err);
}
if (err && callback) { return callback(err); }
async.forEach(subscribers, function(s, callback) {
if (s && s.oldDevices.length !== s.newDevices.length) {
var devs = [];
if (s.oldDevices.length > s.newDevices.length) {
devs = _.difference(s.oldDevices, s.newDevices);
_.each(devs, function(d) {
if (s.log) s.log('unplug device with id ' + device.id);
if (d.close) {
d.close();
}
s.emit('unplug', d);
});
} else {
devs = _.difference(s.newDevices, s.oldDevices);
_.each(devs, function(d) {
if (s.log) s.log('plug device with id ' + device.id);
s.emit('plug', d);
});
}
s.oldDevices = s.newDevices;
}
callback(null);
}, function(err) {
if (err && !err.name) {
err = new Error(err);
}
if (callback) { return callback(err); }
});
});
}
|
javascript
|
function(callback) {
globalSerialDeviceLoader.lookup(function(err) {
if (err && !err.name) {
err = new Error(err);
}
if (err && callback) { return callback(err); }
async.forEach(subscribers, function(s, callback) {
if (s && s.oldDevices.length !== s.newDevices.length) {
var devs = [];
if (s.oldDevices.length > s.newDevices.length) {
devs = _.difference(s.oldDevices, s.newDevices);
_.each(devs, function(d) {
if (s.log) s.log('unplug device with id ' + device.id);
if (d.close) {
d.close();
}
s.emit('unplug', d);
});
} else {
devs = _.difference(s.newDevices, s.oldDevices);
_.each(devs, function(d) {
if (s.log) s.log('plug device with id ' + device.id);
s.emit('plug', d);
});
}
s.oldDevices = s.newDevices;
}
callback(null);
}, function(err) {
if (err && !err.name) {
err = new Error(err);
}
if (callback) { return callback(err); }
});
});
}
|
[
"function",
"(",
"callback",
")",
"{",
"globalSerialDeviceLoader",
".",
"lookup",
"(",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
"&&",
"!",
"err",
".",
"name",
")",
"{",
"err",
"=",
"new",
"Error",
"(",
"err",
")",
";",
"}",
"if",
"(",
"err",
"&&",
"callback",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"async",
".",
"forEach",
"(",
"subscribers",
",",
"function",
"(",
"s",
",",
"callback",
")",
"{",
"if",
"(",
"s",
"&&",
"s",
".",
"oldDevices",
".",
"length",
"!==",
"s",
".",
"newDevices",
".",
"length",
")",
"{",
"var",
"devs",
"=",
"[",
"]",
";",
"if",
"(",
"s",
".",
"oldDevices",
".",
"length",
">",
"s",
".",
"newDevices",
".",
"length",
")",
"{",
"devs",
"=",
"_",
".",
"difference",
"(",
"s",
".",
"oldDevices",
",",
"s",
".",
"newDevices",
")",
";",
"_",
".",
"each",
"(",
"devs",
",",
"function",
"(",
"d",
")",
"{",
"if",
"(",
"s",
".",
"log",
")",
"s",
".",
"log",
"(",
"'unplug device with id '",
"+",
"device",
".",
"id",
")",
";",
"if",
"(",
"d",
".",
"close",
")",
"{",
"d",
".",
"close",
"(",
")",
";",
"}",
"s",
".",
"emit",
"(",
"'unplug'",
",",
"d",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"devs",
"=",
"_",
".",
"difference",
"(",
"s",
".",
"newDevices",
",",
"s",
".",
"oldDevices",
")",
";",
"_",
".",
"each",
"(",
"devs",
",",
"function",
"(",
"d",
")",
"{",
"if",
"(",
"s",
".",
"log",
")",
"s",
".",
"log",
"(",
"'plug device with id '",
"+",
"device",
".",
"id",
")",
";",
"s",
".",
"emit",
"(",
"'plug'",
",",
"d",
")",
";",
"}",
")",
";",
"}",
"s",
".",
"oldDevices",
"=",
"s",
".",
"newDevices",
";",
"}",
"callback",
"(",
"null",
")",
";",
"}",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
"&&",
"!",
"err",
".",
"name",
")",
"{",
"err",
"=",
"new",
"Error",
"(",
"err",
")",
";",
"}",
"if",
"(",
"callback",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Calls lookup function with optional callback
and emits 'plug' for new attached devices
and 'unplug' for removed devices.
@param {Function} callback The function, that will be called when finished triggering. [optional]
`function(err){}`
|
[
"Calls",
"lookup",
"function",
"with",
"optional",
"callback",
"and",
"emits",
"plug",
"for",
"new",
"attached",
"devices",
"and",
"unplug",
"for",
"removed",
"devices",
"."
] |
c0e20b799b5d3d7b5fbd8f0a3b8ab21c13fcad76
|
https://github.com/adrai/devicestack/blob/c0e20b799b5d3d7b5fbd8f0a3b8ab21c13fcad76/lib/serial/globaldeviceloader.js#L171-L210
|
|
38,182 |
adrai/devicestack
|
lib/serial/globaldeviceloader.js
|
function(interval, callback) {
if (lookupIntervalId) {
return;
}
isRunning = true;
if (!callback && _.isFunction(interval)) {
callback = interval;
interval = null;
}
interval = interval || 500;
globalSerialDeviceLoader.trigger(function(err) {
var triggering = false;
lookupIntervalId = setInterval(function() {
if (triggering) return;
triggering = true;
globalSerialDeviceLoader.trigger(function() {
triggering = false;
});
}, interval);
if (err && !err.name) {
err = new Error(err);
}
if (callback) { callback(err); }
});
}
|
javascript
|
function(interval, callback) {
if (lookupIntervalId) {
return;
}
isRunning = true;
if (!callback && _.isFunction(interval)) {
callback = interval;
interval = null;
}
interval = interval || 500;
globalSerialDeviceLoader.trigger(function(err) {
var triggering = false;
lookupIntervalId = setInterval(function() {
if (triggering) return;
triggering = true;
globalSerialDeviceLoader.trigger(function() {
triggering = false;
});
}, interval);
if (err && !err.name) {
err = new Error(err);
}
if (callback) { callback(err); }
});
}
|
[
"function",
"(",
"interval",
",",
"callback",
")",
"{",
"if",
"(",
"lookupIntervalId",
")",
"{",
"return",
";",
"}",
"isRunning",
"=",
"true",
";",
"if",
"(",
"!",
"callback",
"&&",
"_",
".",
"isFunction",
"(",
"interval",
")",
")",
"{",
"callback",
"=",
"interval",
";",
"interval",
"=",
"null",
";",
"}",
"interval",
"=",
"interval",
"||",
"500",
";",
"globalSerialDeviceLoader",
".",
"trigger",
"(",
"function",
"(",
"err",
")",
"{",
"var",
"triggering",
"=",
"false",
";",
"lookupIntervalId",
"=",
"setInterval",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"triggering",
")",
"return",
";",
"triggering",
"=",
"true",
";",
"globalSerialDeviceLoader",
".",
"trigger",
"(",
"function",
"(",
")",
"{",
"triggering",
"=",
"false",
";",
"}",
")",
";",
"}",
",",
"interval",
")",
";",
"if",
"(",
"err",
"&&",
"!",
"err",
".",
"name",
")",
"{",
"err",
"=",
"new",
"Error",
"(",
"err",
")",
";",
"}",
"if",
"(",
"callback",
")",
"{",
"callback",
"(",
"err",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Starts to lookup.
@param {Number} interval The interval milliseconds. [optional]
@param {Function} callback The function, that will be called when trigger has started. [optional]
`function(err){}`
|
[
"Starts",
"to",
"lookup",
"."
] |
c0e20b799b5d3d7b5fbd8f0a3b8ab21c13fcad76
|
https://github.com/adrai/devicestack/blob/c0e20b799b5d3d7b5fbd8f0a3b8ab21c13fcad76/lib/serial/globaldeviceloader.js#L218-L247
|
|
38,183 |
Toxiapo/ardorjs
|
util/curve25519.js
|
cpy32
|
function cpy32 (d, s) {
for (var i = 0; i < 32; i++)
d[i] = s[i];
}
|
javascript
|
function cpy32 (d, s) {
for (var i = 0; i < 32; i++)
d[i] = s[i];
}
|
[
"function",
"cpy32",
"(",
"d",
",",
"s",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"32",
";",
"i",
"++",
")",
"d",
"[",
"i",
"]",
"=",
"s",
"[",
"i",
"]",
";",
"}"
] |
endregion region radix 2^8 math
|
[
"endregion",
"region",
"radix",
"2^8",
"math"
] |
0e312739b420476c4f9f6c072b84930401aa12a8
|
https://github.com/Toxiapo/ardorjs/blob/0e312739b420476c4f9f6c072b84930401aa12a8/util/curve25519.js#L87-L90
|
38,184 |
gegeyang0124/react-native-navigation-cus
|
src/views/Header/HeaderStyleInterpolator.js
|
forLeftButton
|
function forLeftButton(props) {
const { position, scene, scenes } = props;
const interpolate = getSceneIndicesForInterpolationInputRange(props);
if (!interpolate) return { opacity: 0 };
const { first, last } = interpolate;
const index = scene.index;
return {
opacity: position.interpolate({
inputRange: [
first,
first + Math.abs(index - first) / 2,
index,
last - Math.abs(last - index) / 2,
last,
],
outputRange: [0, 0.5, 1, 0.5, 0],
}),
};
}
|
javascript
|
function forLeftButton(props) {
const { position, scene, scenes } = props;
const interpolate = getSceneIndicesForInterpolationInputRange(props);
if (!interpolate) return { opacity: 0 };
const { first, last } = interpolate;
const index = scene.index;
return {
opacity: position.interpolate({
inputRange: [
first,
first + Math.abs(index - first) / 2,
index,
last - Math.abs(last - index) / 2,
last,
],
outputRange: [0, 0.5, 1, 0.5, 0],
}),
};
}
|
[
"function",
"forLeftButton",
"(",
"props",
")",
"{",
"const",
"{",
"position",
",",
"scene",
",",
"scenes",
"}",
"=",
"props",
";",
"const",
"interpolate",
"=",
"getSceneIndicesForInterpolationInputRange",
"(",
"props",
")",
";",
"if",
"(",
"!",
"interpolate",
")",
"return",
"{",
"opacity",
":",
"0",
"}",
";",
"const",
"{",
"first",
",",
"last",
"}",
"=",
"interpolate",
";",
"const",
"index",
"=",
"scene",
".",
"index",
";",
"return",
"{",
"opacity",
":",
"position",
".",
"interpolate",
"(",
"{",
"inputRange",
":",
"[",
"first",
",",
"first",
"+",
"Math",
".",
"abs",
"(",
"index",
"-",
"first",
")",
"/",
"2",
",",
"index",
",",
"last",
"-",
"Math",
".",
"abs",
"(",
"last",
"-",
"index",
")",
"/",
"2",
",",
"last",
",",
"]",
",",
"outputRange",
":",
"[",
"0",
",",
"0.5",
",",
"1",
",",
"0.5",
",",
"0",
"]",
",",
"}",
")",
",",
"}",
";",
"}"
] |
iOS UINavigationController style interpolators
|
[
"iOS",
"UINavigationController",
"style",
"interpolators"
] |
37bf130e0a459ed8f8671ebf87efcb425aaeb775
|
https://github.com/gegeyang0124/react-native-navigation-cus/blob/37bf130e0a459ed8f8671ebf87efcb425aaeb775/src/views/Header/HeaderStyleInterpolator.js#L65-L86
|
38,185 |
DenisCarriere/slippy-grid
|
index.js
|
all
|
function all (extent, minZoom, maxZoom) {
const tiles = []
const grid = single(extent, minZoom, maxZoom)
while (true) {
const {value, done} = grid.next()
if (done) break
tiles.push(value)
}
return tiles
}
|
javascript
|
function all (extent, minZoom, maxZoom) {
const tiles = []
const grid = single(extent, minZoom, maxZoom)
while (true) {
const {value, done} = grid.next()
if (done) break
tiles.push(value)
}
return tiles
}
|
[
"function",
"all",
"(",
"extent",
",",
"minZoom",
",",
"maxZoom",
")",
"{",
"const",
"tiles",
"=",
"[",
"]",
"const",
"grid",
"=",
"single",
"(",
"extent",
",",
"minZoom",
",",
"maxZoom",
")",
"while",
"(",
"true",
")",
"{",
"const",
"{",
"value",
",",
"done",
"}",
"=",
"grid",
".",
"next",
"(",
")",
"if",
"(",
"done",
")",
"break",
"tiles",
".",
"push",
"(",
"value",
")",
"}",
"return",
"tiles",
"}"
] |
All Tiles from a given BBox
@param {BBox|BBox[]|GeoJSON} extent BBox [west, south, east, north] order or GeoJSON Polygon
@param {number} minZoom Minimum Zoom
@param {number} maxZoom Maximum Zoom
@returns {Array<Tile>} Tiles from extent
@example
const tiles = slippyGrid.all([-180.0, -90.0, 180, 90], 3, 8)
//=tiles
|
[
"All",
"Tiles",
"from",
"a",
"given",
"BBox"
] |
6bc936925441598543eafbdd83076257fe3e712b
|
https://github.com/DenisCarriere/slippy-grid/blob/6bc936925441598543eafbdd83076257fe3e712b/index.js#L108-L117
|
38,186 |
DenisCarriere/slippy-grid
|
index.js
|
levels
|
function levels (extent, minZoom, maxZoom) {
const extents = []
if (extent === undefined) throw new Error('extent is required')
if (minZoom === undefined) throw new Error('minZoom is required')
if (maxZoom === undefined) throw new Error('maxZoom is required')
// Single Array
if (extent.length === 4 && extent[0][0] === undefined) { extents.push({bbox: extent, minZoom, maxZoom}) }
// Multiple Array
if (extent.length && extent[0][0] !== undefined) { extent.map(inner => extents.push({bbox: inner, minZoom, maxZoom})) }
// GeoJSON
featureEach(extent, feature => {
const bbox = turfBBox(feature)
const featureMinZoom = feature.properties.minZoom || feature.properties.minzoom || minZoom
const featureMaxZoom = feature.properties.maxZoom || feature.properties.maxzoom || maxZoom
extents.push({bbox, minZoom: featureMinZoom, maxZoom: featureMaxZoom})
})
const levels = []
for (const {bbox, minZoom, maxZoom} of extents) {
let [x1, y1, x2, y2] = bbox
for (const zoom of range(minZoom, maxZoom + 1)) {
if (y2 > 85) y2 = 85
if (y2 < -85) y2 = -85
const t1 = lngLatToTile([x1, y1], zoom)
const t2 = lngLatToTile([x2, y2], zoom)
// Columns
let columns = []
// Fiji - World divided into two parts
if (t1[0] > t2[0]) {
// right world +180 degrees
const maxtx = Math.pow(2, zoom) - 1
const rightColumns = range(t1[0], maxtx + 1)
rightColumns.forEach(column => columns.push(column))
// left world -180 degrees
const mintx = 0
const leftColumns = range(mintx, t2[0] + 1)
leftColumns.forEach(column => columns.push(column))
} else {
// Normal World
const mintx = Math.min(t1[0], t2[0])
const maxtx = Math.max(t1[0], t2[0])
columns = range(mintx, maxtx + 1)
}
// Rows
const minty = Math.min(t1[1], t2[1])
const maxty = Math.max(t1[1], t2[1])
const rows = range(minty, maxty + 1)
levels.push([columns, rows, zoom])
}
}
return levels
}
|
javascript
|
function levels (extent, minZoom, maxZoom) {
const extents = []
if (extent === undefined) throw new Error('extent is required')
if (minZoom === undefined) throw new Error('minZoom is required')
if (maxZoom === undefined) throw new Error('maxZoom is required')
// Single Array
if (extent.length === 4 && extent[0][0] === undefined) { extents.push({bbox: extent, minZoom, maxZoom}) }
// Multiple Array
if (extent.length && extent[0][0] !== undefined) { extent.map(inner => extents.push({bbox: inner, minZoom, maxZoom})) }
// GeoJSON
featureEach(extent, feature => {
const bbox = turfBBox(feature)
const featureMinZoom = feature.properties.minZoom || feature.properties.minzoom || minZoom
const featureMaxZoom = feature.properties.maxZoom || feature.properties.maxzoom || maxZoom
extents.push({bbox, minZoom: featureMinZoom, maxZoom: featureMaxZoom})
})
const levels = []
for (const {bbox, minZoom, maxZoom} of extents) {
let [x1, y1, x2, y2] = bbox
for (const zoom of range(minZoom, maxZoom + 1)) {
if (y2 > 85) y2 = 85
if (y2 < -85) y2 = -85
const t1 = lngLatToTile([x1, y1], zoom)
const t2 = lngLatToTile([x2, y2], zoom)
// Columns
let columns = []
// Fiji - World divided into two parts
if (t1[0] > t2[0]) {
// right world +180 degrees
const maxtx = Math.pow(2, zoom) - 1
const rightColumns = range(t1[0], maxtx + 1)
rightColumns.forEach(column => columns.push(column))
// left world -180 degrees
const mintx = 0
const leftColumns = range(mintx, t2[0] + 1)
leftColumns.forEach(column => columns.push(column))
} else {
// Normal World
const mintx = Math.min(t1[0], t2[0])
const maxtx = Math.max(t1[0], t2[0])
columns = range(mintx, maxtx + 1)
}
// Rows
const minty = Math.min(t1[1], t2[1])
const maxty = Math.max(t1[1], t2[1])
const rows = range(minty, maxty + 1)
levels.push([columns, rows, zoom])
}
}
return levels
}
|
[
"function",
"levels",
"(",
"extent",
",",
"minZoom",
",",
"maxZoom",
")",
"{",
"const",
"extents",
"=",
"[",
"]",
"if",
"(",
"extent",
"===",
"undefined",
")",
"throw",
"new",
"Error",
"(",
"'extent is required'",
")",
"if",
"(",
"minZoom",
"===",
"undefined",
")",
"throw",
"new",
"Error",
"(",
"'minZoom is required'",
")",
"if",
"(",
"maxZoom",
"===",
"undefined",
")",
"throw",
"new",
"Error",
"(",
"'maxZoom is required'",
")",
"// Single Array",
"if",
"(",
"extent",
".",
"length",
"===",
"4",
"&&",
"extent",
"[",
"0",
"]",
"[",
"0",
"]",
"===",
"undefined",
")",
"{",
"extents",
".",
"push",
"(",
"{",
"bbox",
":",
"extent",
",",
"minZoom",
",",
"maxZoom",
"}",
")",
"}",
"// Multiple Array",
"if",
"(",
"extent",
".",
"length",
"&&",
"extent",
"[",
"0",
"]",
"[",
"0",
"]",
"!==",
"undefined",
")",
"{",
"extent",
".",
"map",
"(",
"inner",
"=>",
"extents",
".",
"push",
"(",
"{",
"bbox",
":",
"inner",
",",
"minZoom",
",",
"maxZoom",
"}",
")",
")",
"}",
"// GeoJSON",
"featureEach",
"(",
"extent",
",",
"feature",
"=>",
"{",
"const",
"bbox",
"=",
"turfBBox",
"(",
"feature",
")",
"const",
"featureMinZoom",
"=",
"feature",
".",
"properties",
".",
"minZoom",
"||",
"feature",
".",
"properties",
".",
"minzoom",
"||",
"minZoom",
"const",
"featureMaxZoom",
"=",
"feature",
".",
"properties",
".",
"maxZoom",
"||",
"feature",
".",
"properties",
".",
"maxzoom",
"||",
"maxZoom",
"extents",
".",
"push",
"(",
"{",
"bbox",
",",
"minZoom",
":",
"featureMinZoom",
",",
"maxZoom",
":",
"featureMaxZoom",
"}",
")",
"}",
")",
"const",
"levels",
"=",
"[",
"]",
"for",
"(",
"const",
"{",
"bbox",
",",
"minZoom",
",",
"maxZoom",
"}",
"of",
"extents",
")",
"{",
"let",
"[",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
"]",
"=",
"bbox",
"for",
"(",
"const",
"zoom",
"of",
"range",
"(",
"minZoom",
",",
"maxZoom",
"+",
"1",
")",
")",
"{",
"if",
"(",
"y2",
">",
"85",
")",
"y2",
"=",
"85",
"if",
"(",
"y2",
"<",
"-",
"85",
")",
"y2",
"=",
"-",
"85",
"const",
"t1",
"=",
"lngLatToTile",
"(",
"[",
"x1",
",",
"y1",
"]",
",",
"zoom",
")",
"const",
"t2",
"=",
"lngLatToTile",
"(",
"[",
"x2",
",",
"y2",
"]",
",",
"zoom",
")",
"// Columns",
"let",
"columns",
"=",
"[",
"]",
"// Fiji - World divided into two parts",
"if",
"(",
"t1",
"[",
"0",
"]",
">",
"t2",
"[",
"0",
"]",
")",
"{",
"// right world +180 degrees",
"const",
"maxtx",
"=",
"Math",
".",
"pow",
"(",
"2",
",",
"zoom",
")",
"-",
"1",
"const",
"rightColumns",
"=",
"range",
"(",
"t1",
"[",
"0",
"]",
",",
"maxtx",
"+",
"1",
")",
"rightColumns",
".",
"forEach",
"(",
"column",
"=>",
"columns",
".",
"push",
"(",
"column",
")",
")",
"// left world -180 degrees",
"const",
"mintx",
"=",
"0",
"const",
"leftColumns",
"=",
"range",
"(",
"mintx",
",",
"t2",
"[",
"0",
"]",
"+",
"1",
")",
"leftColumns",
".",
"forEach",
"(",
"column",
"=>",
"columns",
".",
"push",
"(",
"column",
")",
")",
"}",
"else",
"{",
"// Normal World",
"const",
"mintx",
"=",
"Math",
".",
"min",
"(",
"t1",
"[",
"0",
"]",
",",
"t2",
"[",
"0",
"]",
")",
"const",
"maxtx",
"=",
"Math",
".",
"max",
"(",
"t1",
"[",
"0",
"]",
",",
"t2",
"[",
"0",
"]",
")",
"columns",
"=",
"range",
"(",
"mintx",
",",
"maxtx",
"+",
"1",
")",
"}",
"// Rows",
"const",
"minty",
"=",
"Math",
".",
"min",
"(",
"t1",
"[",
"1",
"]",
",",
"t2",
"[",
"1",
"]",
")",
"const",
"maxty",
"=",
"Math",
".",
"max",
"(",
"t1",
"[",
"1",
"]",
",",
"t2",
"[",
"1",
"]",
")",
"const",
"rows",
"=",
"range",
"(",
"minty",
",",
"maxty",
"+",
"1",
")",
"levels",
".",
"push",
"(",
"[",
"columns",
",",
"rows",
",",
"zoom",
"]",
")",
"}",
"}",
"return",
"levels",
"}"
] |
Creates a grid level pattern of arrays
@param {BBox|BBox[]|GeoJSON} extent BBox [west, south, east, north] order or GeoJSON Polygon
@param {number} minZoom Minimum Zoom
@param {number} maxZoom Maximum Zoom
@returns {GridLevel[]} Grid Level
@example
const levels = slippyGrid.levels([-180.0, -90.0, 180, 90], 3, 8)
//=levels
|
[
"Creates",
"a",
"grid",
"level",
"pattern",
"of",
"arrays"
] |
6bc936925441598543eafbdd83076257fe3e712b
|
https://github.com/DenisCarriere/slippy-grid/blob/6bc936925441598543eafbdd83076257fe3e712b/index.js#L165-L222
|
38,187 |
DenisCarriere/slippy-grid
|
index.js
|
count
|
function count (extent, minZoom, maxZoom, quick) {
quick = quick || 1000
let count = 0
// Quick count
if (quick !== -1) {
for (const [columns, rows] of levels(extent, minZoom, maxZoom)) {
count += rows.length * columns.length
}
if (count > quick) { return count }
}
// Accurate count
count = 0
const grid = single(extent, minZoom, maxZoom)
while (true) {
const {done} = grid.next()
if (done) { break }
count++
}
return count
}
|
javascript
|
function count (extent, minZoom, maxZoom, quick) {
quick = quick || 1000
let count = 0
// Quick count
if (quick !== -1) {
for (const [columns, rows] of levels(extent, minZoom, maxZoom)) {
count += rows.length * columns.length
}
if (count > quick) { return count }
}
// Accurate count
count = 0
const grid = single(extent, minZoom, maxZoom)
while (true) {
const {done} = grid.next()
if (done) { break }
count++
}
return count
}
|
[
"function",
"count",
"(",
"extent",
",",
"minZoom",
",",
"maxZoom",
",",
"quick",
")",
"{",
"quick",
"=",
"quick",
"||",
"1000",
"let",
"count",
"=",
"0",
"// Quick count",
"if",
"(",
"quick",
"!==",
"-",
"1",
")",
"{",
"for",
"(",
"const",
"[",
"columns",
",",
"rows",
"]",
"of",
"levels",
"(",
"extent",
",",
"minZoom",
",",
"maxZoom",
")",
")",
"{",
"count",
"+=",
"rows",
".",
"length",
"*",
"columns",
".",
"length",
"}",
"if",
"(",
"count",
">",
"quick",
")",
"{",
"return",
"count",
"}",
"}",
"// Accurate count",
"count",
"=",
"0",
"const",
"grid",
"=",
"single",
"(",
"extent",
",",
"minZoom",
",",
"maxZoom",
")",
"while",
"(",
"true",
")",
"{",
"const",
"{",
"done",
"}",
"=",
"grid",
".",
"next",
"(",
")",
"if",
"(",
"done",
")",
"{",
"break",
"}",
"count",
"++",
"}",
"return",
"count",
"}"
] |
Counts the total amount of tiles from a given BBox
@param {BBox|BBox[]|GeoJSON} extent BBox [west, south, east, north] order or GeoJSON Polygon
@param {number} minZoom Minimum Zoom
@param {number} maxZoom Maximum Zoom
@param {number} [quick=1000] Enable quick count if greater than number
@returns {number} Total tiles from BBox
@example
const count = slippyGrid.count([-180.0, -90.0, 180, 90], 3, 8)
//=count 563136
|
[
"Counts",
"the",
"total",
"amount",
"of",
"tiles",
"from",
"a",
"given",
"BBox"
] |
6bc936925441598543eafbdd83076257fe3e712b
|
https://github.com/DenisCarriere/slippy-grid/blob/6bc936925441598543eafbdd83076257fe3e712b/index.js#L236-L257
|
38,188 |
base/base-env
|
lib/env.js
|
normalize
|
function normalize(file, fn) {
var orig = utils.extend({}, file);
// support paths
if (typeof fn === 'string') {
file.type = 'path';
file.path = fn;
file.origPath = fn;
file = resolve(file, file.options);
// support functions
} else if (typeof fn === 'function') {
file.type = 'function';
file.path = file.name;
file.fn = fn;
// support instances
} else if (utils.isAppArg(file.app)) {
file.type = 'app';
file.path = file.name;
file.app = fn;
} else {
throw new TypeError('expected env to be a string or function');
}
if (file === null) {
var name = typeof fn === 'string' ? fn : orig.key;
throw new Error('cannot resolve: ' + util.inspect(name));
}
return file;
}
|
javascript
|
function normalize(file, fn) {
var orig = utils.extend({}, file);
// support paths
if (typeof fn === 'string') {
file.type = 'path';
file.path = fn;
file.origPath = fn;
file = resolve(file, file.options);
// support functions
} else if (typeof fn === 'function') {
file.type = 'function';
file.path = file.name;
file.fn = fn;
// support instances
} else if (utils.isAppArg(file.app)) {
file.type = 'app';
file.path = file.name;
file.app = fn;
} else {
throw new TypeError('expected env to be a string or function');
}
if (file === null) {
var name = typeof fn === 'string' ? fn : orig.key;
throw new Error('cannot resolve: ' + util.inspect(name));
}
return file;
}
|
[
"function",
"normalize",
"(",
"file",
",",
"fn",
")",
"{",
"var",
"orig",
"=",
"utils",
".",
"extend",
"(",
"{",
"}",
",",
"file",
")",
";",
"// support paths",
"if",
"(",
"typeof",
"fn",
"===",
"'string'",
")",
"{",
"file",
".",
"type",
"=",
"'path'",
";",
"file",
".",
"path",
"=",
"fn",
";",
"file",
".",
"origPath",
"=",
"fn",
";",
"file",
"=",
"resolve",
"(",
"file",
",",
"file",
".",
"options",
")",
";",
"// support functions",
"}",
"else",
"if",
"(",
"typeof",
"fn",
"===",
"'function'",
")",
"{",
"file",
".",
"type",
"=",
"'function'",
";",
"file",
".",
"path",
"=",
"file",
".",
"name",
";",
"file",
".",
"fn",
"=",
"fn",
";",
"// support instances",
"}",
"else",
"if",
"(",
"utils",
".",
"isAppArg",
"(",
"file",
".",
"app",
")",
")",
"{",
"file",
".",
"type",
"=",
"'app'",
";",
"file",
".",
"path",
"=",
"file",
".",
"name",
";",
"file",
".",
"app",
"=",
"fn",
";",
"}",
"else",
"{",
"throw",
"new",
"TypeError",
"(",
"'expected env to be a string or function'",
")",
";",
"}",
"if",
"(",
"file",
"===",
"null",
")",
"{",
"var",
"name",
"=",
"typeof",
"fn",
"===",
"'string'",
"?",
"fn",
":",
"orig",
".",
"key",
";",
"throw",
"new",
"Error",
"(",
"'cannot resolve: '",
"+",
"util",
".",
"inspect",
"(",
"name",
")",
")",
";",
"}",
"return",
"file",
";",
"}"
] |
Create a file object with normalized `fn`, `path` or `app` properties
|
[
"Create",
"a",
"file",
"object",
"with",
"normalized",
"fn",
"path",
"or",
"app",
"properties"
] |
2140c8f12e3d21aba443666a481d71f15da900c2
|
https://github.com/base/base-env/blob/2140c8f12e3d21aba443666a481d71f15da900c2/lib/env.js#L196-L227
|
38,189 |
node-modules/antpb
|
lib/encoder.js
|
genTypePartial
|
function genTypePartial(gen, field, fieldIndex, ref) {
return field.resolvedType.group ?
gen('types[%i].encode(%s,w.uint32(%i)).uint32(%i)', fieldIndex, ref, (field.id << 3 | 3) >>> 0, (field.id << 3 | 4) >>> 0) :
gen('types[%i].encode(%s,w.uint32(%i).fork()).ldelim()', fieldIndex, ref, (field.id << 3 | 2) >>> 0);
}
|
javascript
|
function genTypePartial(gen, field, fieldIndex, ref) {
return field.resolvedType.group ?
gen('types[%i].encode(%s,w.uint32(%i)).uint32(%i)', fieldIndex, ref, (field.id << 3 | 3) >>> 0, (field.id << 3 | 4) >>> 0) :
gen('types[%i].encode(%s,w.uint32(%i).fork()).ldelim()', fieldIndex, ref, (field.id << 3 | 2) >>> 0);
}
|
[
"function",
"genTypePartial",
"(",
"gen",
",",
"field",
",",
"fieldIndex",
",",
"ref",
")",
"{",
"return",
"field",
".",
"resolvedType",
".",
"group",
"?",
"gen",
"(",
"'types[%i].encode(%s,w.uint32(%i)).uint32(%i)'",
",",
"fieldIndex",
",",
"ref",
",",
"(",
"field",
".",
"id",
"<<",
"3",
"|",
"3",
")",
">>>",
"0",
",",
"(",
"field",
".",
"id",
"<<",
"3",
"|",
"4",
")",
">>>",
"0",
")",
":",
"gen",
"(",
"'types[%i].encode(%s,w.uint32(%i).fork()).ldelim()'",
",",
"fieldIndex",
",",
"ref",
",",
"(",
"field",
".",
"id",
"<<",
"3",
"|",
"2",
")",
">>>",
"0",
")",
";",
"}"
] |
Generates a partial message type encoder.
@param {Codegen} gen Codegen instance
@param {Field} field Reflected field
@param {number} fieldIndex Field index
@param {string} ref Variable reference
@return {Codegen} Codegen instance
@ignore
|
[
"Generates",
"a",
"partial",
"message",
"type",
"encoder",
"."
] |
e6d74d4c372151fcb3880eb44a4e85907d99405c
|
https://github.com/node-modules/antpb/blob/e6d74d4c372151fcb3880eb44a4e85907d99405c/lib/encoder.js#L17-L21
|
38,190 |
crysalead-js/dom-layer
|
src/node/patcher/attrs.js
|
patch
|
function patch(element, previous, attrs) {
if (!previous && !attrs) {
return attrs;
}
var name, value;
previous = previous || {};
attrs = attrs || {};
for (name in previous) {
if (previous[name] && !attrs[name]) {
unset(name, element, previous);
}
}
for (name in attrs) {
if (previous[name] === attrs[name]) {
continue;
}
if (attrs[name] || attrs[name] === '') {
set(name, element, previous, attrs);
}
}
return attrs;
}
|
javascript
|
function patch(element, previous, attrs) {
if (!previous && !attrs) {
return attrs;
}
var name, value;
previous = previous || {};
attrs = attrs || {};
for (name in previous) {
if (previous[name] && !attrs[name]) {
unset(name, element, previous);
}
}
for (name in attrs) {
if (previous[name] === attrs[name]) {
continue;
}
if (attrs[name] || attrs[name] === '') {
set(name, element, previous, attrs);
}
}
return attrs;
}
|
[
"function",
"patch",
"(",
"element",
",",
"previous",
",",
"attrs",
")",
"{",
"if",
"(",
"!",
"previous",
"&&",
"!",
"attrs",
")",
"{",
"return",
"attrs",
";",
"}",
"var",
"name",
",",
"value",
";",
"previous",
"=",
"previous",
"||",
"{",
"}",
";",
"attrs",
"=",
"attrs",
"||",
"{",
"}",
";",
"for",
"(",
"name",
"in",
"previous",
")",
"{",
"if",
"(",
"previous",
"[",
"name",
"]",
"&&",
"!",
"attrs",
"[",
"name",
"]",
")",
"{",
"unset",
"(",
"name",
",",
"element",
",",
"previous",
")",
";",
"}",
"}",
"for",
"(",
"name",
"in",
"attrs",
")",
"{",
"if",
"(",
"previous",
"[",
"name",
"]",
"===",
"attrs",
"[",
"name",
"]",
")",
"{",
"continue",
";",
"}",
"if",
"(",
"attrs",
"[",
"name",
"]",
"||",
"attrs",
"[",
"name",
"]",
"===",
"''",
")",
"{",
"set",
"(",
"name",
",",
"element",
",",
"previous",
",",
"attrs",
")",
";",
"}",
"}",
"return",
"attrs",
";",
"}"
] |
Maintains state of element attributes.
@param Object element A DOM element.
@param Object previous The previous state of attributes.
@param Object attrs The attributes to match on.
@return Object attrs The element attributes state.
|
[
"Maintains",
"state",
"of",
"element",
"attributes",
"."
] |
0c3509fe1b6c4cd2ce0c030b73791f951f5f97a2
|
https://github.com/crysalead-js/dom-layer/blob/0c3509fe1b6c4cd2ce0c030b73791f951f5f97a2/src/node/patcher/attrs.js#L14-L36
|
38,191 |
crysalead-js/dom-layer
|
src/node/patcher/attrs.js
|
set
|
function set(name, element, previous, attrs) {
if (set.handlers[name]) {
set.handlers[name](name, element, previous, attrs);
} else if (attrs[name] != null && previous[name] !== attrs[name]) {
element.setAttribute(name, attrs[name]);
}
}
|
javascript
|
function set(name, element, previous, attrs) {
if (set.handlers[name]) {
set.handlers[name](name, element, previous, attrs);
} else if (attrs[name] != null && previous[name] !== attrs[name]) {
element.setAttribute(name, attrs[name]);
}
}
|
[
"function",
"set",
"(",
"name",
",",
"element",
",",
"previous",
",",
"attrs",
")",
"{",
"if",
"(",
"set",
".",
"handlers",
"[",
"name",
"]",
")",
"{",
"set",
".",
"handlers",
"[",
"name",
"]",
"(",
"name",
",",
"element",
",",
"previous",
",",
"attrs",
")",
";",
"}",
"else",
"if",
"(",
"attrs",
"[",
"name",
"]",
"!=",
"null",
"&&",
"previous",
"[",
"name",
"]",
"!==",
"attrs",
"[",
"name",
"]",
")",
"{",
"element",
".",
"setAttribute",
"(",
"name",
",",
"attrs",
"[",
"name",
"]",
")",
";",
"}",
"}"
] |
Sets an attribute.
@param String name The attribute name to set.
@param Object element A DOM element.
@param Object previous The previous state of attributes.
@param Object attrs The attributes to match on.
|
[
"Sets",
"an",
"attribute",
"."
] |
0c3509fe1b6c4cd2ce0c030b73791f951f5f97a2
|
https://github.com/crysalead-js/dom-layer/blob/0c3509fe1b6c4cd2ce0c030b73791f951f5f97a2/src/node/patcher/attrs.js#L46-L52
|
38,192 |
crysalead-js/dom-layer
|
src/node/patcher/attrs.js
|
unset
|
function unset(name, element, previous) {
if (unset.handlers[name]) {
unset.handlers[name](name, element, previous);
} else {
element.removeAttribute(name);
}
}
|
javascript
|
function unset(name, element, previous) {
if (unset.handlers[name]) {
unset.handlers[name](name, element, previous);
} else {
element.removeAttribute(name);
}
}
|
[
"function",
"unset",
"(",
"name",
",",
"element",
",",
"previous",
")",
"{",
"if",
"(",
"unset",
".",
"handlers",
"[",
"name",
"]",
")",
"{",
"unset",
".",
"handlers",
"[",
"name",
"]",
"(",
"name",
",",
"element",
",",
"previous",
")",
";",
"}",
"else",
"{",
"element",
".",
"removeAttribute",
"(",
"name",
")",
";",
"}",
"}"
] |
Unsets an attribute.
@param String name The attribute name to unset.
@param Object element A DOM element.
@param Object previous The previous state of attributes.
|
[
"Unsets",
"an",
"attribute",
"."
] |
0c3509fe1b6c4cd2ce0c030b73791f951f5f97a2
|
https://github.com/crysalead-js/dom-layer/blob/0c3509fe1b6c4cd2ce0c030b73791f951f5f97a2/src/node/patcher/attrs.js#L62-L68
|
38,193 |
DenisCarriere/slippy-grid
|
dependencies/tilebelt.js
|
getParent
|
function getParent(tile) {
// top left
if (tile[0] % 2 === 0 && tile[1] % 2 === 0) {
return [tile[0] / 2, tile[1] / 2, tile[2] - 1];
}
// bottom left
if ((tile[0] % 2 === 0) && (!tile[1] % 2 === 0)) {
return [tile[0] / 2, (tile[1] - 1) / 2, tile[2] - 1];
}
// top right
if ((!tile[0] % 2 === 0) && (tile[1] % 2 === 0)) {
return [(tile[0] - 1) / 2, (tile[1]) / 2, tile[2] - 1];
}
// bottom right
return [(tile[0] - 1) / 2, (tile[1] - 1) / 2, tile[2] - 1];
}
|
javascript
|
function getParent(tile) {
// top left
if (tile[0] % 2 === 0 && tile[1] % 2 === 0) {
return [tile[0] / 2, tile[1] / 2, tile[2] - 1];
}
// bottom left
if ((tile[0] % 2 === 0) && (!tile[1] % 2 === 0)) {
return [tile[0] / 2, (tile[1] - 1) / 2, tile[2] - 1];
}
// top right
if ((!tile[0] % 2 === 0) && (tile[1] % 2 === 0)) {
return [(tile[0] - 1) / 2, (tile[1]) / 2, tile[2] - 1];
}
// bottom right
return [(tile[0] - 1) / 2, (tile[1] - 1) / 2, tile[2] - 1];
}
|
[
"function",
"getParent",
"(",
"tile",
")",
"{",
"// top left",
"if",
"(",
"tile",
"[",
"0",
"]",
"%",
"2",
"===",
"0",
"&&",
"tile",
"[",
"1",
"]",
"%",
"2",
"===",
"0",
")",
"{",
"return",
"[",
"tile",
"[",
"0",
"]",
"/",
"2",
",",
"tile",
"[",
"1",
"]",
"/",
"2",
",",
"tile",
"[",
"2",
"]",
"-",
"1",
"]",
";",
"}",
"// bottom left",
"if",
"(",
"(",
"tile",
"[",
"0",
"]",
"%",
"2",
"===",
"0",
")",
"&&",
"(",
"!",
"tile",
"[",
"1",
"]",
"%",
"2",
"===",
"0",
")",
")",
"{",
"return",
"[",
"tile",
"[",
"0",
"]",
"/",
"2",
",",
"(",
"tile",
"[",
"1",
"]",
"-",
"1",
")",
"/",
"2",
",",
"tile",
"[",
"2",
"]",
"-",
"1",
"]",
";",
"}",
"// top right",
"if",
"(",
"(",
"!",
"tile",
"[",
"0",
"]",
"%",
"2",
"===",
"0",
")",
"&&",
"(",
"tile",
"[",
"1",
"]",
"%",
"2",
"===",
"0",
")",
")",
"{",
"return",
"[",
"(",
"tile",
"[",
"0",
"]",
"-",
"1",
")",
"/",
"2",
",",
"(",
"tile",
"[",
"1",
"]",
")",
"/",
"2",
",",
"tile",
"[",
"2",
"]",
"-",
"1",
"]",
";",
"}",
"// bottom right",
"return",
"[",
"(",
"tile",
"[",
"0",
"]",
"-",
"1",
")",
"/",
"2",
",",
"(",
"tile",
"[",
"1",
"]",
"-",
"1",
")",
"/",
"2",
",",
"tile",
"[",
"2",
"]",
"-",
"1",
"]",
";",
"}"
] |
Get the tile one zoom level lower
@name getParent
@param {Array<number>} tile
@returns {Array<number>} tile
@example
var tile = getParent([5, 10, 10])
//=tile
|
[
"Get",
"the",
"tile",
"one",
"zoom",
"level",
"lower"
] |
6bc936925441598543eafbdd83076257fe3e712b
|
https://github.com/DenisCarriere/slippy-grid/blob/6bc936925441598543eafbdd83076257fe3e712b/dependencies/tilebelt.js#L106-L121
|
38,194 |
sakitam-fdd/rollup-plugin-copied
|
src/index.js
|
copyFile
|
function copyFile (src, dest) {
return new Promise((resolve, reject) => {
const read = fs.createReadStream(src);
read.on('error', reject);
const write = fs.createWriteStream(dest);
write.on('error', reject);
write.on('finish', resolve);
read.pipe(write);
})
}
|
javascript
|
function copyFile (src, dest) {
return new Promise((resolve, reject) => {
const read = fs.createReadStream(src);
read.on('error', reject);
const write = fs.createWriteStream(dest);
write.on('error', reject);
write.on('finish', resolve);
read.pipe(write);
})
}
|
[
"function",
"copyFile",
"(",
"src",
",",
"dest",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"const",
"read",
"=",
"fs",
".",
"createReadStream",
"(",
"src",
")",
";",
"read",
".",
"on",
"(",
"'error'",
",",
"reject",
")",
";",
"const",
"write",
"=",
"fs",
".",
"createWriteStream",
"(",
"dest",
")",
";",
"write",
".",
"on",
"(",
"'error'",
",",
"reject",
")",
";",
"write",
".",
"on",
"(",
"'finish'",
",",
"resolve",
")",
";",
"read",
".",
"pipe",
"(",
"write",
")",
";",
"}",
")",
"}"
] |
copy file to dir
@param src
@param dest
@returns {Promise<any>}
|
[
"copy",
"file",
"to",
"dir"
] |
d9d16f90ea87b958d39ebba5824efce110e25468
|
https://github.com/sakitam-fdd/rollup-plugin-copied/blob/d9d16f90ea87b958d39ebba5824efce110e25468/src/index.js#L96-L105
|
38,195 |
amida-tech/blue-button-cms
|
lib/parser.js
|
parseCMS
|
function parseCMS(fileString) {
var intObj = txtToIntObj(fileString);
var result = cmsObjConverter.convertToBBModel(intObj);
return result;
}
|
javascript
|
function parseCMS(fileString) {
var intObj = txtToIntObj(fileString);
var result = cmsObjConverter.convertToBBModel(intObj);
return result;
}
|
[
"function",
"parseCMS",
"(",
"fileString",
")",
"{",
"var",
"intObj",
"=",
"txtToIntObj",
"(",
"fileString",
")",
";",
"var",
"result",
"=",
"cmsObjConverter",
".",
"convertToBBModel",
"(",
"intObj",
")",
";",
"return",
"result",
";",
"}"
] |
parses CMS BB text format into BB JSON
|
[
"parses",
"CMS",
"BB",
"text",
"format",
"into",
"BB",
"JSON"
] |
749b8cf071910b22f8176a9ed8fc3b05062e1aad
|
https://github.com/amida-tech/blue-button-cms/blob/749b8cf071910b22f8176a9ed8fc3b05062e1aad/lib/parser.js#L8-L15
|
38,196 |
amida-tech/blue-button-cms
|
lib/cmsTxtToIntObj.js
|
clean
|
function clean(cmsString) {
if (cmsString.indexOf('\r\n') >= 0) {
cmsString = cmsString.replace(/\r\n/g, '\n');
cmsString = cmsString.replace(/\r/g, '\n');
}
cmsString = cmsString.replace(/\n{5,}/g, '\n\n\n\n'); //more than 5 line breaks breaks the parser
return cmsString;
}
|
javascript
|
function clean(cmsString) {
if (cmsString.indexOf('\r\n') >= 0) {
cmsString = cmsString.replace(/\r\n/g, '\n');
cmsString = cmsString.replace(/\r/g, '\n');
}
cmsString = cmsString.replace(/\n{5,}/g, '\n\n\n\n'); //more than 5 line breaks breaks the parser
return cmsString;
}
|
[
"function",
"clean",
"(",
"cmsString",
")",
"{",
"if",
"(",
"cmsString",
".",
"indexOf",
"(",
"'\\r\\n'",
")",
">=",
"0",
")",
"{",
"cmsString",
"=",
"cmsString",
".",
"replace",
"(",
"/",
"\\r\\n",
"/",
"g",
",",
"'\\n'",
")",
";",
"cmsString",
"=",
"cmsString",
".",
"replace",
"(",
"/",
"\\r",
"/",
"g",
",",
"'\\n'",
")",
";",
"}",
"cmsString",
"=",
"cmsString",
".",
"replace",
"(",
"/",
"\\n{5,}",
"/",
"g",
",",
"'\\n\\n\\n\\n'",
")",
";",
"//more than 5 line breaks breaks the parser",
"return",
"cmsString",
";",
"}"
] |
main function that will be used to getIntObj
|
[
"main",
"function",
"that",
"will",
"be",
"used",
"to",
"getIntObj"
] |
749b8cf071910b22f8176a9ed8fc3b05062e1aad
|
https://github.com/amida-tech/blue-button-cms/blob/749b8cf071910b22f8176a9ed8fc3b05062e1aad/lib/cmsTxtToIntObj.js#L68-L75
|
38,197 |
amida-tech/blue-button-cms
|
lib/cmsTxtToIntObj.js
|
separateSections
|
function separateSections(data) {
//Separated regular expression into many distinct pieces
//specical metaMatchCode goes first.
// 1st regular expression for meta, need to do
var metaMatchCode = '^(-).[\\S\\s]+?(\\n){2,}'; //this isn't used anywhere...
/* 2nd regular expression for claims, because the structure of claims is
unique */
var claimsHeaderMatchCode = '(-){4,}(\\n)*Claim Summary(\\n){2,}(-){4,}';
var claimsBodyMatchCode = '([\\S\\s]+Claim[\\S\\s]+)+';
var claimsEndMatchCode = '(?=((-){4,}))';
var claimsMatchCode = claimsHeaderMatchCode +
claimsBodyMatchCode + claimsEndMatchCode;
//this match code is for all other sections
var headerMatchCode = '(-){4,}[\\S\\s]+?(\\n){2,}(-){4,}';
var bodyMatchCode = '[\\S\\s]+?';
var endMatchCode = '(?=((-){4,}))';
var sectionMatchCode = headerMatchCode + bodyMatchCode + endMatchCode;
/* The regular expression for everything, search globally and
ignore capitalization */
var totalMatchCode = claimsMatchCode + "|" + sectionMatchCode;
var totalRegExp = new RegExp(totalMatchCode, 'gi');
var matchArray = data.match(totalRegExp);
return matchArray;
}
|
javascript
|
function separateSections(data) {
//Separated regular expression into many distinct pieces
//specical metaMatchCode goes first.
// 1st regular expression for meta, need to do
var metaMatchCode = '^(-).[\\S\\s]+?(\\n){2,}'; //this isn't used anywhere...
/* 2nd regular expression for claims, because the structure of claims is
unique */
var claimsHeaderMatchCode = '(-){4,}(\\n)*Claim Summary(\\n){2,}(-){4,}';
var claimsBodyMatchCode = '([\\S\\s]+Claim[\\S\\s]+)+';
var claimsEndMatchCode = '(?=((-){4,}))';
var claimsMatchCode = claimsHeaderMatchCode +
claimsBodyMatchCode + claimsEndMatchCode;
//this match code is for all other sections
var headerMatchCode = '(-){4,}[\\S\\s]+?(\\n){2,}(-){4,}';
var bodyMatchCode = '[\\S\\s]+?';
var endMatchCode = '(?=((-){4,}))';
var sectionMatchCode = headerMatchCode + bodyMatchCode + endMatchCode;
/* The regular expression for everything, search globally and
ignore capitalization */
var totalMatchCode = claimsMatchCode + "|" + sectionMatchCode;
var totalRegExp = new RegExp(totalMatchCode, 'gi');
var matchArray = data.match(totalRegExp);
return matchArray;
}
|
[
"function",
"separateSections",
"(",
"data",
")",
"{",
"//Separated regular expression into many distinct pieces",
"//specical metaMatchCode goes first.",
"// 1st regular expression for meta, need to do",
"var",
"metaMatchCode",
"=",
"'^(-).[\\\\S\\\\s]+?(\\\\n){2,}'",
";",
"//this isn't used anywhere...",
"/* 2nd regular expression for claims, because the structure of claims is\n unique */",
"var",
"claimsHeaderMatchCode",
"=",
"'(-){4,}(\\\\n)*Claim Summary(\\\\n){2,}(-){4,}'",
";",
"var",
"claimsBodyMatchCode",
"=",
"'([\\\\S\\\\s]+Claim[\\\\S\\\\s]+)+'",
";",
"var",
"claimsEndMatchCode",
"=",
"'(?=((-){4,}))'",
";",
"var",
"claimsMatchCode",
"=",
"claimsHeaderMatchCode",
"+",
"claimsBodyMatchCode",
"+",
"claimsEndMatchCode",
";",
"//this match code is for all other sections",
"var",
"headerMatchCode",
"=",
"'(-){4,}[\\\\S\\\\s]+?(\\\\n){2,}(-){4,}'",
";",
"var",
"bodyMatchCode",
"=",
"'[\\\\S\\\\s]+?'",
";",
"var",
"endMatchCode",
"=",
"'(?=((-){4,}))'",
";",
"var",
"sectionMatchCode",
"=",
"headerMatchCode",
"+",
"bodyMatchCode",
"+",
"endMatchCode",
";",
"/* The regular expression for everything, search globally and\n ignore capitalization */",
"var",
"totalMatchCode",
"=",
"claimsMatchCode",
"+",
"\"|\"",
"+",
"sectionMatchCode",
";",
"var",
"totalRegExp",
"=",
"new",
"RegExp",
"(",
"totalMatchCode",
",",
"'gi'",
")",
";",
"var",
"matchArray",
"=",
"data",
".",
"match",
"(",
"totalRegExp",
")",
";",
"return",
"matchArray",
";",
"}"
] |
Parses string into sections, then returns the array of strings for each section
|
[
"Parses",
"string",
"into",
"sections",
"then",
"returns",
"the",
"array",
"of",
"strings",
"for",
"each",
"section"
] |
749b8cf071910b22f8176a9ed8fc3b05062e1aad
|
https://github.com/amida-tech/blue-button-cms/blob/749b8cf071910b22f8176a9ed8fc3b05062e1aad/lib/cmsTxtToIntObj.js#L80-L108
|
38,198 |
amida-tech/blue-button-cms
|
lib/cmsTxtToIntObj.js
|
cleanUpTitle
|
function cleanUpTitle(rawTitleString) {
/*dashChar is most commonly the dash of the title string, or a
the first repeating character surrounding the title */
var dashChar = rawTitleString.charAt(0);
//beginning and ending index of the dash
var dashBegIndex = 0;
var dashEndIndex = rawTitleString.lastIndexOf(dashChar);
//loop through to find indicies without continous dashes
while (rawTitleString.charAt(dashBegIndex) === (dashChar || '\n')) {
dashBegIndex++;
}
while (rawTitleString.charAt(dashEndIndex) === (dashChar || '\n')) {
dashEndIndex--;
}
var titleString = rawTitleString.slice(dashBegIndex + 1, dashEndIndex - 1);
titleString = trimStringEnds(titleString, ['\n', '-']);
return titleString;
}
|
javascript
|
function cleanUpTitle(rawTitleString) {
/*dashChar is most commonly the dash of the title string, or a
the first repeating character surrounding the title */
var dashChar = rawTitleString.charAt(0);
//beginning and ending index of the dash
var dashBegIndex = 0;
var dashEndIndex = rawTitleString.lastIndexOf(dashChar);
//loop through to find indicies without continous dashes
while (rawTitleString.charAt(dashBegIndex) === (dashChar || '\n')) {
dashBegIndex++;
}
while (rawTitleString.charAt(dashEndIndex) === (dashChar || '\n')) {
dashEndIndex--;
}
var titleString = rawTitleString.slice(dashBegIndex + 1, dashEndIndex - 1);
titleString = trimStringEnds(titleString, ['\n', '-']);
return titleString;
}
|
[
"function",
"cleanUpTitle",
"(",
"rawTitleString",
")",
"{",
"/*dashChar is most commonly the dash of the title string, or a\n the first repeating character surrounding the title */",
"var",
"dashChar",
"=",
"rawTitleString",
".",
"charAt",
"(",
"0",
")",
";",
"//beginning and ending index of the dash",
"var",
"dashBegIndex",
"=",
"0",
";",
"var",
"dashEndIndex",
"=",
"rawTitleString",
".",
"lastIndexOf",
"(",
"dashChar",
")",
";",
"//loop through to find indicies without continous dashes",
"while",
"(",
"rawTitleString",
".",
"charAt",
"(",
"dashBegIndex",
")",
"===",
"(",
"dashChar",
"||",
"'\\n'",
")",
")",
"{",
"dashBegIndex",
"++",
";",
"}",
"while",
"(",
"rawTitleString",
".",
"charAt",
"(",
"dashEndIndex",
")",
"===",
"(",
"dashChar",
"||",
"'\\n'",
")",
")",
"{",
"dashEndIndex",
"--",
";",
"}",
"var",
"titleString",
"=",
"rawTitleString",
".",
"slice",
"(",
"dashBegIndex",
"+",
"1",
",",
"dashEndIndex",
"-",
"1",
")",
";",
"titleString",
"=",
"trimStringEnds",
"(",
"titleString",
",",
"[",
"'\\n'",
",",
"'-'",
"]",
")",
";",
"return",
"titleString",
";",
"}"
] |
cleans up the title string obtained from the regular expression
|
[
"cleans",
"up",
"the",
"title",
"string",
"obtained",
"from",
"the",
"regular",
"expression"
] |
749b8cf071910b22f8176a9ed8fc3b05062e1aad
|
https://github.com/amida-tech/blue-button-cms/blob/749b8cf071910b22f8176a9ed8fc3b05062e1aad/lib/cmsTxtToIntObj.js#L112-L131
|
38,199 |
amida-tech/blue-button-cms
|
lib/cmsTxtToIntObj.js
|
processClaimsLineChild
|
function processClaimsLineChild(objectString) {
var claimLineObj = {};
var obj = {};
var objArray = [];
var keyValuePairRegExp = /(\n){1,}[\S\s,]+?(:)[\S\s]+?(?=((\n){1,})|$)/gi;
var keyValuePairArray = objectString.match(keyValuePairRegExp);
//unusual steps are required to parse meta data and claims summary
for (var s = 0; s < keyValuePairArray.length; s++) {
//clean up the key value pair
var keyValuePairString = trimStringEnds(keyValuePairArray[s], ['\n']);
//split each string by the :, the result is an array of size two
var keyValuePair = keyValuePairString.split(/:(.*)/);
var key = removeUnwantedCharacters(keyValuePair[0].trim(), ['\n', '-']);
key = key.toLowerCase();
var value = keyValuePair[1].trim();
var claimLineCheckRegExp = /claim lines/i;
if (claimLineCheckRegExp.test(key)) {
claimLineObj.claimNumber = value;
continue;
}
if (value.length === 0) {
value = null;
}
//create a new object for line number
if (key in obj) {
objArray.push(obj);
obj = {};
}
obj[key] = value;
}
objArray.push(obj);
claimLineObj.data = objArray;
return claimLineObj;
}
|
javascript
|
function processClaimsLineChild(objectString) {
var claimLineObj = {};
var obj = {};
var objArray = [];
var keyValuePairRegExp = /(\n){1,}[\S\s,]+?(:)[\S\s]+?(?=((\n){1,})|$)/gi;
var keyValuePairArray = objectString.match(keyValuePairRegExp);
//unusual steps are required to parse meta data and claims summary
for (var s = 0; s < keyValuePairArray.length; s++) {
//clean up the key value pair
var keyValuePairString = trimStringEnds(keyValuePairArray[s], ['\n']);
//split each string by the :, the result is an array of size two
var keyValuePair = keyValuePairString.split(/:(.*)/);
var key = removeUnwantedCharacters(keyValuePair[0].trim(), ['\n', '-']);
key = key.toLowerCase();
var value = keyValuePair[1].trim();
var claimLineCheckRegExp = /claim lines/i;
if (claimLineCheckRegExp.test(key)) {
claimLineObj.claimNumber = value;
continue;
}
if (value.length === 0) {
value = null;
}
//create a new object for line number
if (key in obj) {
objArray.push(obj);
obj = {};
}
obj[key] = value;
}
objArray.push(obj);
claimLineObj.data = objArray;
return claimLineObj;
}
|
[
"function",
"processClaimsLineChild",
"(",
"objectString",
")",
"{",
"var",
"claimLineObj",
"=",
"{",
"}",
";",
"var",
"obj",
"=",
"{",
"}",
";",
"var",
"objArray",
"=",
"[",
"]",
";",
"var",
"keyValuePairRegExp",
"=",
"/",
"(\\n){1,}[\\S\\s,]+?(:)[\\S\\s]+?(?=((\\n){1,})|$)",
"/",
"gi",
";",
"var",
"keyValuePairArray",
"=",
"objectString",
".",
"match",
"(",
"keyValuePairRegExp",
")",
";",
"//unusual steps are required to parse meta data and claims summary",
"for",
"(",
"var",
"s",
"=",
"0",
";",
"s",
"<",
"keyValuePairArray",
".",
"length",
";",
"s",
"++",
")",
"{",
"//clean up the key value pair",
"var",
"keyValuePairString",
"=",
"trimStringEnds",
"(",
"keyValuePairArray",
"[",
"s",
"]",
",",
"[",
"'\\n'",
"]",
")",
";",
"//split each string by the :, the result is an array of size two",
"var",
"keyValuePair",
"=",
"keyValuePairString",
".",
"split",
"(",
"/",
":(.*)",
"/",
")",
";",
"var",
"key",
"=",
"removeUnwantedCharacters",
"(",
"keyValuePair",
"[",
"0",
"]",
".",
"trim",
"(",
")",
",",
"[",
"'\\n'",
",",
"'-'",
"]",
")",
";",
"key",
"=",
"key",
".",
"toLowerCase",
"(",
")",
";",
"var",
"value",
"=",
"keyValuePair",
"[",
"1",
"]",
".",
"trim",
"(",
")",
";",
"var",
"claimLineCheckRegExp",
"=",
"/",
"claim lines",
"/",
"i",
";",
"if",
"(",
"claimLineCheckRegExp",
".",
"test",
"(",
"key",
")",
")",
"{",
"claimLineObj",
".",
"claimNumber",
"=",
"value",
";",
"continue",
";",
"}",
"if",
"(",
"value",
".",
"length",
"===",
"0",
")",
"{",
"value",
"=",
"null",
";",
"}",
"//create a new object for line number",
"if",
"(",
"key",
"in",
"obj",
")",
"{",
"objArray",
".",
"push",
"(",
"obj",
")",
";",
"obj",
"=",
"{",
"}",
";",
"}",
"obj",
"[",
"key",
"]",
"=",
"value",
";",
"}",
"objArray",
".",
"push",
"(",
"obj",
")",
";",
"claimLineObj",
".",
"data",
"=",
"objArray",
";",
"return",
"claimLineObj",
";",
"}"
] |
function to process claim section of the document
|
[
"function",
"to",
"process",
"claim",
"section",
"of",
"the",
"document"
] |
749b8cf071910b22f8176a9ed8fc3b05062e1aad
|
https://github.com/amida-tech/blue-button-cms/blob/749b8cf071910b22f8176a9ed8fc3b05062e1aad/lib/cmsTxtToIntObj.js#L189-L225
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.